-
Notifications
You must be signed in to change notification settings - Fork 72
/
lpms_ffmpeg.c
1530 lines (1335 loc) · 53.5 KB
/
lpms_ffmpeg.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
#include "lpms_ffmpeg.h"
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavfilter/avfilter.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
// Not great to appropriate internal API like this...
const int lpms_ERR_INPUT_PIXFMT = FFERRTAG('I','N','P','X');
const int lpms_ERR_INPUT_CODEC = FFERRTAG('I','N','P','C');
const int lpms_ERR_FILTERS = FFERRTAG('F','L','T','R');
const int lpms_ERR_PACKET_ONLY = FFERRTAG('P','K','O','N');
const int lpms_ERR_OUTPUTS = FFERRTAG('O','U','T','P');
const int lpms_ERR_DTS = FFERRTAG('-','D','T','S');
//
// Notes on transcoder internals:
//
// Transcoding follows the typical process of the FFmpeg API:
// read/demux/decode/filter/encode/mux/write
//
// This is done over discrete segments. However, decode/filter/encoder are
// expensive to re-initialize for every segment. We work around this by
// persisting these components across segments.
//
// The challenge with persistence is there is often internal data that is
// buffered, and there isn't an explicit API to flush or drain that data
// short of re-initializing the component. This is addressed for each component
// as follows:
//
// Decoder: For audio, we pay the price of closing and re-opening the decoder.
// For video, we cache the first packet we read (input_ctx.first_pkt).
// The pts is set to a sentinel value and fed to the decoder. Once we
// receive all frames from the decoder OR have sent too many sentinel
// pkts without receiving anything, then we know the decoder has been
// fully flushed.
//
// Filter: The challenge here is around fps filter adding and dropping frames.
// The fps filter expects a strictly monotonic input pts: frames with
// earlier timestamps get dropped, and frames with too-late timestamps
// will see a bunch of duplicated frames be generated to catch up with
// the timestamp that was just inserted. So we cache the last seen
// frame, rewrite the PTS based on the expected duration, and set a
// sentinel field (AVFrame.opaque). Then do a lot of rewriting to
// accommodate changes. See the notes in the filter_ctx struct and the
// process_out function. This is done for both audio and video.
//
// One consequence of this behavior is that we currently cannot
// process segments out of order, due to the monotonicity requirement.
//
// Encoder: For software encoding, we close the encoder and re-open.
// For Nvidia encoding, there is luckily an API available via
// avcodec_flush_buffers to flush the encoder.
//
//
// Internal transcoder data structures
//
struct input_ctx {
AVFormatContext *ic; // demuxer required
AVCodecContext *vc; // video decoder optional
AVCodecContext *ac; // audo decoder optional
int vi, ai; // video and audio stream indices
int dv, da; // flags whether to drop video or audio
// Hardware decoding support
AVBufferRef *hw_device_ctx;
enum AVHWDeviceType hw_type;
char *device;
// Decoder flush
AVPacket *first_pkt;
int flushed;
int flushing;
// The diff of `packets sent - frames recv` serves as an estimate of
// internally buffered packets by the decoder. We're done flushing when this
// becomes 0.
uint16_t pkt_diff;
// We maintain a count of sentinel packets sent without receiving any
// valid frames back, and stop flushing if it crosses SENTINEL_MAX.
// FIXME This is needed due to issue #155 - input/output frame mismatch.
#define SENTINEL_MAX 5
uint16_t sentinel_count;
// Filter flush
AVFrame *last_frame_v, *last_frame_a;
};
struct filter_ctx {
int active;
AVFilterGraph *graph;
AVFrame *frame;
AVFilterContext *sink_ctx;
AVFilterContext *src_ctx;
uint8_t *hwframes; // GPU frame pool data
// When draining the filtergraph, we inject fake frames.
// These frames need monotonically increasing timestamps at
// approximately the same interval as a normal stream of frames.
// In order to continue using the filter after flushing, we need
// to do two things:
// Adjust input timestamps forward to match the expected cumulative offset
// ( otherwise filter will drop frames <= current pts )
// Re-adjust output timestamps backwards to compensate for the offset
// ( pts received from filter will be wrong by however many flushed
// frames received )
// the cumulative offset effect of flushing
int64_t flush_offset;
int flushed, flush_count;
};
struct output_ctx {
char *fname; // required output file name
char *vfilters; // required output video filters
int width, height, bitrate; // w, h, br required
AVRational fps;
AVFormatContext *oc; // muxer required
AVCodecContext *vc; // video decoder optional
AVCodecContext *ac; // audo decoder optional
int vi, ai; // video and audio stream indices
int dv, da; // flags whether to drop video or audio
struct filter_ctx vf, af;
// Optional hardware encoding support
enum AVHWDeviceType hw_type;
// muxer and encoder information (name + options)
component_opts *muxer;
component_opts *video;
component_opts *audio;
int64_t drop_ts; // preroll audio ts to drop
output_results *res; // data to return for this output
};
#define MAX_OUTPUT_SIZE 10
struct transcode_thread {
int initialized;
struct input_ctx ictx;
struct output_ctx outputs[MAX_OUTPUT_SIZE];
int nb_outputs;
};
void lpms_init()
{
av_log_set_level(AV_LOG_WARNING);
}
//
// Segmenter
//
int lpms_rtmp2hls(char *listen, char *outf, char *ts_tmpl, char* seg_time, char *seg_start)
{
#define r2h_err(str) {\
if (!ret) ret = 1; \
errstr = str; \
goto handle_r2h_err; \
}
char *errstr = NULL;
int ret = 0;
AVFormatContext *ic = NULL;
AVFormatContext *oc = NULL;
AVOutputFormat *ofmt = NULL;
AVStream *ist = NULL;
AVStream *ost = NULL;
AVDictionary *md = NULL;
AVCodec *codec = NULL;
int64_t prev_ts[2] = {AV_NOPTS_VALUE, AV_NOPTS_VALUE};
int stream_map[2] = {-1, -1};
int got_video_kf = 0;
AVPacket pkt;
ret = avformat_open_input(&ic, listen, NULL, NULL);
if (ret < 0) r2h_err("segmenter: Unable to open input\n");
ret = avformat_find_stream_info(ic, NULL);
if (ret < 0) r2h_err("segmenter: Unable to find any input streams\n");
ofmt = av_guess_format(NULL, outf, NULL);
if (!ofmt) r2h_err("Could not deduce output format from file extension\n");
ret = avformat_alloc_output_context2(&oc, ofmt, NULL, outf);
if (ret < 0) r2h_err("Unable to allocate output context\n");
// XXX accommodate cases where audio or video is empty
stream_map[0] = av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);
if (stream_map[0] < 0) r2h_err("segmenter: Unable to find video stream\n");
stream_map[1] = av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
if (stream_map[1] < 0) r2h_err("segmenter: Unable to find audio stream\n");
ist = ic->streams[stream_map[0]];
ost = avformat_new_stream(oc, NULL);
if (!ost) r2h_err("segmenter: Unable to allocate output video stream\n");
avcodec_parameters_copy(ost->codecpar, ist->codecpar);
ist = ic->streams[stream_map[1]];
ost = avformat_new_stream(oc, NULL);
if (!ost) r2h_err("segmenter: Unable to allocate output audio stream\n");
avcodec_parameters_copy(ost->codecpar, ist->codecpar);
av_dict_set(&md, "hls_time", seg_time, 0);
av_dict_set(&md, "hls_segment_filename", ts_tmpl, 0);
av_dict_set(&md, "start_number", seg_start, 0);
av_dict_set(&md, "hls_flags", "delete_segments", 0);
ret = avformat_write_header(oc, &md);
if (ret < 0) r2h_err("Error writing header\n");
av_init_packet(&pkt);
while (1) {
ret = av_read_frame(ic, &pkt);
if (ret == AVERROR_EOF) {
av_interleaved_write_frame(oc, NULL); // flush
break;
} else if (ret < 0) r2h_err("Error reading\n");
// rescale timestamps
if (pkt.stream_index == stream_map[0]) pkt.stream_index = 0;
else if (pkt.stream_index == stream_map[1]) pkt.stream_index = 1;
else goto r2hloop_end;
ist = ic->streams[stream_map[pkt.stream_index]];
ost = oc->streams[pkt.stream_index];
int64_t dts_next = pkt.dts, dts_prev = prev_ts[pkt.stream_index];
if (oc->streams[pkt.stream_index]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
AV_NOPTS_VALUE == dts_prev &&
(pkt.flags & AV_PKT_FLAG_KEY)) got_video_kf = 1;
if (!got_video_kf) goto r2hloop_end; // skip everyting until first video KF
if (AV_NOPTS_VALUE == dts_prev) dts_prev = dts_next;
else if (dts_next <= dts_prev) goto r2hloop_end; // drop late packets
pkt.pts = av_rescale_q_rnd(pkt.pts, ist->time_base, ost->time_base,
AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
pkt.dts = av_rescale_q_rnd(pkt.dts, ist->time_base, ost->time_base,
AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
if (!pkt.duration) pkt.duration = dts_next - dts_prev;
pkt.duration = av_rescale_q(pkt.duration, ist->time_base, ost->time_base);
prev_ts[pkt.stream_index] = dts_next;
// write the thing
ret = av_interleaved_write_frame(oc, &pkt);
if (ret < 0) r2h_err("segmenter: Unable to write output frame\n");
r2hloop_end:
av_packet_unref(&pkt);
}
ret = av_write_trailer(oc);
if (ret < 0) r2h_err("segmenter: Unable to write trailer\n");
handle_r2h_err:
if (errstr) fprintf(stderr, "%s", errstr);
if (ic) avformat_close_input(&ic);
if (oc) avformat_free_context(oc);
if (md) av_dict_free(&md);
return ret == AVERROR_EOF ? 0 : ret;
}
//
// Transcoder
//
static void free_filter(struct filter_ctx *filter)
{
if (filter->frame) av_frame_free(&filter->frame);
if (filter->graph) avfilter_graph_free(&filter->graph);
memset(filter, 0, sizeof(struct filter_ctx));
}
static void close_output(struct output_ctx *octx)
{
if (octx->oc) {
if (!(octx->oc->oformat->flags & AVFMT_NOFILE) && octx->oc->pb) {
avio_closep(&octx->oc->pb);
}
avformat_free_context(octx->oc);
octx->oc = NULL;
}
if (octx->vc && AV_HWDEVICE_TYPE_NONE == octx->hw_type) avcodec_free_context(&octx->vc);
if (octx->ac) avcodec_free_context(&octx->ac);
octx->af.flushed = octx->vf.flushed = 0;
}
static void free_output(struct output_ctx *octx) {
close_output(octx);
if (octx->vc) avcodec_free_context(&octx->vc);
free_filter(&octx->vf);
free_filter(&octx->af);
}
static void flush_input(struct input_ctx *ictx) {
AVPacket pkt = {0};
av_init_packet(&pkt);
while (ictx->ic->pb) {
int ret = av_read_frame(ictx->ic, &pkt);
av_packet_unref(&pkt);
if (ret) break;
}
}
static int is_copy(char *encoder) {
return encoder && !strcmp("copy", encoder);
}
static int is_drop(char *encoder) {
return !encoder || !strcmp("drop", encoder) || !strcmp("", encoder);
}
static int needs_decoder(char *encoder) {
// Checks whether the given "encoder" depends on having a decoder.
// Do this by enumerating special cases that do *not* need encoding
return !(is_copy(encoder) || is_drop(encoder));
}
static int is_flush_frame(AVFrame *frame)
{
return -1 == frame->pts;
}
static void send_first_pkt(struct input_ctx *ictx)
{
if (ictx->flushed || !ictx->first_pkt) return;
int ret = avcodec_send_packet(ictx->vc, ictx->first_pkt);
if (ret < 0) {
char errstr[AV_ERROR_MAX_STRING_SIZE];
av_strerror(ret, errstr, sizeof errstr);
fprintf(stderr, "Error sending flush packet : %s\n", errstr);
} else ictx->sentinel_count++;
}
static enum AVPixelFormat hw2pixfmt(AVCodecContext *ctx)
{
const AVCodec *decoder = ctx->codec;
struct input_ctx *params = (struct input_ctx*)ctx->opaque;
for (int i = 0;; i++) {
const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
if (!config) {
fprintf(stderr, "Decoder %s does not support hw decoding\n", decoder->name);
return AV_PIX_FMT_NONE;
}
if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
config->device_type == params->hw_type) {
return config->pix_fmt;
}
}
return AV_PIX_FMT_NONE;
}
static enum AVPixelFormat get_hw_pixfmt(AVCodecContext *vc, const enum AVPixelFormat *pix_fmts)
{
AVHWFramesContext *frames;
int ret;
// XXX Ideally this would be auto initialized by the HW device ctx
// However the initialization doesn't occur in time to set up filters
// So we do it here. Also see avcodec_get_hw_frames_parameters
av_buffer_unref(&vc->hw_frames_ctx);
vc->hw_frames_ctx = av_hwframe_ctx_alloc(vc->hw_device_ctx);
if (!vc->hw_frames_ctx) {
fprintf(stderr, "Unable to allocate hwframe context for decoding\n");
return AV_PIX_FMT_NONE;
}
frames = (AVHWFramesContext*)vc->hw_frames_ctx->data;
frames->format = hw2pixfmt(vc);
frames->sw_format = vc->sw_pix_fmt;
frames->width = vc->width;
frames->height = vc->height;
// May want to allocate extra HW frames if we encounter samples where
// the defaults are insufficient. Raising this increases GPU memory usage
// For now, the defaults seems OK.
//vc->extra_hw_frames = 16 + 1; // H.264 max refs
ret = av_hwframe_ctx_init(vc->hw_frames_ctx);
if (AVERROR(ENOSYS) == ret) ret = lpms_ERR_INPUT_PIXFMT; // most likely
if (ret < 0) {
fprintf(stderr,"Unable to initialize a hardware frame pool\n");
return AV_PIX_FMT_NONE;
}
/*
fprintf(stderr, "selected format: hw %s sw %s\n",
av_get_pix_fmt_name(frames->format), av_get_pix_fmt_name(frames->sw_format));
const enum AVPixelFormat *p;
for (p = pix_fmts; *p != -1; p++) {
fprintf(stderr,"possible format: %s\n", av_get_pix_fmt_name(*p));
}
*/
return frames->format;
}
static int init_video_filters(struct input_ctx *ictx, struct output_ctx *octx)
{
#define filters_err(msg) { \
if (!ret) ret = -1; \
fprintf(stderr, msg); \
goto init_video_filters_cleanup; \
}
char args[512];
int ret = 0;
const AVFilter *buffersrc = avfilter_get_by_name("buffer");
const AVFilter *buffersink = avfilter_get_by_name("buffersink");
AVFilterInOut *outputs = NULL;
AVFilterInOut *inputs = NULL;
AVRational time_base = ictx->ic->streams[ictx->vi]->time_base;
enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_CUDA, AV_PIX_FMT_NONE }; // XXX ensure the encoder allows this
struct filter_ctx *vf = &octx->vf;
char *filters_descr = octx->vfilters;
enum AVPixelFormat in_pix_fmt = ictx->vc->pix_fmt;
// no need for filters with the following conditions
if (vf->active) goto init_video_filters_cleanup; // already initialized
if (!needs_decoder(octx->video->name)) goto init_video_filters_cleanup;
outputs = avfilter_inout_alloc();
inputs = avfilter_inout_alloc();
vf->graph = avfilter_graph_alloc();
if (!outputs || !inputs || !vf->graph) {
ret = AVERROR(ENOMEM);
filters_err("Unble to allocate filters\n");
}
if (ictx->vc->hw_device_ctx) in_pix_fmt = hw2pixfmt(ictx->vc);
/* buffer video source: the decoded frames from the decoder will be inserted here. */
snprintf(args, sizeof args,
"video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
ictx->vc->width, ictx->vc->height, in_pix_fmt,
time_base.num, time_base.den,
ictx->vc->sample_aspect_ratio.num, ictx->vc->sample_aspect_ratio.den);
ret = avfilter_graph_create_filter(&vf->src_ctx, buffersrc,
"in", args, NULL, vf->graph);
if (ret < 0) filters_err("Cannot create video buffer source\n");
if (ictx->vc && ictx->vc->hw_frames_ctx) {
// XXX a bit problematic in that it's set before decoder is fully ready
AVBufferSrcParameters *srcpar = av_buffersrc_parameters_alloc();
srcpar->hw_frames_ctx = ictx->vc->hw_frames_ctx;
vf->hwframes = ictx->vc->hw_frames_ctx->data;
av_buffersrc_parameters_set(vf->src_ctx, srcpar);
av_freep(&srcpar);
}
/* buffer video sink: to terminate the filter chain. */
ret = avfilter_graph_create_filter(&vf->sink_ctx, buffersink,
"out", NULL, NULL, vf->graph);
if (ret < 0) filters_err("Cannot create video buffer sink\n");
ret = av_opt_set_int_list(vf->sink_ctx, "pix_fmts", pix_fmts,
AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
if (ret < 0) filters_err("Cannot set output pixel format\n");
/*
* Set the endpoints for the filter graph. The filter_graph will
* be linked to the graph described by filters_descr.
*/
/*
* The buffer source output must be connected to the input pad of
* the first filter described by filters_descr; since the first
* filter input label is not specified, it is set to "in" by
* default.
*/
outputs->name = av_strdup("in");
outputs->filter_ctx = vf->src_ctx;
outputs->pad_idx = 0;
outputs->next = NULL;
/*
* The buffer sink input must be connected to the output pad of
* the last filter described by filters_descr; since the last
* filter output label is not specified, it is set to "out" by
* default.
*/
inputs->name = av_strdup("out");
inputs->filter_ctx = vf->sink_ctx;
inputs->pad_idx = 0;
inputs->next = NULL;
ret = avfilter_graph_parse_ptr(vf->graph, filters_descr,
&inputs, &outputs, NULL);
if (ret < 0) filters_err("Unable to parse video filters desc\n");
ret = avfilter_graph_config(vf->graph, NULL);
if (ret < 0) filters_err("Unable configure video filtergraph\n");
vf->frame = av_frame_alloc();
if (!vf->frame) filters_err("Unable to allocate video frame\n");
vf->active = 1;
init_video_filters_cleanup:
avfilter_inout_free(&inputs);
avfilter_inout_free(&outputs);
return ret;
#undef filters_err
}
static int init_audio_filters(struct input_ctx *ictx, struct output_ctx *octx)
{
#define af_err(msg) { \
if (!ret) ret = -1; \
fprintf(stderr, msg); \
goto init_audio_filters_cleanup; \
}
int ret = 0;
char args[512];
char filters_descr[256];
const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
AVFilterInOut *outputs = NULL;
AVFilterInOut *inputs = NULL;
struct filter_ctx *af = &octx->af;
AVRational time_base = ictx->ic->streams[ictx->ai]->time_base;
// no need for filters with the following conditions
if (af->active) goto init_audio_filters_cleanup; // already initialized
if (!needs_decoder(octx->audio->name)) goto init_audio_filters_cleanup;
outputs = avfilter_inout_alloc();
inputs = avfilter_inout_alloc();
af->graph = avfilter_graph_alloc();
if (!outputs || !inputs || !af->graph) {
ret = AVERROR(ENOMEM);
af_err("Unble to allocate audio filters\n");
}
/* buffer audio source: the decoded frames from the decoder will be inserted here. */
snprintf(args, sizeof args,
"sample_rate=%d:sample_fmt=%d:channel_layout=0x%"PRIx64":channels=%d:"
"time_base=%d/%d",
ictx->ac->sample_rate, ictx->ac->sample_fmt, ictx->ac->channel_layout,
ictx->ac->channels, time_base.num, time_base.den);
// TODO set sample format and rate based on encoder support,
// rather than hardcoding
snprintf(filters_descr, sizeof filters_descr,
"aformat=sample_fmts=fltp:channel_layouts=stereo:sample_rates=44100");
ret = avfilter_graph_create_filter(&af->src_ctx, buffersrc,
"in", args, NULL, af->graph);
if (ret < 0) af_err("Cannot create audio buffer source\n");
/* buffer audio sink: to terminate the filter chain. */
ret = avfilter_graph_create_filter(&af->sink_ctx, buffersink,
"out", NULL, NULL, af->graph);
if (ret < 0) af_err("Cannot create audio buffer sink\n");
/*
* Set the endpoints for the filter graph. The filter_graph will
* be linked to the graph described by filters_descr.
*/
/*
* The buffer source output must be connected to the input pad of
* the first filter described by filters_descr; since the first
* filter input label is not specified, it is set to "in" by
* default.
*/
outputs->name = av_strdup("in");
outputs->filter_ctx = af->src_ctx;
outputs->pad_idx = 0;
outputs->next = NULL;
/*
* The buffer sink input must be connected to the output pad of
* the last filter described by filters_descr; since the last
* filter output label is not specified, it is set to "out" by
* default.
*/
inputs->name = av_strdup("out");
inputs->filter_ctx = af->sink_ctx;
inputs->pad_idx = 0;
inputs->next = NULL;
ret = avfilter_graph_parse_ptr(af->graph, filters_descr,
&inputs, &outputs, NULL);
if (ret < 0) af_err("Unable to parse audio filters desc\n");
ret = avfilter_graph_config(af->graph, NULL);
if (ret < 0) af_err("Unable configure audio filtergraph\n");
af->frame = av_frame_alloc();
if (!af->frame) af_err("Unable to allocate audio frame\n");
af->active = 1;
init_audio_filters_cleanup:
avfilter_inout_free(&inputs);
avfilter_inout_free(&outputs);
return ret;
#undef af_err
}
static int add_video_stream(struct output_ctx *octx, struct input_ctx *ictx)
{
#define vs_err(msg) { \
if (!ret) ret = -1; \
fprintf(stderr, "Error adding video stream: " msg); \
goto add_video_err; \
}
// video stream to muxer
int ret = 0;
AVStream *st = avformat_new_stream(octx->oc, NULL);
if (!st) vs_err("Unable to alloc video stream\n");
octx->vi = st->index;
st->avg_frame_rate = octx->fps;
if (is_copy(octx->video->name)) {
AVStream *ist = ictx->ic->streams[ictx->vi];
if (ictx->vi < 0 || !ist) vs_err("Input video stream does not exist\n");
st->time_base = ist->time_base;
ret = avcodec_parameters_copy(st->codecpar, ist->codecpar);
if (ret < 0) vs_err("Error copying video params from input stream\n");
// Sometimes the codec tag is wonky for some reason, so correct it
ret = av_codec_get_tag2(octx->oc->oformat->codec_tag, st->codecpar->codec_id, &st->codecpar->codec_tag);
avformat_transfer_internal_stream_timing_info(octx->oc->oformat, st, ist, AVFMT_TBCF_DEMUXER);
} else if (octx->vc) {
st->time_base = octx->vc->time_base;
ret = avcodec_parameters_from_context(st->codecpar, octx->vc);
if (ret < 0) vs_err("Error setting video params from encoder\n");
} else vs_err("No video encoder, not a copy; what is this?\n");
return 0;
add_video_err:
// XXX free anything here?
return ret;
#undef vs_err
}
static int add_audio_stream(struct input_ctx *ictx, struct output_ctx *octx)
{
#define as_err(msg) { \
if (!ret) ret = -1; \
fprintf(stderr, "Error adding audio stream: " msg); \
goto add_audio_err; \
}
if (ictx->ai < 0 || octx->da) {
// Don't need to add an audio stream if no input audio exists,
// or we're dropping the output audio stream
return 0;
}
// audio stream to muxer
int ret = 0;
AVStream *st = avformat_new_stream(octx->oc, NULL);
if (!st) as_err("Unable to alloc audio stream\n");
if (is_copy(octx->audio->name)) {
AVStream *ist = ictx->ic->streams[ictx->ai];
if (ictx->ai < 0 || !ist) as_err("Input audio stream does not exist\n");
st->time_base = ist->time_base;
ret = avcodec_parameters_copy(st->codecpar, ist->codecpar);
if (ret < 0) as_err("Error copying audio params from input stream\n");
// Sometimes the codec tag is wonky for some reason, so correct it
ret = av_codec_get_tag2(octx->oc->oformat->codec_tag, st->codecpar->codec_id, &st->codecpar->codec_tag);
avformat_transfer_internal_stream_timing_info(octx->oc->oformat, st, ist, AVFMT_TBCF_DEMUXER);
} else if (octx->ac) {
st->time_base = octx->ac->time_base;
ret = avcodec_parameters_from_context(st->codecpar, octx->ac);
if (ret < 0) as_err("Error setting audio params from encoder\n");
} else if (is_drop(octx->audio->name)) {
// Supposed to exit this function early if there's a drop
as_err("Shouldn't ever happen here\n");
} else {
as_err("No audio encoder; not a copy; what is this?\n");
}
octx->ai = st->index;
// signal whether to drop preroll audio
if (st->codecpar->initial_padding) octx->drop_ts = AV_NOPTS_VALUE;
return 0;
add_audio_err:
// XXX free anything here?
return ret;
#undef as_err
}
static int open_audio_output(struct input_ctx *ictx, struct output_ctx *octx,
AVOutputFormat *fmt)
{
#define ao_err(msg) { \
if (!ret) ret = -1; \
fprintf(stderr, msg"\n"); \
goto audio_output_err; \
}
int ret = 0;
AVCodec *codec = NULL;
AVCodecContext *ac = NULL;
// add audio encoder if a decoder exists and this output requires one
if (ictx->ac && needs_decoder(octx->audio->name)) {
// initialize audio filters
ret = init_audio_filters(ictx, octx);
if (ret < 0) ao_err("Unable to open audio filter")
// open encoder
codec = avcodec_find_encoder_by_name(octx->audio->name);
if (!codec) ao_err("Unable to find audio encoder");
// open audio encoder
ac = avcodec_alloc_context3(codec);
if (!ac) ao_err("Unable to alloc audio encoder");
octx->ac = ac;
ac->sample_fmt = av_buffersink_get_format(octx->af.sink_ctx);
ac->channel_layout = av_buffersink_get_channel_layout(octx->af.sink_ctx);
ac->channels = av_buffersink_get_channels(octx->af.sink_ctx);
ac->sample_rate = av_buffersink_get_sample_rate(octx->af.sink_ctx);
ac->time_base = av_buffersink_get_time_base(octx->af.sink_ctx);
if (fmt->flags & AVFMT_GLOBALHEADER) ac->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
ret = avcodec_open2(ac, codec, &octx->audio->opts);
if (ret < 0) ao_err("Error opening audio encoder");
av_buffersink_set_frame_size(octx->af.sink_ctx, ac->frame_size);
}
ret = add_audio_stream(ictx, octx);
if (ret < 0) ao_err("Error adding audio stream")
audio_output_err:
// TODO clean up anything here?
return ret;
#undef ao_err
}
static int open_output(struct output_ctx *octx, struct input_ctx *ictx)
{
#define em_err(msg) { \
if (!ret) ret = -1; \
fprintf(stderr, msg); \
goto open_output_err; \
}
int ret = 0, inp_has_stream;
AVOutputFormat *fmt = NULL;
AVFormatContext *oc = NULL;
AVCodecContext *vc = NULL;
AVCodec *codec = NULL;
// open muxer
fmt = av_guess_format(octx->muxer->name, octx->fname, NULL);
if (!fmt) em_err("Unable to guess output format\n");
ret = avformat_alloc_output_context2(&oc, fmt, NULL, octx->fname);
if (ret < 0) em_err("Unable to alloc output context\n");
octx->oc = oc;
// add video encoder if a decoder exists and this output requires one
if (ictx->vc && needs_decoder(octx->video->name)) {
ret = init_video_filters(ictx, octx);
if (ret < 0) em_err("Unable to open video filter");
codec = avcodec_find_encoder_by_name(octx->video->name);
if (!codec) em_err("Unable to find encoder");
// open video encoder
// XXX use avoptions rather than manual enumeration
vc = avcodec_alloc_context3(codec);
if (!vc) em_err("Unable to alloc video encoder\n");
octx->vc = vc;
vc->width = av_buffersink_get_w(octx->vf.sink_ctx);
vc->height = av_buffersink_get_h(octx->vf.sink_ctx);
if (octx->fps.den) vc->framerate = av_buffersink_get_frame_rate(octx->vf.sink_ctx);
else vc->framerate = ictx->vc->framerate;
if (octx->fps.den) vc->time_base = av_buffersink_get_time_base(octx->vf.sink_ctx);
else if (ictx->vc->time_base.num && ictx->vc->time_base.den) vc->time_base = ictx->vc->time_base;
else vc->time_base = ictx->ic->streams[ictx->vi]->time_base;
if (octx->bitrate) vc->rc_min_rate = vc->rc_max_rate = vc->rc_buffer_size = octx->bitrate;
if (av_buffersink_get_hw_frames_ctx(octx->vf.sink_ctx)) {
vc->hw_frames_ctx =
av_buffer_ref(av_buffersink_get_hw_frames_ctx(octx->vf.sink_ctx));
if (!vc->hw_frames_ctx) em_err("Unable to alloc hardware context\n");
}
vc->pix_fmt = av_buffersink_get_format(octx->vf.sink_ctx); // XXX select based on encoder + input support
if (fmt->flags & AVFMT_GLOBALHEADER) vc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
ret = avcodec_open2(vc, codec, &octx->video->opts);
if (ret < 0) em_err("Error opening video encoder\n");
octx->hw_type = ictx->hw_type;
}
// add video stream if input contains video
inp_has_stream = ictx->vi >= 0;
if (inp_has_stream && !octx->dv) {
ret = add_video_stream(octx, ictx);
if (ret < 0) em_err("Error adding video stream\n");
}
ret = open_audio_output(ictx, octx, fmt);
if (ret < 0) em_err("Error opening audio output\n");
if (!(fmt->flags & AVFMT_NOFILE)) {
ret = avio_open(&octx->oc->pb, octx->fname, AVIO_FLAG_WRITE);
if (ret < 0) em_err("Error opening output file\n");
}
ret = avformat_write_header(oc, &octx->muxer->opts);
if (ret < 0) em_err("Error writing header\n");
return 0;
open_output_err:
free_output(octx);
return ret;
}
static void free_input(struct input_ctx *inctx)
{
if (inctx->ic) avformat_close_input(&inctx->ic);
if (inctx->vc) {
if (inctx->vc->hw_device_ctx) av_buffer_unref(&inctx->vc->hw_device_ctx);
avcodec_free_context(&inctx->vc);
}
if (inctx->ac) avcodec_free_context(&inctx->ac);
if (inctx->hw_device_ctx) av_buffer_unref(&inctx->hw_device_ctx);
if (inctx->last_frame_v) av_frame_free(&inctx->last_frame_v);
if (inctx->last_frame_a) av_frame_free(&inctx->last_frame_a);
}
static int open_video_decoder(input_params *params, struct input_ctx *ctx)
{
#define dd_err(msg) { \
if (!ret) ret = -1; \
fprintf(stderr, msg); \
goto open_decoder_err; \
}
int ret = 0;
AVCodec *codec = NULL;
AVFormatContext *ic = ctx->ic;
// open video decoder
ctx->vi = av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);
if (ctx->dv) ; // skip decoding video
else if (ctx->vi < 0) {
fprintf(stderr, "No video stream found in input\n");
} else {
if (AV_HWDEVICE_TYPE_CUDA == params->hw_type) {
if (AV_CODEC_ID_H264 != codec->id) {
ret = lpms_ERR_INPUT_CODEC;
dd_err("Non H264 codec detected in input\n");
}
AVCodec *c = avcodec_find_decoder_by_name("h264_cuvid");
if (c) codec = c;
else fprintf(stderr, "Cuvid decoder not found; defaulting to software\n");
if (AV_PIX_FMT_YUV420P != ic->streams[ctx->vi]->codecpar->format &&
AV_PIX_FMT_YUVJ420P != ic->streams[ctx->vi]->codecpar->format) {
// TODO check whether the color range is truncated if yuvj420p is used
ret = lpms_ERR_INPUT_PIXFMT;
dd_err("Non 4:2:0 pixel format detected in input\n");
}
}
AVCodecContext *vc = avcodec_alloc_context3(codec);
if (!vc) dd_err("Unable to alloc video codec\n");
ctx->vc = vc;
ret = avcodec_parameters_to_context(vc, ic->streams[ctx->vi]->codecpar);
if (ret < 0) dd_err("Unable to assign video params\n");
vc->opaque = (void*)ctx;
// XXX Could this break if the original device falls out of scope in golang?
if (params->hw_type != AV_HWDEVICE_TYPE_NONE) {
// First set the hw device then set the hw frame
ret = av_hwdevice_ctx_create(&ctx->hw_device_ctx, params->hw_type, params->device, NULL, 0);
if (ret < 0) dd_err("Unable to open hardware context for decoding\n")
ctx->hw_type = params->hw_type;
vc->hw_device_ctx = av_buffer_ref(ctx->hw_device_ctx);
vc->get_format = get_hw_pixfmt;
}
vc->pkt_timebase = ic->streams[ctx->vi]->time_base;
ret = avcodec_open2(vc, codec, NULL);
if (ret < 0) dd_err("Unable to open video decoder\n");
}
return 0;
open_decoder_err:
free_input(ctx);
return ret;
#undef dd_err
}
static int open_audio_decoder(input_params *params, struct input_ctx *ctx)
{
#define ad_err(msg) { \
if (!ret) ret = -1; \
fprintf(stderr, msg); \
goto open_audio_err; \
}
int ret = 0;
AVCodec *codec = NULL;
AVFormatContext *ic = ctx->ic;
// open audio decoder
ctx->ai = av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
if (ctx->da) ; // skip decoding audio
else if (ctx->ai < 0) {
fprintf(stderr, "No audio stream found in input\n");
} else {
AVCodecContext * ac = avcodec_alloc_context3(codec);
if (!ac) ad_err("Unable to alloc audio codec\n");
if (ctx->ac) fprintf(stderr, "Audio context already open! %p\n", ctx->ac);
ctx->ac = ac;
ret = avcodec_parameters_to_context(ac, ic->streams[ctx->ai]->codecpar);
if (ret < 0) ad_err("Unable to assign audio params\n");
ret = avcodec_open2(ac, codec, NULL);
if (ret < 0) ad_err("Unable to open audio decoder\n");
}
return 0;
open_audio_err:
free_input(ctx);
return ret;
#undef ad_err
}
static int open_input(input_params *params, struct input_ctx *ctx)
{
#define dd_err(msg) { \
if (!ret) ret = -1; \
fprintf(stderr, msg); \
goto open_input_err; \
}
AVFormatContext *ic = NULL;
AVIOContext *pb = NULL;
char *inp = params->fname;
int ret = 0;
// open demuxer
ic = avformat_alloc_context();
if (!ic) dd_err("demuxer: Unable to alloc context\n");
ret = avio_open(&pb, inp, AVIO_FLAG_READ);
if (ret < 0) dd_err("demuxer: Unable to open file\n");
ic->pb = pb;
ret = avformat_open_input(&ic, NULL, NULL, NULL);
if (ret < 0) dd_err("demuxer: Unable to open input\n");
ctx->ic = ic;
ret = avformat_find_stream_info(ic, NULL);
if (ret < 0) dd_err("Unable to find input info\n");
ret = open_video_decoder(params, ctx);
if (ret < 0) dd_err("Unable to open video decoder\n")
ret = open_audio_decoder(params, ctx);
if (ret < 0) dd_err("Unable to open audio decoder\n")
ctx->last_frame_v = av_frame_alloc();
if (!ctx->last_frame_v) dd_err("Unable to alloc last_frame_v");
ctx->last_frame_a = av_frame_alloc();
if (!ctx->last_frame_a) dd_err("Unable to alloc last_frame_a");
return 0;
open_input_err:
fprintf(stderr, "Freeing input based on OPEN INPUT error\n");
avio_close(pb); // need to close manually, avformat_open_input
// not closes it in case of error
free_input(ctx);
return ret;
#undef dd_err
}
static int lpms_send_packet(struct input_ctx *ictx, AVCodecContext *dec, AVPacket *pkt)
{
int ret = avcodec_send_packet(dec, pkt);
if (ret == 0 && dec == ictx->vc) ictx->pkt_diff++; // increase buffer count for video packets
return ret;
}
static int lpms_receive_frame(struct input_ctx *ictx, AVCodecContext *dec, AVFrame *frame)
{
int ret = avcodec_receive_frame(dec, frame);
if (dec != ictx->vc) return ret;
if (!ret && frame && !is_flush_frame(frame)) {
ictx->pkt_diff--; // decrease buffer count for non-sentinel video frames
if (ictx->flushing) ictx->sentinel_count = 0;
}
return ret;
}
int process_in(struct input_ctx *ictx, AVFrame *frame, AVPacket *pkt)
{
#define dec_err(msg) { \
if (!ret) ret = -1; \
fprintf(stderr, "dec_cleanup: "msg); \
goto dec_cleanup; \
}
int ret = 0;
// Read a packet and attempt to decode it.
// If decoding was not possible, return the packet anyway for streamcopy
av_init_packet(pkt);
// TODO this while-loop isn't necessary anymore; clean up
while (1) {
AVStream *ist = NULL;