-
Notifications
You must be signed in to change notification settings - Fork 0
/
ffmpeg_av_jni.c
2440 lines (2199 loc) · 91.8 KB
/
ffmpeg_av_jni.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define _GNU_SOURCE
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include <dirent.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
#include <libavcodec/avcodec.h>
#include <libavdevice/avdevice.h>
#include <libavfilter/avfilter.h>
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include "libavutil/channel_layout.h"
#include <libavutil/imgutils.h>
#include <libavutil/time.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
#ifdef __APPLE__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#ifndef OS_WIN32
#include <sys/time.h>
#endif
#ifdef __linux__
#ifndef DONOTHAVEX11
#include <X11/Xlib.h>
#endif
#endif
#include <jni.h>
// ----------- version -----------
// ----------- version -----------
#define VERSION_MAJOR 0
#define VERSION_MINOR 99
#define VERSION_PATCH 26
static const char global_version_string[] = "0.99.26";
static const char global_version_asan_string[] = "0.99.26-ASAN";
// ----------- version -----------
// ----------- version -----------
#define CLEAR(x) memset(&(x), 0, sizeof(x))
#define c_sleep(x) usleep(1000*x)
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
#define min(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
#define CURRENT_LOG_LEVEL 9 // 0 -> error, 1 -> warn, 2 -> info, 9 -> debug
#define MAX_LOG_LINE_LENGTH 1000
#define MAX_FULL_PATH_LENGTH 1000
#ifdef __cplusplus
extern "C" {
#endif
// ############## FIFO ##############
// ############## FIFO ##############
typedef struct {
uint8_t* data;
size_t size;
size_t head;
size_t tail;
} fifo_buffer_t;
fifo_buffer_t* fifo_buffer_create(size_t size) {
fifo_buffer_t* buffer = calloc(1, sizeof(fifo_buffer_t));
buffer->data = (uint8_t *)calloc(1, size);
buffer->size = size;
buffer->head = 0;
buffer->tail = 0;
return buffer;
}
void fifo_buffer_destroy(fifo_buffer_t* buffer) {
free(buffer->data);
free(buffer);
}
size_t fifo_buffer_free(fifo_buffer_t* buffer) {
if ((buffer->tail == buffer->head) && (buffer->head == 0)){
return (buffer->size - 1);
} else {
if (buffer->tail > 0)
{
if (buffer->tail < buffer->head)
{
// move data to beginning of the buffer
memmove(buffer->data, buffer->data + buffer->tail, buffer->head - buffer->tail);
}
buffer->head -= buffer->tail;
buffer->tail = (size_t)0;
}
return buffer->size - buffer->head - 1;
}
}
size_t fifo_buffer_data_available(fifo_buffer_t* buffer) {
if ((buffer->tail == buffer->head) && (buffer->head == (size_t)0)) {
return (size_t)0;
} else {
return buffer->head - buffer->tail;
}
}
size_t fifo_buffer_write(fifo_buffer_t* buffer, const uint8_t* data, size_t size) {
size_t available = fifo_buffer_free(buffer);
if (size > available) {
size = available;
}
memcpy(buffer->data + buffer->head, data, size);
buffer->head += size;
return size;
}
size_t fifo_buffer_read(fifo_buffer_t* buffer, uint8_t* data, size_t size) {
size_t available = fifo_buffer_data_available(buffer);
if (size > available) {
size = available;
}
memcpy(data, buffer->data + buffer->tail, size);
buffer->tail += size;
return size;
}
// ############## FIFO ##############
// ############## FIFO ##############
// ----- JNI stuff -----
JNIEnv *jnienv;
JavaVM *cachedJVM = NULL;
// gives a counter value that increaes every millisecond
static uint64_t ffmpegav_current_time_monotonic_default()
{
uint64_t time = 0;
#ifdef OS_WIN32
/* Must hold mono_time->last_clock_lock here */
/* GetTickCount provides only a 32 bit counter, but we can't use
* GetTickCount64 for backwards compatibility, so we handle wraparound
* ourselves.
*/
uint32_t ticks = GetTickCount();
/* the higher 32 bits count the number of wrap arounds */
uint64_t old_ovf = mono_time->time & ~((uint64_t)UINT32_MAX);
/* Check if time has decreased because of 32 bit wrap from GetTickCount() */
if (ticks < mono_time->last_clock_mono) {
/* account for overflow */
old_ovf += UINT32_MAX + UINT64_C(1);
}
if (mono_time->last_clock_update) {
mono_time->last_clock_mono = ticks;
mono_time->last_clock_update = false;
}
/* splice the low and high bits back together */
time = old_ovf + ticks;
#else
struct timespec clock_mono;
#if defined(__APPLE__)
clock_serv_t muhclock;
mach_timespec_t machtime;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &muhclock);
clock_get_time(muhclock, &machtime);
mach_port_deallocate(mach_task_self(), muhclock);
clock_mono.tv_sec = machtime.tv_sec;
clock_mono.tv_nsec = machtime.tv_nsec;
#else
clock_gettime(CLOCK_MONOTONIC, &clock_mono);
#endif
time = 1000ULL * clock_mono.tv_sec + (clock_mono.tv_nsec / 1000000ULL);
#endif
return time;
}
static size_t ffmpegav_xnet_pack_u16(uint8_t *bytes, uint16_t v)
{
bytes[0] = (v >> 8) & 0xff;
bytes[1] = v & 0xff;
return sizeof(v);
}
static size_t ffmpegav_xnet_pack_u32(uint8_t *bytes, uint32_t v)
{
uint8_t *p = bytes;
p += ffmpegav_xnet_pack_u16(p, (v >> 16) & 0xffff);
p += ffmpegav_xnet_pack_u16(p, v & 0xffff);
return p - bytes;
}
static size_t ffmpegav_xnet_unpack_u16(const uint8_t *bytes, uint16_t *v)
{
uint8_t hi = bytes[0];
uint8_t lo = bytes[1];
*v = ((uint16_t)hi << 8) | lo;
return sizeof(*v);
}
static size_t ffmpegav_xnet_unpack_u32(const uint8_t *bytes, uint32_t *v)
{
const uint8_t *p = bytes;
uint16_t hi;
uint16_t lo;
p += ffmpegav_xnet_unpack_u16(p, &hi);
p += ffmpegav_xnet_unpack_u16(p, &lo);
*v = ((uint32_t)hi << 16) | lo;
return p - bytes;
}
// ------------- JNI -------------
// ------------- JNI -------------
// ------------- JNI -------------
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)
{
JNIEnv *env_this;
cachedJVM = jvm;
if((*jvm)->GetEnv(jvm, (void **) &env_this, JNI_VERSION_1_6))
{
return JNI_ERR;
}
return JNI_VERSION_1_6;
}
JNIEnv *jni_getenv()
{
JNIEnv *env_this;
(*cachedJVM)->GetEnv(cachedJVM, (void **) &env_this, JNI_VERSION_1_6);
return env_this;
}
int java_find_class_global(char *name, jclass *ret)
{
JNIEnv *jnienv2;
jnienv2 = jni_getenv();
*ret = (*jnienv2)->FindClass(jnienv2, name);
if(!*ret)
{
return 0;
}
*ret = (*jnienv2)->NewGlobalRef(jnienv2, *ret);
return 1;
}
jclass AVActivity = NULL;
jclass cls_descrid = NULL;
jmethodID descrid_constr = NULL;
jfieldID descrid_descr = NULL;
jfieldID descrid_id = NULL;
jmethodID callback_video_capture_frame_pts_cb_method = NULL;
jmethodID callback_video_capture_frame_too_small_cb_method = NULL;
jmethodID callback_audio_capture_frame_pts_cb_method = NULL;
jmethodID callback_audio_capture_frame_too_small_cb_method = NULL;
// --------- AV VARS ---------
// --------- AV VARS ---------
// --------- AV VARS ---------
int global_audio_delay_factor = 0;
bool video_device_open = false;
bool audio_device_open = false;
AVInputFormat *inputFormat_audio = NULL;
AVFormatContext *formatContext_audio = NULL;
AVCodecContext *global_audio_codec_ctx = NULL;
AVDictionary *options_audio = NULL;
int audio_stream_index = -1;
AVCodec *audio_codec = NULL;
bool global_audio_in_capture_running = false;
static pthread_t ffmpeg_thread_audio_in_capture;
AVRational time_base_audio = (AVRational) {0, 0};
#define DEFAULT_SCREEN_CAPTURE_PULSE_DEVICE "default"
int apply_audio_filter = 0;
char *resources_dir_path = NULL;
const int resources_dir_path_maxlen = 1000;
AVInputFormat *inputFormat_video = NULL;
AVFormatContext *formatContext_video = NULL;
AVCodecContext *global_video_codec_ctx = NULL;
AVDictionary *options_video = NULL;
int video_stream_index = -1;
AVCodec *video_codec = NULL;
bool global_video_in_capture_running = false;
static pthread_t ffmpeg_thread_video_in_capture;
AVRational time_base_video = (AVRational) {0, 0};
pthread_mutex_t apicalls___mutex;
pthread_mutex_t vsend___mutex;
pthread_mutex_t vscale___mutex;
pthread_mutex_t vbuffer2___mutex;
#define VIDEO_SEND_THREAD_COUNT_MAX 10
int vsend_thread_count = 0;
int sws_scale_algo = SWS_POINT; // SWS_POINT SWS_FAST_BILINEAR SWS_BILINEAR SWS_BICUBIC SWS_SINC SWS_LANCZOS
int output_width = 640;
int output_height = 480;
const int audio_frame_size_ms = 60;
const int out_channels = 1;
const AVChannelLayout chlayout_mono = AV_CHANNEL_LAYOUT_MONO;
const AVChannelLayout chlayout_stereo = AV_CHANNEL_LAYOUT_STEREO;
const int out_bytes_per_sample = 2; // 2 byte per PCM16 sample
const int out_samples = audio_frame_size_ms * 48; // X ms @ 48000Hz
const int out_sample_rate = 48000; // fixed at 48000Hz
const int temp_audio_buf_sizes = 600000; // fixed buffer
uint8_t *video_buffer_1 = NULL;
uint8_t *video_buffer_1_u = NULL;
uint8_t *video_buffer_1_v = NULL;
long video_buffer_1_size = 0;
int video_buffer_1_width = 0;
int video_buffer_1_height = 0;
int video_buffer_1_y_size = 0;
int video_buffer_1_u_size = 0;
int video_buffer_1_v_size = 0;
uint8_t *video_buffer_2 = NULL;
uint8_t *video_buffer_2_u = NULL;
uint8_t *video_buffer_2_v = NULL;
long video_buffer_2_size = 0;
int video_buffer_2_y_size = 0;
int video_buffer_2_u_size = 0;
int video_buffer_2_v_size = 0;
uint8_t *audio_buffer_pcm_1 = NULL;
long audio_buffer_pcm_1_size = 0;
uint8_t *audio_buffer_pcm_2 = NULL;
long audio_buffer_pcm_2_size = 0;
// --------- AV VARS ---------
// --------- AV VARS ---------
// --------- AV VARS ---------
static void reset_video_in_values()
{
inputFormat_video = NULL;
options_video = NULL;
video_stream_index = -1;
}
static void reset_audio_in_values()
{
inputFormat_audio = NULL;
options_audio = NULL;
audio_stream_index = -1;
}
/**
* @brief Delays the execution of the current thread for a specified number of milliseconds.
*
* @param ms The number of milliseconds to delay the execution of the current thread.
*/
static void yieldcpu(uint32_t ms)
{
usleep(1000 * ms);
}
struct vsend_data {
int output_width;
int output_height;
struct SwsContext *scaler_ctx;
AVFrame* frame2;
int source_format;
uint64_t pin_ts_ms;
int estimated_fps;
uint8_t *dst_yuv_buffer[3];
};
static void *thread_v_send_bg_func(void *data)
{
struct vsend_data *vs = (struct vsend_data *) data;
int output_width_local = vs->output_width;
int output_height_local = vs->output_height;
struct SwsContext *scaler_ctx = vs->scaler_ctx;
AVFrame* frame = vs->frame2;
uint64_t pint_ts_ms = vs->pin_ts_ms;
int source_format = vs->source_format;
int estimated_fps = vs->estimated_fps;
// Convert the video frame to YUV
int planes_stride[3];
planes_stride[0] = av_image_get_linesize(AV_PIX_FMT_YUV420P, output_width_local, 0);
planes_stride[1] = av_image_get_linesize(AV_PIX_FMT_YUV420P, output_width_local, 1);
planes_stride[2] = av_image_get_linesize(AV_PIX_FMT_YUV420P, output_width_local, 2);
// fprintf(stderr, "VideoFrame:strides:%d %d %d\n",planes_stride[0],planes_stride[1],planes_stride[2]);
uint8_t *yuv_buffer = (uint8_t *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_YUV420P,
output_width_local, output_height_local, 1));
if (yuv_buffer == NULL) {
fprintf(stderr, "Error: could not allocate YUV buffer\n");
av_frame_unref(frame);
free(vs);
pthread_mutex_lock(&vsend___mutex);
vsend_thread_count--;
if (vsend_thread_count < 0)
{
vsend_thread_count = 0;
}
pthread_mutex_unlock(&vsend___mutex);
return NULL;
}
uint8_t *dst_yuv_buffer[3];
dst_yuv_buffer[0] = yuv_buffer;
dst_yuv_buffer[1] = yuv_buffer + (output_width_local * output_height_local);
dst_yuv_buffer[2] = dst_yuv_buffer[1] + ((output_width_local * output_height_local) / 4);
pthread_mutex_lock(&vscale___mutex);
sws_scale(scaler_ctx, (const uint8_t * const*)frame->data, frame->linesize, 0, global_video_codec_ctx->height,
dst_yuv_buffer, planes_stride);
pthread_mutex_unlock(&vscale___mutex);
JNIEnv *jnienv2 = NULL;
if (jnienv2 == NULL)
{
JavaVMAttachArgs args;
args.version = JNI_VERSION_1_6; // choose your JNI version
args.name = "t_ff_jvcb2"; // you might want to give the java thread a name
args.group = NULL; // you might want to assign the java thread to a ThreadGroup
if (cachedJVM)
{
(*cachedJVM)->AttachCurrentThread(cachedJVM, (void **) &jnienv2, &args);
}
}
pthread_mutex_lock(&vbuffer2___mutex);
if (
(video_buffer_2_y_size >= (planes_stride[0] * output_height_local)) &&
(video_buffer_2_u_size >= (planes_stride[1] * (output_height_local / 2))) &&
(video_buffer_2_v_size >= (planes_stride[2] * (output_height_local / 2)))
)
{
memcpy(video_buffer_2, dst_yuv_buffer[0], planes_stride[0] * output_height_local);
memcpy(video_buffer_2_u, dst_yuv_buffer[1], planes_stride[1] * (output_height_local / 2));
memcpy(video_buffer_2_v, dst_yuv_buffer[2], planes_stride[2] * (output_height_local / 2));
pthread_mutex_unlock(&vbuffer2___mutex);
if (jnienv2 != NULL) {
uint64_t video_frame_age_ms = ffmpegav_current_time_monotonic_default() - pint_ts_ms;
if ((video_frame_age_ms < 1) || (video_frame_age_ms > 300))
{
video_frame_age_ms = 0;
}
(*jnienv2)->CallStaticVoidMethod(jnienv2, AVActivity,
callback_video_capture_frame_pts_cb_method,
(jlong)output_width_local,
(jlong)output_height_local,
(jlong)global_video_codec_ctx->width,
(jlong)global_video_codec_ctx->height,
(jlong)video_frame_age_ms,
(jint)estimated_fps,
(jint)source_format
);
}
else
{
fprintf(stderr, "could not attach thread to JVM [1]\n");
}
}
else
{
pthread_mutex_unlock(&vbuffer2___mutex);
fprintf(stderr, "video buffer too small for video frame data\n");
if (jnienv2 != NULL) {
(*jnienv2)->CallStaticVoidMethod(jnienv2, AVActivity,
callback_video_capture_frame_too_small_cb_method,
(jint)(planes_stride[0] * output_height_local),
(jint)(planes_stride[1] * (output_height_local / 2)),
(jint)(planes_stride[2] * (output_height_local / 2))
);
}
else
{
fprintf(stderr, "could not attach thread to JVM [2]\n");
}
}
av_free(yuv_buffer);
av_frame_unref(frame);
free(vs);
if (cachedJVM)
{
(*cachedJVM)->DetachCurrentThread(cachedJVM);
}
pthread_mutex_lock(&vsend___mutex);
vsend_thread_count--;
if (vsend_thread_count < 0)
{
vsend_thread_count = 0;
}
pthread_mutex_unlock(&vsend___mutex);
return NULL;
}
static void *ffmpeg_thread_video_in_capture_func(void *data)
{
AVPacket packet;
AVFrame *frame = NULL;
int ret = 0;
int estimated_fps = 0;
uint64_t fps_measure_timestamp = 0;
int32_t count_video_frames = 0;
int source_format = -1;
if (global_video_codec_ctx == NULL) {
fprintf(stderr, "video codec is NULL\n");
return NULL;
}
if (inputFormat_video == NULL) {
fprintf(stderr, "inputFormat_video is NULL\n");
return NULL;
}
if (video_stream_index == -1) {
fprintf(stderr, "video_stream_index is -1\n");
return NULL;
}
// Allocate a frame for decoding
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate frame\n");
printf("ffmpeg Video Capture Thread:ERROR:001:thread exit!\n");
return NULL;
}
// Allocate a buffer for the YUV data
int yuv_buffer_bytes_size = av_image_get_buffer_size(AV_PIX_FMT_YUV420P, output_width, output_height, 1);
uint8_t *yuv_buffer = (uint8_t *)av_malloc(yuv_buffer_bytes_size);
if (yuv_buffer == NULL) {
fprintf(stderr, "Error: could not allocate YUV buffer\n");
printf("ffmpeg Video Capture Thread:ERROR:002:thread exit!\n");
av_frame_free(&frame);
return NULL;
}
/*
uint8_t *dst_yuv_buffer[3];
dst_yuv_buffer[0] = yuv_buffer;
dst_yuv_buffer[1] = yuv_buffer + (output_width * output_height);
dst_yuv_buffer[2] = dst_yuv_buffer[1] + ((output_width * output_height) / 4);
*/
if (global_video_codec_ctx->pix_fmt < 0 || global_video_codec_ctx->pix_fmt >= AV_PIX_FMT_NB)
{
printf("pxfmt BAD!!!!!! fmt:%d maxfmt: %d\n", global_video_codec_ctx->pix_fmt, AV_PIX_FMT_NB);
}
else
{
AVPixFmtDescriptor pixfmt_desc = *av_pix_fmt_desc_get(global_video_codec_ctx->pix_fmt);
printf("pxfmt OK fmt: %d fmtname: %s\n", global_video_codec_ctx->pix_fmt, pixfmt_desc.name);
}
// Create a scaler context to convert the video to YUV
struct SwsContext *scaler_ctx = sws_getContext(
global_video_codec_ctx->width,
global_video_codec_ctx->height,
global_video_codec_ctx->pix_fmt, output_width, output_height,
AV_PIX_FMT_YUV420P, sws_scale_algo, NULL, NULL, NULL);
if (scaler_ctx == NULL) {
fprintf(stderr, "Error: could not create scaler context\n");
printf("ffmpeg Video Capture Thread:ERROR:003:thread exit!\n");
av_frame_free(&frame);
av_free(yuv_buffer);
return NULL;
}
fprintf(stderr, "SwsContext: %dx%d -> %dx%d\n",
global_video_codec_ctx->width, global_video_codec_ctx->height, output_width, output_height);
JNIEnv *jnienv2 = NULL;
if (jnienv2 == NULL)
{
JavaVMAttachArgs args;
args.version = JNI_VERSION_1_6; // choose your JNI version
args.name = "t_ff_jvcb"; // you might want to give the java thread a name
args.group = NULL; // you might want to assign the java thread to a ThreadGroup
if (cachedJVM)
{
(*cachedJVM)->AttachCurrentThread(cachedJVM, (void **) &jnienv2, &args);
}
}
source_format = global_video_codec_ctx->codec_id;
fps_measure_timestamp = ffmpegav_current_time_monotonic_default();
while (global_video_in_capture_running == true)
{
if (av_read_frame(formatContext_video, &packet) >= 0)
{
if (packet.stream_index == video_stream_index)
{
// Decode video packet
ret = avcodec_send_packet(global_video_codec_ctx, &packet);
if (ret < 0)
{
fprintf(stderr, "Error sending video packet for decoding\n");
break;
}
while (ret >= 0)
{
ret = avcodec_receive_frame(global_video_codec_ctx, frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
{
break;
}
else if (ret < 0)
{
fprintf(stderr, "Error during video decoding\n");
break;
}
// calculate fps on every 5th video frame ---------------------------------
count_video_frames++;
if (count_video_frames > 4)
{
const uint64_t fps_measure_timestamp_end = ffmpegav_current_time_monotonic_default();
const float delta_ms = (float)(fps_measure_timestamp_end - fps_measure_timestamp);
if ((delta_ms > 1) && (delta_ms < 8000)) {
estimated_fps = (int)(1000.0f / (delta_ms / (float)count_video_frames));
} else {
estimated_fps = 0; // set fps to zero on any errors or issues
}
fps_measure_timestamp = fps_measure_timestamp_end;
count_video_frames = 0;
}
// calculate fps on every 5th video frame ---------------------------------
// --------------------
// --------------------
// ---- Background ----
// --------------------
// --------------------
AVFrame* frame2 = av_frame_clone(frame);
av_frame_unref(frame);
struct vsend_data *vs = malloc(sizeof(struct vsend_data));
vs->output_width = output_width;
vs->output_height = output_height;
vs->scaler_ctx = scaler_ctx;
vs->frame2 = frame2;
vs->source_format = source_format;
vs->pin_ts_ms = ffmpegav_current_time_monotonic_default();
vs->estimated_fps = estimated_fps;
bool vsend_thread_spawn = 1;
pthread_t thread_v_send_bg;
pthread_mutex_lock(&vsend___mutex);
if (vsend_thread_count > VIDEO_SEND_THREAD_COUNT_MAX)
{
vsend_thread_spawn = 0;
}
pthread_mutex_unlock(&vsend___mutex);
if (vsend_thread_spawn == 1)
{
if (pthread_create(&thread_v_send_bg, NULL, thread_v_send_bg_func, (void *)vs) != 0)
{
printf("VSend Thread create failed\n");
av_frame_unref(frame2);
free(vs);
}
else
{
pthread_mutex_lock(&vsend___mutex);
vsend_thread_count++;
// printf("vsend_thread_count:%d\n", vsend_thread_count);
pthread_mutex_unlock(&vsend___mutex);
#ifdef __linux__
pthread_setname_np(thread_v_send_bg, "t_vsend");
#endif
if (pthread_detach(thread_v_send_bg))
{
printf("error detaching VSend Thread\n");
}
}
}
else
{
av_frame_unref(frame2);
free(vs);
}
// --------------------
// --------------------
// ---- Background ----
// --------------------
// --------------------
}
}
av_packet_unref(&packet);
}
// yieldcpu(100);
}
// HINT: wait for all video bg send threads to finish ------------
long loop_count = 0;
const long max_loop_count = 200;
while (true)
{
pthread_mutex_lock(&vsend___mutex);
if (vsend_thread_count < 1)
{
pthread_mutex_unlock(&vsend___mutex);
break;
}
pthread_mutex_unlock(&vsend___mutex);
yieldcpu(2);
loop_count++;
if (loop_count > max_loop_count)
{
fprintf(stderr, "break waiting for video capture threads to finish, vsend_thread_count=%d\n", vsend_thread_count);
break;
}
}
// HINT: wait for all video bg send threads to finish ------------
if (cachedJVM)
{
(*cachedJVM)->DetachCurrentThread(cachedJVM);
}
av_frame_free(&frame);
av_free(yuv_buffer);
sws_freeContext(scaler_ctx);
printf("ffmpeg Video Capture Thread:Clean thread exit!\n");
return NULL;
}
static void *ffmpeg_thread_audio_in_capture_func(void *data)
{
AVPacket packet;
AVFrame *frame = NULL;
AVFrame *oframe = NULL;
int ret = 0;
int num_samples = 0;
int audio_delay_in_bytes = 0;
uint8_t **converted_samples = NULL;
int use_filter = 0;
int filter_init_error = 0;
if (global_audio_codec_ctx == NULL) {
fprintf(stderr, "audio codec is NULL\n");
return NULL;
}
if (inputFormat_audio == NULL) {
fprintf(stderr, "inputFormat_audio is NULL\n");
return NULL;
}
if (audio_stream_index == -1) {
fprintf(stderr, "audio_stream_index is -1\n");
return NULL;
}
// Allocate a frame for decoding
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate frame\n");
printf("ffmpeg Audio Capture Thread:ERROR:001:thread exit!\n");
return NULL;
}
oframe = av_frame_alloc();
if (!oframe) {
fprintf(stderr, "Could not allocate filtered frame\n");
printf("ffmpeg Audio Capture Thread:ERROR:031:thread exit!\n");
return NULL;
}
fprintf(stderr, "AA:audio_codec_ctx->ch_layout numchannels: %d mask: %ld AV_CH_LAYOUT_STEREO: %lld\n",
global_audio_codec_ctx->ch_layout.nb_channels,
global_audio_codec_ctx->ch_layout.u.mask,
(long long)AV_CH_LAYOUT_STEREO);
fprintf(stderr, "AA:audio_codec_ctx->frame_size: %d\n",
formatContext_audio->streams[audio_stream_index]->codecpar->frame_size);
fprintf(stderr, "AA:audio_codec_ctx->sample_rate: %d\n",
formatContext_audio->streams[audio_stream_index]->codecpar->sample_rate);
SwrContext *swr_ctx = NULL;
int opts2_alloc_result = swr_alloc_set_opts2(&swr_ctx,
&chlayout_mono, AV_SAMPLE_FMT_S16, out_sample_rate,
&global_audio_codec_ctx->ch_layout,
formatContext_audio->streams[audio_stream_index]->codecpar->format,
formatContext_audio->streams[audio_stream_index]->codecpar->sample_rate,
0, NULL);
if ((opts2_alloc_result != 0) || (!swr_ctx)) {
fprintf(stderr, "AA:Could not allocate resampler context\n");
fprintf(stderr, "AA:%d %d %d %d %d %d\n", (int)chlayout_mono.nb_channels,
AV_SAMPLE_FMT_S16, out_sample_rate, (int)global_audio_codec_ctx->ch_layout.nb_channels,
global_audio_codec_ctx->sample_fmt, global_audio_codec_ctx->sample_rate);
av_frame_free(&frame);
return NULL;
}
if (swr_init(swr_ctx) < 0) {
fprintf(stderr, "AA:Could not initialize resampler context\n");
fprintf(stderr, "AA:%d %d %d %d %d %d\n", (int)chlayout_mono.nb_channels,
AV_SAMPLE_FMT_S16, out_sample_rate, (int)global_audio_codec_ctx->ch_layout.nb_channels,
global_audio_codec_ctx->sample_fmt, global_audio_codec_ctx->sample_rate);
av_frame_free(&frame);
swr_free(&swr_ctx);
return NULL;
}
fprintf(stderr, "AA:Audio Config:%d %d %d %d %d %d\n", (int)chlayout_mono.nb_channels,
AV_SAMPLE_FMT_S16, out_sample_rate, global_audio_codec_ctx->ch_layout.nb_channels,
global_audio_codec_ctx->sample_fmt, global_audio_codec_ctx->sample_rate);
JNIEnv *jnienv2 = NULL;
if (jnienv2 == NULL)
{
JavaVMAttachArgs args;
args.version = JNI_VERSION_1_6; // choose your JNI version
args.name = "t_ff_jacb"; // you might want to give the java thread a name
args.group = NULL; // you might want to assign the java thread to a ThreadGroup
if (cachedJVM)
{
(*cachedJVM)->AttachCurrentThread(cachedJVM, (void **) &jnienv2, &args);
}
}
fifo_buffer_t* audio_pcm_buffer = fifo_buffer_create(temp_audio_buf_sizes);
// ------------ create filter ------------
AVFilterContext *abuffer_ctx = NULL;
AVFilterContext *aformat_ctx = NULL;
AVFilterContext *abuffersink_ctx = NULL;
AVFilterGraph *filter_graph = NULL;
filter_graph = avfilter_graph_alloc();
if (!filter_graph) {
fprintf(stderr, "ERROR: unable to create filter graph\n");
} else {
// ---------- here is the actual filter ----------
//
// HINT: get filter files from: https://github.com/GregorR/rnnoise-models
//
// bd.rnnn Voice in a reasonable recording environment. Fans, AC, computers, etc.
// cb.rnnn General use in a reasonable recording environment. Fans, AC, computers, etc.
// lq.rnnn Voice in a noisy recording environment.
// mp.rnnn General use in a noisy recording environment.
// sh.rnnn Speech in a reasonable recording environment. Fans, AC, computers, etc.
// Note that "speech" means speech, not other human sounds; laughter, coughing, etc are not included.
//
AVFilter *noisefilter = avfilter_get_by_name("arnndn");
AVFilterContext *noisefilter_ctx = NULL;
static char args_strbuf[1512];
if (resources_dir_path) {
snprintf(args_strbuf, sizeof(args_strbuf), "m=%slq.rnnn", resources_dir_path);
} else {
snprintf(args_strbuf, sizeof(args_strbuf), "m=lq.rnnn");
}
fprintf(stderr, "arnndn filter: %s\n", args_strbuf);
int err_filter = avfilter_graph_create_filter(&noisefilter_ctx, noisefilter, NULL, args_strbuf, NULL, filter_graph);
if (err_filter < 0) {
fprintf(stderr, "ERROR: error initializing noise filter\n");
filter_init_error = 1;
}
// ---------- here is the actual filter ----------
if (filter_init_error == 1)
{
avfilter_graph_free(&filter_graph);
}
else
{
// ---------- abuffer ----------
AVFilter *abuffer = avfilter_get_by_name("abuffer");
const char *channel_str_mono = "mono";
const char *channel_str_stereo = "stereo";
char *channel_str;
if (global_audio_codec_ctx->ch_layout.nb_channels == 1) {
channel_str = channel_str_mono;
} else {
channel_str = channel_str_stereo;
}
memset(args_strbuf, 0, sizeof(args_strbuf));
snprintf(args_strbuf, sizeof(args_strbuf),
"sample_rate=%d:sample_fmt=%s:channel_layout=%s",
global_audio_codec_ctx->sample_rate,
av_get_sample_fmt_name(global_audio_codec_ctx->sample_fmt),
channel_str
);
fprintf(stderr, "abuffer: %s\n", args_strbuf);
int err = avfilter_graph_create_filter(&abuffer_ctx, abuffer, NULL, args_strbuf, NULL, filter_graph);
if (err < 0) {
fprintf(stderr, "ERROR: error initializing abuffer filter\n");
}
// ---------- abuffer ----------
#if 0
// -------- loudnorm 1 filter --------
AVFilter *loudnorm1filter = avfilter_get_by_name("loudnorm");
if (!loudnorm1filter) {
fprintf(stderr, "ERROR: Could not find the loudnorm1 filter\n");
}
AVFilterContext *loudnorm1filter_ctx = NULL;
int err2 = avfilter_graph_create_filter(&loudnorm1filter_ctx, loudnorm1filter, NULL, NULL, NULL, filter_graph);
if (err2 < 0) {
fprintf(stderr, "ERROR: error initializing loudnorm1 filter\n");
}
// -------- loudnorm 1 filter --------
// -------- loudnorm 2 filter --------
AVFilter *loudnorm2filter = avfilter_get_by_name("loudnorm");
if (!loudnorm2filter) {
fprintf(stderr, "ERROR: Could not find the loudnorm2 filter\n");
}
AVFilterContext *loudnorm2filter_ctx = NULL;
int err3 = avfilter_graph_create_filter(&loudnorm2filter_ctx, loudnorm2filter, NULL, NULL, NULL, filter_graph);
if (err3 < 0) {
fprintf(stderr, "ERROR: error initializing loudnorm2 filter\n");
}
// -------- loudnorm 2 filter --------
#endif
// -------- speechnorm filter --------
AVFilter *speechnormfilter = avfilter_get_by_name("speechnorm");
if (!speechnormfilter) {
fprintf(stderr, "ERROR: Could not find the speechnorm filter\n");
}
AVFilterContext *speechnormfilter_ctx = NULL;
static char speechnormfilter_strbuf[512];
snprintf(speechnormfilter_strbuf, sizeof(speechnormfilter_strbuf), "e=20:c=20:l=1");
fprintf(stderr, "volume: %s\n", speechnormfilter_strbuf);
int err4 = avfilter_graph_create_filter(&speechnormfilter_ctx, speechnormfilter, NULL, speechnormfilter_strbuf, NULL, filter_graph);
if (err4 < 0) {
fprintf(stderr, "ERROR: error initializing speechnorm filter\n");
}
// -------- speechnorm filter --------
// -------- volume filter --------
AVFilter *volumefilter = avfilter_get_by_name("volume");
if (!volumefilter) {
fprintf(stderr, "ERROR: Could not find the volume filter\n");
}
AVFilterContext *volumefilter_ctx = NULL;
static char volumefilter_strbuf[512];
// double voln = 2.50;
char *vols = "10dB";
snprintf(volumefilter_strbuf, sizeof(volumefilter_strbuf), "volume=%s", vols);
fprintf(stderr, "volume: %s\n", volumefilter_strbuf);
int err5 = avfilter_graph_create_filter(&volumefilter_ctx, volumefilter, NULL, volumefilter_strbuf, NULL, filter_graph);
if (err5 < 0) {
fprintf(stderr, "ERROR: error initializing volume filter\n");
}
// -------- volume filter --------