-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathavformat.c
3509 lines (2879 loc) · 104 KB
/
avformat.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
/*
* FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
* Copyright (C) 2005-2015, Anthony Minessale II <anthm@freeswitch.org>
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
*
* The Initial Developer of the Original Code is
* Seven Du <dujinfang@gmail.com>
* Portions created by the Initial Developer are Copyright (C)
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Seven Du <dujinfang@gmail.com>
* Anthony Minessale <anthm@freeswitch.org>
* Jakub Karolczyk <jakub.karolczyk@signalwire.com>
*
* mod_avformat -- File Formats with libav.org
*
*/
#include <switch.h>
#include "mod_av.h"
GCC_DIAG_OFF(deprecated-declarations)
#include <libavcodec/avcodec.h>
#ifdef _MSC_VER
#include <libavcodec/version.h> /* LIBAVCODEC_VERSION_INT */
#endif
#include <libavformat/avformat.h>
#ifdef _MSC_VER
#include <libavformat/version.h> /* LIBAVFORMAT_VERSION_INT */
#endif
#include <libavutil/opt.h>
#include <libavutil/imgutils.h>
#include <libavutil/avstring.h>
#include <libavutil/channel_layout.h>
#include <libswscale/swscale.h>
#ifdef USE_AVRESAMPLE
#include <libavresample/avresample.h>
#define SwrContext AVAudioResampleContext
#define swr_alloc avresample_alloc_context
#define swr_init avresample_open
#define swr_free avresample_free
#define swr_get_out_samples avresample_get_out_samples
#define swr_get_out_samples avresample_get_out_samples
#define swr_convert(ctx, odata, osamples, idata, isamples) \
avresample_convert(ctx, odata, 0, osamples, (uint8_t **)idata, 0, isamples)
#else
#include <libswresample/swresample.h>
#endif
#define SLICE_SIZE (SWITCH_DEFAULT_VIDEO_SIZE + 100)
GCC_DIAG_ON(deprecated-declarations)
#define SCALE_FLAGS SWS_BICUBIC
#define DFT_RECORD_OFFSET 0
#ifndef AVUTIL_TIMESTAMP_H
#define AVUTIL_TIMESTAMP_H
#define AV_TS_MAX_STRING_SIZE 32
#define UINTVAL(v) (v > 0 ? v : 0);
// Compatibility with old libav on Debian Jessie
// Not required if libavcodec version > 56.34.1
#ifndef AV_CODEC_FLAG_LOOP_FILTER
#define AV_CODEC_FLAG_LOOP_FILTER CODEC_FLAG_LOOP_FILTER
#define AV_CODEC_FLAG_GLOBAL_HEADER CODEC_FLAG_GLOBAL_HEADER
#define AV_CODEC_CAP_VARIABLE_FRAME_SIZE CODEC_CAP_VARIABLE_FRAME_SIZE
#endif
struct avformat_globals {
enum AVColorSpace colorspace;
};
struct avformat_globals avformat_globals = { 0 };
/* App interface */
// a wrapper around a single output AVStream
typedef struct MediaStream {
AVStream *st;
AVFrame *frame;
AVFrame *tmp_frame;
#if (LIBAVFORMAT_VERSION_MAJOR >= LIBAVFORMAT_V)
AVCodecContext *codec;
#endif
// audio
int channels;
int sample_rate;
struct SwrContext *resample_ctx;
//video
int width;
int height;
struct SwsContext *sws_ctx;
int64_t next_pts;
int active;
int r;
} MediaStream;
typedef struct record_helper_s {
switch_mutex_t *mutex;
AVFormatContext *fc;
MediaStream *video_st;
switch_timer_t *video_timer;
int in_callback;
switch_queue_t *video_queue;
switch_thread_t *video_thread;
switch_mm_t *mm;
int finalize;
switch_file_handle_t *fh;
switch_time_t record_timer_paused;
uint64_t last_ts;
} record_helper_t;
/* file interface */
struct av_file_context {
switch_memory_pool_t *pool;
switch_mutex_t *mutex;
switch_thread_cond_t *cond;
switch_buffer_t *buf;
switch_buffer_t *audio_buffer;
switch_timer_t video_timer;
int offset;
int audio_start;
int aud_ready;
int vid_ready;
int audio_ready;
int closed;
MediaStream video_st;
MediaStream audio_st[2];
AVFormatContext *fc;
#if (LIBAVCODEC_VERSION_MAJOR < LIBAVCODEC_V)
AVCodec *audio_codec;
AVCodec *video_codec;
#else
const AVCodec *audio_codec;
const AVCodec *video_codec;
#endif
enum AVColorSpace colorspace;
int has_audio;
int has_video;
record_helper_t eh;
switch_thread_t *file_read_thread;
int file_read_thread_running;
int file_read_thread_started;
switch_time_t video_start_time;
switch_image_t *last_img;
int read_fps;
switch_time_t last_vid_push;
int64_t seek_ts;
switch_bool_t read_paused;
int errs;
switch_file_handle_t *handle;
int16_t *mux_buf;
switch_size_t mux_buf_len;
switch_time_t last_vid_write;
int audio_timer;
switch_bool_t no_video_decode;
switch_queue_t *video_pkt_queue;
switch_packetizer_t *packetizer;
AVPacket *last_read_pkt;
};
typedef struct av_file_context av_file_context_t;
/**
* Fill the provided buffer with a string containing a timestamp
* representation.
*
* @param buf a buffer with size in bytes of at least AV_TS_MAX_STRING_SIZE
* @param ts the timestamp to represent
* @return the buffer in input
*/
static inline char *av_ts_make_string(char *buf, int64_t ts)
{
if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, "NOPTS");
else snprintf(buf, AV_TS_MAX_STRING_SIZE, "%"PRId64"", ts);
return buf;
}
/**
* Convenience macro, the return value should be used only directly in
* function arguments but never stand-alone.
*/
#define av_ts2str(ts) av_ts_make_string((char[AV_TS_MAX_STRING_SIZE]){0}, ts)
/**
* Fill the provided buffer with a string containing a timestamp time
* representation.
*
* @param buf a buffer with size in bytes of at least AV_TS_MAX_STRING_SIZE
* @param ts the timestamp to represent
* @param tb the timebase of the timestamp
* @return the buffer in input
*/
static inline char *av_ts_make_time_string(char *buf, int64_t ts, AVRational *tb)
{
if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, "NOPTS");
else snprintf(buf, AV_TS_MAX_STRING_SIZE, "%.6g", av_q2d(*tb) * ts);
return buf;
}
/**
* Convenience macro, the return value should be used only directly in
* function arguments but never stand-alone.
*/
#define av_ts2timestr(ts, tb) av_ts_make_time_string((char[AV_TS_MAX_STRING_SIZE]){0}, ts, tb)
#endif /* AVUTIL_TIMESTAMP_H */
static switch_status_t av_file_close(switch_file_handle_t *handle);
SWITCH_MODULE_LOAD_FUNCTION(mod_avformat_load);
static inline AVCodecContext *av_get_codec_context(MediaStream *stream)
{
AVCodecContext *c = NULL;
#if (LIBAVFORMAT_VERSION_MAJOR < LIBAVFORMAT_V)
GCC_DIAG_OFF(deprecated-declarations)
if (stream->st) {
c = stream->st->codec;
}
GCC_DIAG_ON(deprecated-declarations)
#else
c = stream->codec;
#endif
return c;
}
static inline enum AVCodecID av_get_codec_id(AVStream *av_stream)
{
if (!av_stream) {
return AV_CODEC_ID_NONE;
}
#if (LIBAVFORMAT_VERSION_MAJOR < LIBAVFORMAT_V)
GCC_DIAG_OFF(deprecated-declarations)
return av_stream->codec->codec_id;
GCC_DIAG_ON(deprecated-declarations)
#else
return av_stream->codecpar->codec_id;
#endif
}
static inline enum AVMediaType av_get_codec_type(AVStream *av_stream)
{
if (!av_stream) {
return AVMEDIA_TYPE_UNKNOWN;
}
#if (LIBAVFORMAT_VERSION_MAJOR < LIBAVFORMAT_V)
GCC_DIAG_OFF(deprecated-declarations)
return av_stream->codec->codec_type;
GCC_DIAG_ON(deprecated-declarations)
#else
return av_stream->codecpar->codec_type;
#endif
}
static char *const get_error_text(const int error, char *error_buffer, switch_size_t error_buflen)
{
av_strerror(error, error_buffer, error_buflen);
return error_buffer;
}
static void av_unused fill_avframe(AVFrame *pict, switch_image_t *img)
{
int i;
uint8_t *y = img->planes[0];
uint8_t *u = img->planes[1];
uint8_t *v = img->planes[2];
/* Y */
for (i = 0; i < pict->height; i++) {
memcpy(&pict->data[0][i * pict->linesize[0]], y + i * img->stride[0], pict->width);
}
/* U/V */
for(i = 0; i < pict->height / 2; i++) {
memcpy(&pict->data[1][i * pict->linesize[1]], u + i * img->stride[1], pict->width / 2);
memcpy(&pict->data[2][i * pict->linesize[2]], v + i * img->stride[2], pict->width / 2);
}
}
static void av_unused avframe2img(AVFrame *pict, switch_image_t *img)
{
int i, j;
if (img->fmt == SWITCH_IMG_FMT_I420) {
if (pict->format == AV_PIX_FMT_YUV420P) {
switch_I420_copy2(pict->data, pict->linesize, img->planes, img->stride, img->d_w, img->d_h);
} else if (pict->format == AV_PIX_FMT_YUVA420P) {
int linesize[3];
linesize[0] = pict->linesize[0];
linesize[1] = pict->linesize[1];
linesize[2] = pict->linesize[2] + pict->linesize[0];
switch_I420_copy2(pict->data, linesize, img->planes, img->stride, img->d_w, img->d_h);
}
} else if (img->fmt == SWITCH_IMG_FMT_ARGB) {
if (pict->format == AV_PIX_FMT_YUV420P) {
switch_rgb_color_t *color = (switch_rgb_color_t *)img->planes[SWITCH_PLANE_PACKED];
uint8_t *alpha = pict->data[3];
/*!\brief I420 to ARGB Convertion*/
switch_I420ToARGB(pict->data[0], pict->linesize[0],
pict->data[1], pict->linesize[1],
pict->data[2], pict->linesize[2],
img->planes[SWITCH_PLANE_PACKED], img->stride[SWITCH_PLANE_PACKED],
img->d_w, img->d_h);
for (j = 0; j < img->d_h; j++) {
for (i = 0; i < img->d_w; i++) {
color->a = *alpha++;
color++;
}
color = (switch_rgb_color_t *)(img->planes[SWITCH_PLANE_PACKED] + img->stride[SWITCH_PLANE_PACKED] * j);
}
} else if (pict->format == AV_PIX_FMT_RGBA) {
#if SWITCH_BYTE_ORDER == __BIG_ENDIAN
switch_RGBAToARGB(pict->data[0], pict->linesize[0],
mg->planes[SWITCH_PLANE_PACKED], img->stride[SWITCH_PLANE_PACKED],
img->d_w, img->d_h);
#else
switch_ABGRToARGB(pict->data[0], pict->linesize[0],
img->planes[SWITCH_PLANE_PACKED], img->stride[SWITCH_PLANE_PACKED],
img->d_w, img->d_h);
#endif
} else if (pict->format == AV_PIX_FMT_BGRA) {
#if SWITCH_BYTE_ORDER == __BIG_ENDIAN
switch_BGRAToARGB(pict->data[0], pict->linesize[0],
, img->planes[SWITCH_PLANE_PACKED], img->stride[SWITCH_PLANE_PACKED],
, img->d_w, img->d_h);
#else
switch_ARGBToARGB(pict->data[0], pict->linesize[0],
img->planes[SWITCH_PLANE_PACKED], img->stride[SWITCH_PLANE_PACKED],
img->d_w, img->d_h);
#endif
}
}
}
static void av_unused avframe2fd(AVFrame *pict, int fd)
{
int i;
uint8_t *y = pict->data[0];
uint8_t *u = pict->data[1];
uint8_t *v = pict->data[2];
/* Y */
for (i = 0; i < pict->height; i++) {
write(fd, y + i * pict->linesize[0], pict->width);
}
/* U/V */
for(i = 0; i < pict->height / 2; i++) {
write(fd, u + i * pict->linesize[1], pict->width / 2);
}
for(i = 0; i < pict->height / 2; i++) {
write(fd, v + i * pict->linesize[2], pict->width / 2);
}
}
static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt)
{
if (mod_av_globals.debug < 2) return;
{
AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n",
av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, time_base),
av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, time_base),
av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, time_base),
pkt->stream_index);
}
}
static int interrupt_cb(void *cp)
{
av_file_context_t *context = (av_file_context_t *) cp;
if (context->closed) {
return 1;
}
return 0;
}
static int mod_avformat_alloc_output_context2(AVFormatContext **avctx, const char *format, const char *filename, av_file_context_t *context)
{
AVFormatContext *s = avformat_alloc_context();
int ret = 0;
#if (LIBAVFORMAT_VERSION_MAJOR < LIBAVFORMAT_V)
AVOutputFormat *oformat = NULL;
#else
const AVOutputFormat *oformat = NULL;
#endif
s->interrupt_callback.callback = interrupt_cb;
s->interrupt_callback.opaque = context;
*avctx = NULL;
if (!s) {
goto nomem;
}
if (!oformat) {
if (format) {
oformat = av_guess_format(format, NULL, NULL);
if (!oformat) {
av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
ret = AVERROR(EINVAL);
goto error;
}
} else {
oformat = av_guess_format(NULL, filename, NULL);
if (!oformat) {
ret = AVERROR(EINVAL);
av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
filename);
goto error;
}
}
}
s->oformat = oformat;
if (s->oformat->priv_data_size > 0) {
s->priv_data = av_mallocz(s->oformat->priv_data_size);
if (!s->priv_data) {
goto nomem;
}
if (s->oformat->priv_class) {
*(const AVClass**)s->priv_data= s->oformat->priv_class;
av_opt_set_defaults(s->priv_data);
}
} else {
s->priv_data = NULL;
}
if (filename) {
#if (LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58,7,100))
av_strlcpy(s->filename, filename, sizeof(s->filename));
#else
s->url = av_strdup(filename);
switch_assert(s->url);
#endif
}
*avctx = s;
return 0;
nomem:
av_log(s, AV_LOG_ERROR, "Out of memory\n");
ret = AVERROR(ENOMEM);
error:
avformat_free_context(s);
return ret;
}
static int write_frame(AVFormatContext *fmt_ctx, const AVRational *time_base, AVStream *st, AVPacket *pkt)
{
/* rescale output packet timestamp values from codec to stream timebase */
av_packet_rescale_ts(pkt, *time_base, st->time_base);
pkt->stream_index = st->index;
/* Write the compressed frame to the media file. */
log_packet(fmt_ctx, pkt);
return av_interleaved_write_frame(fmt_ctx, pkt);
}
/* Add an output stream. */
#if (LIBAVCODEC_VERSION_MAJOR < LIBAVCODEC_V)
static switch_status_t add_stream(av_file_context_t *context, MediaStream *mst, AVFormatContext *fc, AVCodec **codec, enum AVCodecID codec_id, switch_mm_t *mm)
#else
static switch_status_t add_stream(av_file_context_t *context, MediaStream *mst, AVFormatContext *fc, const AVCodec **codec, enum AVCodecID codec_id, switch_mm_t *mm)
#endif
{
AVCodecContext *c = NULL;
switch_status_t status = SWITCH_STATUS_FALSE;
//int threads = switch_core_cpu_count();
int buffer_bytes = 2097152; /* 2 mb */
int fps = 15;
//if (mm->try_hardware_encoder && codec_id == AV_CODEC_ID_H264) {
// *codec = avcodec_find_encoder_by_name("nvenc_h264");
//}
if (!*codec) {
/* find the encoder */
*codec = avcodec_find_encoder(codec_id);
}
if (!(*codec)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not find encoder\n");
return status;
}
mst->st = avformat_new_stream(fc, *codec);
if (!mst->st) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate stream\n");
return status;
}
mst->st->id = fc->nb_streams - 1;
#if (LIBAVCODEC_VERSION_MAJOR >= LIBAVCODEC_V)
mst->codec = avcodec_alloc_context3(*codec);
if (!mst->codec) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate codec context\n");
return status;
}
#endif
c = av_get_codec_context(mst);
//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "id:%d den:%d num:%d\n", mst->st->id, mst->st->time_base.den, mst->st->time_base.num);
//if (threads > 4) {
// threads = 4;
// }
switch ((*codec)->type) {
case AVMEDIA_TYPE_AUDIO:
c->sample_fmt = (*codec)->sample_fmts ? (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
c->bit_rate = 128000;
c->sample_rate = mst->sample_rate = context->handle->samplerate;
#if (LIBAVCODEC_VERSION_MAJOR < LIBAVCODEC_V)
c->channels = mst->channels;
c->channel_layout = av_get_default_channel_layout(c->channels);
#else
av_channel_layout_default(&c->ch_layout, mst->channels);
#endif
if (mm) {
if (mm->ab) {
c->bit_rate = mm->ab * 1024;
}
if (mm->samplerate) {
c->sample_rate = mst->sample_rate = mm->samplerate;
}
}
if (context && context->has_video && !context->handle->stream_name) {
mst->st->time_base.den = c->sample_rate;
mst->st->time_base.num = 1;
c->time_base.den = c->sample_rate;
c->time_base.num = 1;
} else {
// nothing to do for audio only recording, just leave the time base as is
// switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "stream_timebase: %d/%d codec_timebase: %d/%d nb_samples: %d\n",
// mst->st->time_base.num, mst->st->time_base.den, c->time_base.num, c->time_base.den, c->frame_size);
}
break;
case AVMEDIA_TYPE_VIDEO:
switch_assert(mm);
if (mm->vbuf) {
buffer_bytes = mm->vbuf;
}
if (mm->fps) {
fps = mm->fps;
} else {
mm->fps = fps;
}
if (mm->vw && mm->vh) {
mst->width = mm->vw;
mst->height = mm->vh;
}
c->codec_id = codec_id;
/* Resolution must be a multiple of two. */
c->width = mst->width;
c->height = mst->height;
c->bit_rate = mm->vb * 1024;
mst->st->time_base.den = 90000;
mst->st->time_base.num = 1;
c->time_base.den = 90000;
c->time_base.num = 1;
c->gop_size = fps * 10; /* emit one intra frame every 10 frames at most */
c->pix_fmt = AV_PIX_FMT_YUV420P;
//c->thread_count = threads;
c->rc_initial_buffer_occupancy = buffer_bytes * 8;
if (codec_id == AV_CODEC_ID_H264) {
c->ticks_per_frame = 2;
c->flags|=AV_CODEC_FLAG_LOOP_FILTER; // flags=+loop
c->me_cmp|= 1; // cmp=+chroma, where CHROMA = 1
c->me_range = 16; // me_range=16
c->max_b_frames = 3; // bf=3
av_opt_set_int(c->priv_data, "b_strategy", 1, 0);
//av_opt_set_int(c->priv_data, "motion_est", ME_HEX, 0);
av_opt_set(c->priv_data, "motion_est", "hex", 0);
av_opt_set_int(c->priv_data, "coder", 1, 0);
switch (mm->vprofile) {
case SWITCH_VIDEO_PROFILE_BASELINE:
av_opt_set(c->priv_data, "profile", "baseline", 0);
c->level = 41;
break;
case SWITCH_VIDEO_PROFILE_MAIN:
av_opt_set(c->priv_data, "profile", "main", 0);
av_opt_set(c->priv_data, "level", "5", 0);
c->level = 5;
break;
case SWITCH_VIDEO_PROFILE_HIGH:
av_opt_set(c->priv_data, "profile", "high", 0);
av_opt_set(c->priv_data, "level", "52", 0);
c->level = 52;
break;
}
switch (mm->vencspd) {
case SWITCH_VIDEO_ENCODE_SPEED_SLOW:
av_opt_set(c->priv_data, "preset", "veryslow", 0);
break;
case SWITCH_VIDEO_ENCODE_SPEED_MEDIUM:
av_opt_set(c->priv_data, "preset", "medium", 0);
break;
case SWITCH_VIDEO_ENCODE_SPEED_FAST:
//av_opt_set_int(c->priv_data, "intra-refresh", 1, 0);
av_opt_set(c->priv_data, "preset", "veryfast", 0);
//av_opt_set(c->priv_data, "tune", "animation+zerolatency", 0);
av_opt_set(c->priv_data, "tune", "fastdecode", 0);
break;
default:
break;
}
}
if (mm->cbr) {
c->rc_min_rate = c->bit_rate;
c->rc_max_rate = c->bit_rate;
c->rc_buffer_size = c->bit_rate;
c->qcompress = 0;
c->gop_size = fps * 2;
c->keyint_min = fps * 2;
} else {
c->gop_size = fps * 10;
c->keyint_min = fps;
c->i_quant_factor = 0.71; // i_qfactor=0.71
c->qcompress = 0.6; // qcomp=0.6
c->qmin = 10; // qmin=10
c->qmax = 31; // qmax=31
c->max_qdiff = 4; // qdiff=4
av_opt_set_int(c->priv_data, "crf", 18, 0);
}
if (mm->vb) {
c->bit_rate = mm->vb * 1024;
}
if (mm->keyint) {
c->gop_size = mm->keyint;
}
if (codec_id == AV_CODEC_ID_VP8) {
av_set_options_string(c, "quality=realtime", "=", ":");
}
// av_opt_set_int(c->priv_data, "slice-max-size", SWITCH_DEFAULT_VIDEO_SIZE, 0);
c->colorspace = context->colorspace;
c->color_range = AVCOL_RANGE_JPEG;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "colorspace = %d\n", c->colorspace);
break;
default:
break;
}
/* Some formats want stream headers to be separate. */
if (fc->oformat->flags & AVFMT_GLOBALHEADER) {
c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
mst->active = 1;
return SWITCH_STATUS_SUCCESS;
}
static AVFrame *alloc_picture(enum AVPixelFormat pix_fmt, int width, int height)
{
AVFrame *picture;
int ret;
picture = av_frame_alloc();
if (!picture) return NULL;
picture->format = pix_fmt;
picture->width = width;
picture->height = height;
/* allocate the buffers for the frame data */
ret = av_frame_get_buffer(picture, 32);
if (ret < 0) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate frame data.\n");
return NULL;
}
return picture;
}
#if (LIBAVCODEC_VERSION_MAJOR < LIBAVCODEC_V)
static switch_status_t open_video(AVFormatContext *fc, AVCodec *codec, MediaStream *mst)
#else
static switch_status_t open_video(AVFormatContext *fc, const AVCodec *codec, MediaStream *mst)
#endif
{
int ret;
AVCodecContext *c = NULL;
switch_status_t status = SWITCH_STATUS_FALSE;
//int threads = switch_core_cpu_count();
// if (threads > 4) threads = 4;
// c->thread_count = threads;
c = av_get_codec_context(mst);
/* open the codec */
ret = avcodec_open2(c, codec, NULL);
if (ret < 0) {
char ebuf[255] = "";
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not open video codec: %s\n", get_error_text(ret, ebuf, sizeof(ebuf)));
return status;
}
/* allocate and init a re-usable frame */
mst->frame = alloc_picture(c->pix_fmt, c->width, c->height);
switch_assert(mst->frame);
mst->frame->pts = 0;
// switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "pix_fmt: %d\n", c->pix_fmt);
switch_assert(c->pix_fmt == AV_PIX_FMT_YUV420P); // always I420 for NOW
#if (LIBAVCODEC_VERSION_MAJOR >= LIBAVCODEC_V)
if (((ret = avcodec_parameters_from_context(mst->st->codecpar, mst->codec)) < 0)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not copy to codec params ret=%d\n", ret);
return SWITCH_STATUS_FALSE;
}
#endif
return SWITCH_STATUS_SUCCESS;
}
#if (LIBAVCODEC_VERSION_MAJOR < LIBAVCODEC_V)
static switch_status_t open_audio(AVFormatContext *fc, AVCodec *codec, MediaStream *mst)
#else
static switch_status_t open_audio(AVFormatContext *fc, const AVCodec *codec, MediaStream *mst)
#endif
{
AVCodecContext *c = NULL;
int ret;
switch_status_t status = SWITCH_STATUS_FALSE;
c = av_get_codec_context(mst);
ret = avcodec_open2(c, codec, NULL);
if (ret == AVERROR_EXPERIMENTAL) {
const AVCodecDescriptor *desc = avcodec_descriptor_get(c->codec_id);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Codec [%s] is experimental feature in libavcodec, never mind\n", desc->name);
c->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
ret = avcodec_open2(c, codec, NULL);
}
if (ret < 0) {
const AVCodecDescriptor *desc = avcodec_descriptor_get(c->codec_id);
char ebuf[255] = "";
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not open audio codec [%s], error: %s\n", desc->name, get_error_text(ret, ebuf, sizeof(ebuf)));
return status;
}
mst->frame = av_frame_alloc();
switch_assert(mst->frame);
mst->frame->sample_rate = c->sample_rate;
mst->frame->format = AV_SAMPLE_FMT_S16;
#if (LIBAVCODEC_VERSION_MAJOR < LIBAVCODEC_V)
mst->frame->channel_layout = c->channel_layout;
#else
mst->frame->ch_layout = c->ch_layout;
#endif
if (c->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE) {
//mst->frame->nb_samples = 10000;
#if (LIBAVCODEC_VERSION_MAJOR < LIBAVCODEC_V)
mst->frame->nb_samples = (mst->frame->sample_rate / 50) * c->channels;
#else
mst->frame->nb_samples = (mst->frame->sample_rate / 50) * c->ch_layout.nb_channels;
#endif
} else {
mst->frame->nb_samples = c->frame_size;
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "sample_rate: %d nb_samples: %d\n", mst->frame->sample_rate, mst->frame->nb_samples);
if (c->sample_fmt != AV_SAMPLE_FMT_S16 || c->sample_rate != mst->sample_rate) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "sample_fmt %d != AV_SAMPLE_FMT_S16, start resampler\n", c->sample_fmt);
mst->resample_ctx = swr_alloc();
if (!mst->resample_ctx) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate resampler context\n");
return status;
}
/* set options */
#if (LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59,27,100)) /* FFmpeg 5.0 */
av_opt_set_int(mst->resample_ctx, "in_channel_count", c->channels, 0);
#else /* FFmpeg 5.1 */
av_opt_set_chlayout(mst->resample_ctx, "in_chlayout", &c->ch_layout, 0);
#endif
av_opt_set_int(mst->resample_ctx, "in_sample_rate", c->sample_rate, 0);
#if (LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59,27,100))
av_opt_set_int(mst->resample_ctx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
av_opt_set_int(mst->resample_ctx, "in_channel_layout", c->channel_layout, 0);
av_opt_set_int(mst->resample_ctx, "out_channel_count", c->channels, 0);
#else
av_opt_set_sample_fmt(mst->resample_ctx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
av_opt_set_chlayout(mst->resample_ctx, "out_chlayout", &c->ch_layout, 0);
#endif
av_opt_set_int(mst->resample_ctx, "out_sample_rate", c->sample_rate, 0);
#if (LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(59,27,100))
av_opt_set_int(mst->resample_ctx, "out_sample_fmt", c->sample_fmt, 0);
av_opt_set_int(mst->resample_ctx, "out_channel_layout", c->channel_layout, 0);
#else
av_opt_set_sample_fmt(mst->resample_ctx, "out_sample_fmt", c->sample_fmt, 0);
#endif
if (swr_init(mst->resample_ctx) < 0) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to initialize the resampling context\n");
av_free(mst->resample_ctx);
mst->resample_ctx = NULL;
return status;
}
}
ret = av_frame_get_buffer(mst->frame, 0);
if (ret < 0) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate audio frame.\n");
return status;
}
if (mst->resample_ctx) {
mst->tmp_frame = av_frame_alloc();
switch_assert(mst->tmp_frame);
mst->tmp_frame->sample_rate = c->sample_rate;
mst->tmp_frame->format = c->sample_fmt;
#if (LIBAVCODEC_VERSION_MAJOR < LIBAVCODEC_V)
mst->tmp_frame->channel_layout = c->channel_layout;
#else
mst->tmp_frame->ch_layout = c->ch_layout;
#endif
mst->tmp_frame->nb_samples = mst->frame->nb_samples;
ret = av_frame_get_buffer(mst->tmp_frame, 0);
if (ret < 0) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate audio frame.\n");
return status;
}
}
#if (LIBAVCODEC_VERSION_MAJOR >= LIBAVCODEC_V)
if (((ret = avcodec_parameters_from_context(mst->st->codecpar, mst->codec)) < 0)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not copy to codec params ret=%d\n", ret);
return SWITCH_STATUS_FALSE;
}
#endif
return SWITCH_STATUS_SUCCESS;
}
static int flush_video_queue(switch_queue_t *q, int min)
{
void *pop;
if (switch_queue_size(q) > min) {
while (switch_queue_trypop(q, &pop) == SWITCH_STATUS_SUCCESS) {
switch_image_t *img = (switch_image_t *) pop;
switch_img_free(&img);
if (min && switch_queue_size(q) <= min) {
break;
}
}
}
return switch_queue_size(q);
}
static void flush_video_pkt_queue(switch_queue_t *q)
{
AVPacket *pkt;
while (switch_queue_trypop(q, (void **)&pkt) == SWITCH_STATUS_SUCCESS) {
av_packet_free(&pkt);
}
}
static void *SWITCH_THREAD_FUNC video_thread_run(switch_thread_t *thread, void *obj)
{
av_file_context_t *context = (av_file_context_t *) obj;
void *pop = NULL;
switch_image_t *img = NULL;
int d_w = context->eh.video_st->width, d_h = context->eh.video_st->height;
int size = 0, skip = 0, skip_freq = 0, skip_count = 0, skip_total = 0, skip_total_count = 0;
uint64_t delta_avg = 0, delta_sum = 0, delta_i = 0, delta = 0;
int first = 1;
AVCodecContext *c = NULL;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "video thread start\n");
switch_assert(context->eh.video_queue);
for(;;) {
AVPacket *pkt = NULL;
#if (LIBAVCODEC_VERSION_MAJOR < LIBAVCODEC_V)
int got_packet;
#endif
int ret = -1;
top:
switch_assert(context->eh.video_queue);
while(switch_queue_size(context->eh.video_queue) > 1) {
switch_image_t *tmp_img;
switch_queue_pop(context->eh.video_queue, &pop);
tmp_img = (switch_image_t *) pop;
switch_img_free(&tmp_img);
}
if (switch_queue_pop(context->eh.video_queue, &pop) == SWITCH_STATUS_SUCCESS) {
switch_img_free(&img);
if (!pop) {
goto endfor;
}
img = (switch_image_t *) pop;
if (!d_w) d_w = img->d_w;
if (!d_h) d_h = img->d_h;
if (d_w && d_h && (d_w != img->d_w || d_h != img->d_h)) {
/* scale to match established stream */
switch_img_fit(&img, d_w, d_h, SWITCH_FIT_SIZE);
}
} else {
continue;
}
if (skip) {
if ((skip_total_count > 0 && !--skip_total_count) || ++skip_count >= skip_freq) {
skip_total_count = skip_total;
skip_count = 0;