-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathFFmpegWriter.cpp
2157 lines (1829 loc) · 73 KB
/
FFmpegWriter.cpp
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
/**
* @file
* @brief Source file for FFmpegWriter class
* @author Jonathan Thomas <jonathan@openshot.org>, Fabrice Bellard
*
* @ref License
*/
/* LICENSE
*
* Copyright (c) 2008-2019 OpenShot Studios, LLC, Fabrice Bellard
* (http://www.openshotstudios.com). This file is part of
* OpenShot Library (http://www.openshot.org), an open-source project
* dedicated to delivering high quality video editing and animation solutions
* to the world.
*
* This file is originally based on the Libavformat API example, and then modified
* by the libopenshot project.
*
* OpenShot Library (libopenshot) is free software: you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* OpenShot Library (libopenshot) is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../include/FFmpegWriter.h"
using namespace openshot;
#if IS_FFMPEG_3_2
#pragma message "You are compiling with experimental hardware encode"
#else
#pragma message "You are compiling only with software encode"
#endif
// Multiplexer parameters temporary storage
AVDictionary *mux_dict = NULL;
#if IS_FFMPEG_3_2
int hw_en_on = 1; // Is set in UI
int hw_en_supported = 0; // Is set by FFmpegWriter
AVPixelFormat hw_en_av_pix_fmt = AV_PIX_FMT_NONE;
AVHWDeviceType hw_en_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
static AVBufferRef *hw_device_ctx = NULL;
AVFrame *hw_frame = NULL;
static int set_hwframe_ctx(AVCodecContext *ctx, AVBufferRef *hw_device_ctx, int64_t width, int64_t height)
{
AVBufferRef *hw_frames_ref;
AVHWFramesContext *frames_ctx = NULL;
int err = 0;
if (!(hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx))) {
fprintf(stderr, "Failed to create HW frame context.\n");
return -1;
}
frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
frames_ctx->format = hw_en_av_pix_fmt;
frames_ctx->sw_format = AV_PIX_FMT_NV12;
frames_ctx->width = width;
frames_ctx->height = height;
frames_ctx->initial_pool_size = 20;
if ((err = av_hwframe_ctx_init(hw_frames_ref)) < 0) {
fprintf(stderr, "Failed to initialize HW frame context."
"Error code: %s\n",av_err2str(err));
av_buffer_unref(&hw_frames_ref);
return err;
}
ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
if (!ctx->hw_frames_ctx)
err = AVERROR(ENOMEM);
av_buffer_unref(&hw_frames_ref);
return err;
}
#endif
FFmpegWriter::FFmpegWriter(std::string path) :
path(path), fmt(NULL), oc(NULL), audio_st(NULL), video_st(NULL), audio_pts(0), video_pts(0), samples(NULL),
audio_outbuf(NULL), audio_outbuf_size(0), audio_input_frame_size(0), audio_input_position(0),
initial_audio_input_frame_size(0), img_convert_ctx(NULL), cache_size(8), num_of_rescalers(32),
rescaler_position(0), video_codec(NULL), audio_codec(NULL), is_writing(false), write_video_count(0), write_audio_count(0),
original_sample_rate(0), original_channels(0), avr(NULL), avr_planar(NULL), is_open(false), prepare_streams(false),
write_header(false), write_trailer(false), audio_encoder_buffer_size(0), audio_encoder_buffer(NULL) {
// Disable audio & video (so they can be independently enabled)
info.has_audio = false;
info.has_video = false;
// Initialize FFMpeg, and register all formats and codecs
AV_REGISTER_ALL
// auto detect format
auto_detect_format();
}
// Open the writer
void FFmpegWriter::Open() {
if (!is_open) {
// Open the writer
is_open = true;
// Prepare streams (if needed)
if (!prepare_streams)
PrepareStreams();
// Now that all the parameters are set, we can open the audio and video codecs and allocate the necessary encode buffers
if (info.has_video && video_st)
open_video(oc, video_st);
if (info.has_audio && audio_st)
open_audio(oc, audio_st);
// Write header (if needed)
if (!write_header)
WriteHeader();
}
}
// auto detect format (from path)
void FFmpegWriter::auto_detect_format() {
// Auto detect the output format from the name. default is mpeg.
fmt = av_guess_format(NULL, path.c_str(), NULL);
if (!fmt)
throw InvalidFormat("Could not deduce output format from file extension.", path);
// Allocate the output media context
AV_OUTPUT_CONTEXT(&oc, path.c_str());
if (!oc)
throw OutOfMemory("Could not allocate memory for AVFormatContext.", path);
// Set the AVOutputFormat for the current AVFormatContext
oc->oformat = fmt;
// Update codec names
if (fmt->video_codec != AV_CODEC_ID_NONE && info.has_video)
// Update video codec name
info.vcodec = avcodec_find_encoder(fmt->video_codec)->name;
if (fmt->audio_codec != AV_CODEC_ID_NONE && info.has_audio)
// Update audio codec name
info.acodec = avcodec_find_encoder(fmt->audio_codec)->name;
}
// initialize streams
void FFmpegWriter::initialize_streams() {
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::initialize_streams", "fmt->video_codec", fmt->video_codec, "fmt->audio_codec", fmt->audio_codec, "AV_CODEC_ID_NONE", AV_CODEC_ID_NONE);
// Add the audio and video streams using the default format codecs and initialize the codecs
video_st = NULL;
audio_st = NULL;
if (fmt->video_codec != AV_CODEC_ID_NONE && info.has_video)
// Add video stream
video_st = add_video_stream();
if (fmt->audio_codec != AV_CODEC_ID_NONE && info.has_audio)
// Add audio stream
audio_st = add_audio_stream();
}
// Set video export options
void FFmpegWriter::SetVideoOptions(bool has_video, std::string codec, Fraction fps, int width, int height, Fraction pixel_ratio, bool interlaced, bool top_field_first, int bit_rate) {
// Set the video options
if (codec.length() > 0) {
AVCodec *new_codec;
// Check if the codec selected is a hardware accelerated codec
#if IS_FFMPEG_3_2
#if defined(__linux__)
if (strstr(codec.c_str(), "_vaapi") != NULL) {
new_codec = avcodec_find_encoder_by_name(codec.c_str());
hw_en_on = 1;
hw_en_supported = 1;
hw_en_av_pix_fmt = AV_PIX_FMT_VAAPI;
hw_en_av_device_type = AV_HWDEVICE_TYPE_VAAPI;
} else if (strstr(codec.c_str(), "_nvenc") != NULL) {
new_codec = avcodec_find_encoder_by_name(codec.c_str());
hw_en_on = 1;
hw_en_supported = 1;
hw_en_av_pix_fmt = AV_PIX_FMT_CUDA;
hw_en_av_device_type = AV_HWDEVICE_TYPE_CUDA;
} else {
new_codec = avcodec_find_encoder_by_name(codec.c_str());
hw_en_on = 0;
hw_en_supported = 0;
}
#elif defined(_WIN32)
if (strstr(codec.c_str(), "_dxva2") != NULL) {
new_codec = avcodec_find_encoder_by_name(codec.c_str());
hw_en_on = 1;
hw_en_supported = 1;
hw_en_av_pix_fmt = AV_PIX_FMT_DXVA2_VLD;
hw_en_av_device_type = AV_HWDEVICE_TYPE_DXVA2;
} else if (strstr(codec.c_str(), "_nvenc") != NULL) {
new_codec = avcodec_find_encoder_by_name(codec.c_str());
hw_en_on = 1;
hw_en_supported = 1;
hw_en_av_pix_fmt = AV_PIX_FMT_CUDA;
hw_en_av_device_type = AV_HWDEVICE_TYPE_CUDA;
} else {
new_codec = avcodec_find_encoder_by_name(codec.c_str());
hw_en_on = 0;
hw_en_supported = 0;
}
#elif defined(__APPLE__)
if (strstr(codec.c_str(), "_videotoolbox") != NULL) {
new_codec = avcodec_find_encoder_by_name(codec.c_str());
hw_en_on = 1;
hw_en_supported = 1;
hw_en_av_pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX;
hw_en_av_device_type = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
} else {
new_codec = avcodec_find_encoder_by_name(codec.c_str());
hw_en_on = 0;
hw_en_supported = 0;
}
#else // is FFmpeg 3 but not linux
new_codec = avcodec_find_encoder_by_name(codec.c_str());
#endif //__linux__
#else // not ffmpeg 3
new_codec = avcodec_find_encoder_by_name(codec.c_str());
#endif //IS_FFMPEG_3_2
if (new_codec == NULL)
throw InvalidCodec("A valid video codec could not be found for this file.", path);
else {
// Set video codec
info.vcodec = new_codec->name;
// Update video codec in fmt
fmt->video_codec = new_codec->id;
}
}
if (fps.num > 0) {
// Set frames per second (if provided)
info.fps.num = fps.num;
info.fps.den = fps.den;
// Set the timebase (inverse of fps)
info.video_timebase.num = info.fps.den;
info.video_timebase.den = info.fps.num;
}
if (width >= 1)
info.width = width;
if (height >= 1)
info.height = height;
if (pixel_ratio.num > 0) {
info.pixel_ratio.num = pixel_ratio.num;
info.pixel_ratio.den = pixel_ratio.den;
}
if (bit_rate >= 1000) // bit_rate is the bitrate in b/s
info.video_bit_rate = bit_rate;
if ((bit_rate >= 0) && (bit_rate < 64)) // bit_rate is the bitrate in crf
info.video_bit_rate = bit_rate;
info.interlaced_frame = interlaced;
info.top_field_first = top_field_first;
// Calculate the DAR (display aspect ratio)
Fraction size(info.width * info.pixel_ratio.num, info.height * info.pixel_ratio.den);
// Reduce size fraction
size.Reduce();
// Set the ratio based on the reduced fraction
info.display_ratio.num = size.num;
info.display_ratio.den = size.den;
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::SetVideoOptions (" + codec + ")", "width", width, "height", height, "size.num", size.num, "size.den", size.den, "fps.num", fps.num, "fps.den", fps.den);
// Enable / Disable video
info.has_video = has_video;
}
// Set audio export options
void FFmpegWriter::SetAudioOptions(bool has_audio, std::string codec, int sample_rate, int channels, ChannelLayout channel_layout, int bit_rate) {
// Set audio options
if (codec.length() > 0) {
AVCodec *new_codec = avcodec_find_encoder_by_name(codec.c_str());
if (new_codec == NULL)
throw InvalidCodec("A valid audio codec could not be found for this file.", path);
else {
// Set audio codec
info.acodec = new_codec->name;
// Update audio codec in fmt
fmt->audio_codec = new_codec->id;
}
}
if (sample_rate > 7999)
info.sample_rate = sample_rate;
if (channels > 0)
info.channels = channels;
if (bit_rate > 999)
info.audio_bit_rate = bit_rate;
info.channel_layout = channel_layout;
// init resample options (if zero)
if (original_sample_rate == 0)
original_sample_rate = info.sample_rate;
if (original_channels == 0)
original_channels = info.channels;
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::SetAudioOptions (" + codec + ")", "sample_rate", sample_rate, "channels", channels, "bit_rate", bit_rate);
// Enable / Disable audio
info.has_audio = has_audio;
}
// Set custom options (some codecs accept additional params)
void FFmpegWriter::SetOption(StreamType stream, std::string name, std::string value) {
// Declare codec context
AVCodecContext *c = NULL;
AVStream *st = NULL;
std::stringstream convert(value);
if (info.has_video && stream == VIDEO_STREAM && video_st) {
st = video_st;
// Get codec context
c = AV_GET_CODEC_PAR_CONTEXT(st, video_codec);
} else if (info.has_audio && stream == AUDIO_STREAM && audio_st) {
st = audio_st;
// Get codec context
c = AV_GET_CODEC_PAR_CONTEXT(st, audio_codec);
} else
throw NoStreamsFound("The stream was not found. Be sure to call PrepareStreams() first.", path);
// Init AVOption
const AVOption *option = NULL;
// Was a codec / stream found?
if (c)
// Find AVOption (if it exists)
option = AV_OPTION_FIND(c->priv_data, name.c_str());
// Was option found?
if (option || (name == "g" || name == "qmin" || name == "qmax" || name == "max_b_frames" || name == "mb_decision" ||
name == "level" || name == "profile" || name == "slices" || name == "rc_min_rate" || name == "rc_max_rate" ||
name == "rc_buffer_size" || name == "crf" || name == "cqp")) {
// Check for specific named options
if (name == "g")
// Set gop_size
convert >> c->gop_size;
else if (name == "qmin")
// Minimum quantizer
convert >> c->qmin;
else if (name == "qmax")
// Maximum quantizer
convert >> c->qmax;
else if (name == "max_b_frames")
// Maximum number of B-frames between non-B-frames
convert >> c->max_b_frames;
else if (name == "mb_decision")
// Macroblock decision mode
convert >> c->mb_decision;
else if (name == "level")
// Set codec level
convert >> c->level;
else if (name == "profile")
// Set codec profile
convert >> c->profile;
else if (name == "slices")
// Indicates number of picture subdivisions
convert >> c->slices;
else if (name == "rc_min_rate")
// Minimum bitrate
convert >> c->rc_min_rate;
else if (name == "rc_max_rate")
// Maximum bitrate
convert >> c->rc_max_rate;
else if (name == "rc_buffer_size")
// Buffer size
convert >> c->rc_buffer_size;
else if (name == "cqp") {
// encode quality and special settings like lossless
// This might be better in an extra methods as more options
// and way to set quality are possible
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55, 39, 101)
#if IS_FFMPEG_3_2
if (hw_en_on) {
av_opt_set_int(c->priv_data, "qp", std::min(std::stoi(value),63), 0); // 0-63
} else
#endif
{
switch (c->codec_id) {
#if (LIBAVCODEC_VERSION_MAJOR >= 58)
case AV_CODEC_ID_AV1 :
c->bit_rate = 0;
av_opt_set_int(c->priv_data, "qp", std::min(std::stoi(value),63), 0); // 0-63
break;
#endif
case AV_CODEC_ID_VP8 :
c->bit_rate = 10000000;
av_opt_set_int(c->priv_data, "qp", std::max(std::min(std::stoi(value), 63), 4), 0); // 4-63
break;
case AV_CODEC_ID_VP9 :
c->bit_rate = 0; // Must be zero!
av_opt_set_int(c->priv_data, "qp", std::min(std::stoi(value), 63), 0); // 0-63
if (std::stoi(value) == 0) {
av_opt_set(c->priv_data, "preset", "veryslow", 0);
av_opt_set_int(c->priv_data, "lossless", 1, 0);
}
break;
case AV_CODEC_ID_H264 :
av_opt_set_int(c->priv_data, "qp", std::min(std::stoi(value), 51), 0); // 0-51
if (std::stoi(value) == 0) {
av_opt_set(c->priv_data, "preset", "veryslow", 0);
}
break;
case AV_CODEC_ID_HEVC :
av_opt_set_int(c->priv_data, "qp", std::min(std::stoi(value), 51), 0); // 0-51
if (std::stoi(value) == 0) {
av_opt_set(c->priv_data, "preset", "veryslow", 0);
av_opt_set_int(c->priv_data, "lossless", 1, 0);
}
break;
default:
// For all other codecs assume a range of 0-63
av_opt_set_int(c->priv_data, "qp", std::min(std::stoi(value), 63), 0); // 0-63
c->bit_rate = 0;
}
}
#endif
} else if (name == "crf") {
// encode quality and special settings like lossless
// This might be better in an extra methods as more options
// and way to set quality are possible
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55, 39, 101)
#if IS_FFMPEG_3_2
if (hw_en_on) {
double mbs = 15000000.0;
if (info.video_bit_rate > 0) {
if (info.video_bit_rate > 42) {
mbs = 380000.0;
}
else {
mbs *= std::pow(0.912,info.video_bit_rate);
}
}
c->bit_rate = (int)(mbs);
} else
#endif
{
switch (c->codec_id) {
#if (LIBAVCODEC_VERSION_MAJOR >= 58)
case AV_CODEC_ID_AV1 :
c->bit_rate = 0;
av_opt_set_int(c->priv_data, "crf", std::min(std::stoi(value),63), 0);
break;
#endif
case AV_CODEC_ID_VP8 :
c->bit_rate = 10000000;
av_opt_set_int(c->priv_data, "crf", std::max(std::min(std::stoi(value), 63), 4), 0); // 4-63
break;
case AV_CODEC_ID_VP9 :
c->bit_rate = 0; // Must be zero!
av_opt_set_int(c->priv_data, "crf", std::min(std::stoi(value), 63), 0); // 0-63
if (std::stoi(value) == 0) {
av_opt_set(c->priv_data, "preset", "veryslow", 0);
av_opt_set_int(c->priv_data, "lossless", 1, 0);
}
break;
case AV_CODEC_ID_H264 :
av_opt_set_int(c->priv_data, "crf", std::min(std::stoi(value), 51), 0); // 0-51
if (std::stoi(value) == 0) {
av_opt_set(c->priv_data, "preset", "veryslow", 0);
}
break;
case AV_CODEC_ID_HEVC :
av_opt_set_int(c->priv_data, "crf", std::min(std::stoi(value), 51), 0); // 0-51
if (std::stoi(value) == 0) {
av_opt_set(c->priv_data, "preset", "veryslow", 0);
av_opt_set_int(c->priv_data, "lossless", 1, 0);
}
break;
default:
// If this codec doesn't support crf calculate a bitrate
// TODO: find better formula
double mbs = 15000000.0;
if (info.video_bit_rate > 0) {
if (info.video_bit_rate > 42) {
mbs = 380000.0;
} else {
mbs *= std::pow(0.912, info.video_bit_rate);
}
}
c->bit_rate = (int) (mbs);
}
}
#endif
} else {
// Set AVOption
AV_OPTION_SET(st, c->priv_data, name.c_str(), value.c_str(), c);
}
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::SetOption (" + (std::string)name + ")", "stream == VIDEO_STREAM", stream == VIDEO_STREAM);
// Muxing dictionary is not part of the codec context.
// Just reusing SetOption function to set popular multiplexing presets.
} else if (name == "muxing_preset") {
if (value == "mp4_faststart") {
// 'moov' box to the beginning; only for MOV, MP4
av_dict_set(&mux_dict, "movflags", "faststart", 0);
} else if (value == "mp4_fragmented") {
// write selfcontained fragmented file, minimum length of the fragment 8 sec; only for MOV, MP4
av_dict_set(&mux_dict, "movflags", "frag_keyframe", 0);
av_dict_set(&mux_dict, "min_frag_duration", "8000000", 0);
}
} else {
throw InvalidOptions("The option is not valid for this codec.", path);
}
}
/// Determine if codec name is valid
bool FFmpegWriter::IsValidCodec(std::string codec_name) {
// Initialize FFMpeg, and register all formats and codecs
AV_REGISTER_ALL
// Find the codec (if any)
if (avcodec_find_encoder_by_name(codec_name.c_str()) == NULL)
return false;
else
return true;
}
// Prepare & initialize streams and open codecs
void FFmpegWriter::PrepareStreams() {
if (!info.has_audio && !info.has_video)
throw InvalidOptions("No video or audio options have been set. You must set has_video or has_audio (or both).", path);
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::PrepareStreams [" + path + "]", "info.has_audio", info.has_audio, "info.has_video", info.has_video);
// Initialize the streams (i.e. add the streams)
initialize_streams();
// Mark as 'prepared'
prepare_streams = true;
}
// Write the file header (after the options are set)
void FFmpegWriter::WriteHeader() {
if (!info.has_audio && !info.has_video)
throw InvalidOptions("No video or audio options have been set. You must set has_video or has_audio (or both).", path);
// Open the output file, if needed
if (!(fmt->flags & AVFMT_NOFILE)) {
if (avio_open(&oc->pb, path.c_str(), AVIO_FLAG_WRITE) < 0)
throw InvalidFile("Could not open or write file.", path);
}
// Force the output filename (which doesn't always happen for some reason)
AV_SET_FILENAME(oc, path.c_str());
// Add general metadata (if any)
for (std::map<std::string, std::string>::iterator iter = info.metadata.begin(); iter != info.metadata.end(); ++iter) {
av_dict_set(&oc->metadata, iter->first.c_str(), iter->second.c_str(), 0);
}
// Set multiplexing parameters
AVDictionary *dict = NULL;
bool is_mp4 = strcmp(oc->oformat->name, "mp4");
bool is_mov = strcmp(oc->oformat->name, "mov");
// Set dictionary preset only for MP4 and MOV files
if (is_mp4 || is_mov)
av_dict_copy(&dict, mux_dict, 0);
// Write the stream header
if (avformat_write_header(oc, &dict) != 0) {
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::WriteHeader (avformat_write_header)");
throw InvalidFile("Could not write header to file.", path);
};
// Free multiplexing dictionaries sets
if (dict) av_dict_free(&dict);
if (mux_dict) av_dict_free(&mux_dict);
// Mark as 'written'
write_header = true;
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::WriteHeader");
}
// Add a frame to the queue waiting to be encoded.
void FFmpegWriter::WriteFrame(std::shared_ptr<Frame> frame) {
// Check for open reader (or throw exception)
if (!is_open)
throw WriterClosed("The FFmpegWriter is closed. Call Open() before calling this method.", path);
// Add frame pointer to "queue", waiting to be processed the next
// time the WriteFrames() method is called.
if (info.has_video && video_st)
spooled_video_frames.push_back(frame);
if (info.has_audio && audio_st)
spooled_audio_frames.push_back(frame);
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::WriteFrame", "frame->number", frame->number, "spooled_video_frames.size()", spooled_video_frames.size(), "spooled_audio_frames.size()", spooled_audio_frames.size(), "cache_size", cache_size, "is_writing", is_writing);
// Write the frames once it reaches the correct cache size
if ((int)spooled_video_frames.size() == cache_size || (int)spooled_audio_frames.size() == cache_size) {
// Is writer currently writing?
if (!is_writing)
// Write frames to video file
write_queued_frames();
else {
// Write frames to video file
write_queued_frames();
}
}
// Keep track of the last frame added
last_frame = frame;
}
// Write all frames in the queue to the video file.
void FFmpegWriter::write_queued_frames() {
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::write_queued_frames", "spooled_video_frames.size()", spooled_video_frames.size(), "spooled_audio_frames.size()", spooled_audio_frames.size());
// Flip writing flag
is_writing = true;
// Transfer spool to queue
queued_video_frames = spooled_video_frames;
queued_audio_frames = spooled_audio_frames;
// Empty spool
spooled_video_frames.clear();
spooled_audio_frames.clear();
// Set the number of threads in OpenMP
omp_set_num_threads(OPEN_MP_NUM_PROCESSORS);
// Allow nested OpenMP sections
omp_set_nested(true);
// Create blank exception
bool has_error_encoding_video = false;
#pragma omp parallel
{
#pragma omp single
{
// Process all audio frames (in a separate thread)
if (info.has_audio && audio_st && !queued_audio_frames.empty())
write_audio_packets(false);
// Loop through each queued image frame
while (!queued_video_frames.empty()) {
// Get front frame (from the queue)
std::shared_ptr<Frame> frame = queued_video_frames.front();
// Add to processed queue
processed_frames.push_back(frame);
// Encode and add the frame to the output file
if (info.has_video && video_st)
process_video_packet(frame);
// Remove front item
queued_video_frames.pop_front();
} // end while
} // end omp single
#pragma omp single
{
// Loop back through the frames (in order), and write them to the video file
while (!processed_frames.empty()) {
// Get front frame (from the queue)
std::shared_ptr<Frame> frame = processed_frames.front();
if (info.has_video && video_st) {
// Add to deallocate queue (so we can remove the AVFrames when we are done)
deallocate_frames.push_back(frame);
// Does this frame's AVFrame still exist
if (av_frames.count(frame)) {
// Get AVFrame
AVFrame *frame_final = av_frames[frame];
// Write frame to video file
bool success = write_video_packet(frame, frame_final);
if (!success)
has_error_encoding_video = true;
}
}
// Remove front item
processed_frames.pop_front();
}
// Loop through, and deallocate AVFrames
while (!deallocate_frames.empty()) {
// Get front frame (from the queue)
std::shared_ptr<Frame> frame = deallocate_frames.front();
// Does this frame's AVFrame still exist
if (av_frames.count(frame)) {
// Get AVFrame
AVFrame *av_frame = av_frames[frame];
// Deallocate AVPicture and AVFrame
av_freep(&(av_frame->data[0]));
AV_FREE_FRAME(&av_frame);
av_frames.erase(frame);
}
// Remove front item
deallocate_frames.pop_front();
}
// Done writing
is_writing = false;
} // end omp single
} // end omp parallel
// Raise exception from main thread
if (has_error_encoding_video)
throw ErrorEncodingVideo("Error while writing raw video frame", -1);
}
// Write a block of frames from a reader
void FFmpegWriter::WriteFrame(ReaderBase *reader, int64_t start, int64_t length) {
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::WriteFrame (from Reader)", "start", start, "length", length);
// Loop through each frame (and encoded it)
for (int64_t number = start; number <= length; number++) {
// Get the frame
std::shared_ptr<Frame> f = reader->GetFrame(number);
// Encode frame
WriteFrame(f);
}
}
// Write the file trailer (after all frames are written)
void FFmpegWriter::WriteTrailer() {
// Write any remaining queued frames to video file
write_queued_frames();
// Process final audio frame (if any)
if (info.has_audio && audio_st)
write_audio_packets(true);
// Flush encoders (who sometimes hold on to frames)
flush_encoders();
/* write the trailer, if any. The trailer must be written
* before you close the CodecContexts open when you wrote the
* header; otherwise write_trailer may try to use memory that
* was freed on av_codec_close() */
av_write_trailer(oc);
// Mark as 'written'
write_trailer = true;
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::WriteTrailer");
}
// Flush encoders
void FFmpegWriter::flush_encoders() {
if (info.has_audio && audio_codec && AV_GET_CODEC_TYPE(audio_st) == AVMEDIA_TYPE_AUDIO && AV_GET_CODEC_ATTRIBUTES(audio_st, audio_codec)->frame_size <= 1)
return;
#if (LIBAVFORMAT_VERSION_MAJOR < 58)
if (info.has_video && video_codec && AV_GET_CODEC_TYPE(video_st) == AVMEDIA_TYPE_VIDEO && (oc->oformat->flags & AVFMT_RAWPICTURE) && AV_FIND_DECODER_CODEC_ID(video_st) == AV_CODEC_ID_RAWVIDEO)
return;
#endif
int error_code = 0;
int stop_encoding = 1;
// FLUSH VIDEO ENCODER
if (info.has_video)
for (;;) {
// Increment PTS (in frames and scaled to the codec's timebase)
write_video_count += av_rescale_q(1, (AVRational) {info.fps.den, info.fps.num}, video_codec->time_base);
AVPacket pkt;
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
// Pointer for video buffer (if using old FFmpeg version)
uint8_t *video_outbuf = NULL;
/* encode the image */
int got_packet = 0;
int error_code = 0;
#if IS_FFMPEG_3_2
#pragma omp critical (write_video_packet)
{
// Encode video packet (latest version of FFmpeg)
error_code = avcodec_send_frame(video_codec, NULL);
got_packet = 0;
while (error_code >= 0) {
error_code = avcodec_receive_packet(video_codec, &pkt);
if (error_code == AVERROR(EAGAIN)|| error_code == AVERROR_EOF) {
got_packet = 0;
// Write packet
avcodec_flush_buffers(video_codec);
break;
}
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts = av_rescale_q(pkt.pts, video_codec->time_base, video_st->time_base);
if (pkt.dts != AV_NOPTS_VALUE)
pkt.dts = av_rescale_q(pkt.dts, video_codec->time_base, video_st->time_base);
if (pkt.duration > 0)
pkt.duration = av_rescale_q(pkt.duration, video_codec->time_base, video_st->time_base);
pkt.stream_index = video_st->index;
error_code = av_interleaved_write_frame(oc, &pkt);
}
}
#else // IS_FFMPEG_3_2
#if LIBAVFORMAT_VERSION_MAJOR >= 54
// Encode video packet (older than FFmpeg 3.2)
error_code = avcodec_encode_video2(video_codec, &pkt, NULL, &got_packet);
#else
// Encode video packet (even older version of FFmpeg)
int video_outbuf_size = 0;
/* encode the image */
int out_size = avcodec_encode_video(video_codec, NULL, video_outbuf_size, NULL);
/* if zero size, it means the image was buffered */
if (out_size > 0) {
if(video_codec->coded_frame->key_frame)
pkt.flags |= AV_PKT_FLAG_KEY;
pkt.data= video_outbuf;
pkt.size= out_size;
// got data back (so encode this frame)
got_packet = 1;
}
#endif // LIBAVFORMAT_VERSION_MAJOR >= 54
#endif // IS_FFMPEG_3_2
if (error_code < 0) {
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::flush_encoders ERROR [" + (std::string) av_err2str(error_code) + "]", "error_code", error_code);
}
if (!got_packet) {
stop_encoding = 1;
break;
}
// Override PTS (in frames and scaled to the codec's timebase)
//pkt.pts = write_video_count;
// set the timestamp
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts = av_rescale_q(pkt.pts, video_codec->time_base, video_st->time_base);
if (pkt.dts != AV_NOPTS_VALUE)
pkt.dts = av_rescale_q(pkt.dts, video_codec->time_base, video_st->time_base);
if (pkt.duration > 0)
pkt.duration = av_rescale_q(pkt.duration, video_codec->time_base, video_st->time_base);
pkt.stream_index = video_st->index;
// Write packet
error_code = av_interleaved_write_frame(oc, &pkt);
if (error_code < 0) {
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::flush_encoders ERROR [" + (std::string)av_err2str(error_code) + "]", "error_code", error_code);
}
// Deallocate memory (if needed)
if (video_outbuf)
av_freep(&video_outbuf);
}
// FLUSH AUDIO ENCODER
if (info.has_audio)
for (;;) {
// Increment PTS (in samples and scaled to the codec's timebase)
#if LIBAVFORMAT_VERSION_MAJOR >= 54
// for some reason, it requires me to multiply channels X 2
write_audio_count += av_rescale_q(audio_input_position / (audio_codec->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16)), (AVRational){1, info.sample_rate}, audio_codec->time_base);
#else
write_audio_count += av_rescale_q(audio_input_position / audio_codec->channels, (AVRational){1, info.sample_rate}, audio_codec->time_base);
#endif
AVPacket pkt;
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
pkt.pts = pkt.dts = write_audio_count;
/* encode the image */
int got_packet = 0;
#if IS_FFMPEG_3_2
avcodec_send_frame(audio_codec, NULL);
got_packet = 0;
#else
error_code = avcodec_encode_audio2(audio_codec, &pkt, NULL, &got_packet);
#endif
if (error_code < 0) {
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::flush_encoders ERROR [" + (std::string)av_err2str(error_code) + "]", "error_code", error_code);
}
if (!got_packet) {
stop_encoding = 1;
break;
}
// Since the PTS can change during encoding, set the value again. This seems like a huge hack,
// but it fixes lots of PTS related issues when I do this.
pkt.pts = pkt.dts = write_audio_count;
// Scale the PTS to the audio stream timebase (which is sometimes different than the codec's timebase)
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts = av_rescale_q(pkt.pts, audio_codec->time_base, audio_st->time_base);
if (pkt.dts != AV_NOPTS_VALUE)
pkt.dts = av_rescale_q(pkt.dts, audio_codec->time_base, audio_st->time_base);
if (pkt.duration > 0)
pkt.duration = av_rescale_q(pkt.duration, audio_codec->time_base, audio_st->time_base);
// set stream
pkt.stream_index = audio_st->index;
pkt.flags |= AV_PKT_FLAG_KEY;
// Write packet
error_code = av_interleaved_write_frame(oc, &pkt);
if (error_code < 0) {
ZmqLogger::Instance()->AppendDebugMethod("FFmpegWriter::flush_encoders ERROR [" + (std::string)av_err2str(error_code) + "]", "error_code", error_code);
}
// deallocate memory for packet
AV_FREE_PACKET(&pkt);
}
}
// Close the video codec
void FFmpegWriter::close_video(AVFormatContext *oc, AVStream *st)
{
#if IS_FFMPEG_3_2
// #if defined(__linux__)
if (hw_en_on && hw_en_supported) {
if (hw_device_ctx) {
av_buffer_unref(&hw_device_ctx);
hw_device_ctx = NULL;
}
}
// #endif
#endif
}
// Close the audio codec
void FFmpegWriter::close_audio(AVFormatContext *oc, AVStream *st)
{
// Clear buffers
delete[] samples;
delete[] audio_outbuf;
delete[] audio_encoder_buffer;
samples = NULL;
audio_outbuf = NULL;
audio_encoder_buffer = NULL;
// Deallocate resample buffer
if (avr) {
SWR_CLOSE(avr);
SWR_FREE(&avr);
avr = NULL;
}
if (avr_planar) {
SWR_CLOSE(avr_planar);
SWR_FREE(&avr_planar);
avr_planar = NULL;
}
}
// Close the writer
void FFmpegWriter::Close() {
// Write trailer (if needed)
if (!write_trailer)
WriteTrailer();