42 static AVBufferRef *hw_device_ctx = NULL;
45 static int set_hwframe_ctx(AVCodecContext *ctx, AVBufferRef *hw_device_ctx, int64_t width, int64_t height)
47 AVBufferRef *hw_frames_ref;
48 AVHWFramesContext *frames_ctx = NULL;
51 if (!(hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx))) {
52 std::clog <<
"Failed to create HW frame context.\n";
55 frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
57 frames_ctx->sw_format = AV_PIX_FMT_NV12;
58 frames_ctx->width = width;
59 frames_ctx->height = height;
60 frames_ctx->initial_pool_size = 20;
61 if ((err = av_hwframe_ctx_init(hw_frames_ref)) < 0) {
62 std::clog <<
"Failed to initialize HW frame context. " <<
63 "Error code: " << av_err2string(err) <<
"\n";
64 av_buffer_unref(&hw_frames_ref);
67 ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
68 if (!ctx->hw_frames_ctx)
69 err = AVERROR(ENOMEM);
71 av_buffer_unref(&hw_frames_ref);
74 #endif // USE_HW_ACCEL
77 path(
path), oc(NULL), audio_st(NULL), video_st(NULL), samples(NULL),
78 audio_outbuf(NULL), audio_outbuf_size(0), audio_input_frame_size(0), audio_input_position(0),
79 initial_audio_input_frame_size(0), img_convert_ctx(NULL),
80 video_codec_ctx(NULL), audio_codec_ctx(NULL), is_writing(false), video_timestamp(0), audio_timestamp(0),
81 original_sample_rate(0), original_channels(0), avr(NULL), avr_planar(NULL), is_open(false), prepare_streams(false),
82 write_header(false), write_trailer(false), allow_b_frames(false), audio_encoder_buffer_size(0), audio_encoder_buffer(NULL) {
102 if (!prepare_streams)
107 open_video(oc, video_st);
109 open_audio(oc, audio_st);
118 void FFmpegWriter::auto_detect_format() {
124 "Could not allocate memory for AVFormatContext.", path);
128 oc->oformat = av_guess_format(NULL, path.c_str(), NULL);
129 if (oc->oformat ==
nullptr) {
130 throw InvalidFormat(
"Could not deduce output format from file extension.", path);
134 if (oc->oformat->video_codec != AV_CODEC_ID_NONE &&
info.
has_video) {
135 const AVCodec *vcodec = avcodec_find_encoder(oc->oformat->video_codec);
136 info.
vcodec = vcodec ? vcodec->name : std::string();
138 if (oc->oformat->audio_codec != AV_CODEC_ID_NONE &&
info.
has_audio) {
139 const AVCodec *acodec = avcodec_find_encoder(oc->oformat->audio_codec);
140 info.
acodec = acodec ? acodec->name : std::string();
145 void FFmpegWriter::initialize_streams() {
147 "FFmpegWriter::initialize_streams",
148 "oc->oformat->video_codec", oc->oformat->video_codec,
149 "oc->oformat->audio_codec", oc->oformat->audio_codec,
150 "AV_CODEC_ID_NONE", AV_CODEC_ID_NONE);
155 if (oc->oformat->video_codec != AV_CODEC_ID_NONE &&
info.
has_video)
157 video_st = add_video_stream();
159 if (oc->oformat->audio_codec != AV_CODEC_ID_NONE &&
info.
has_audio)
161 audio_st = add_audio_stream();
167 if (
codec.length() > 0) {
168 const AVCodec *new_codec;
171 #if defined(__linux__)
172 if (strstr(
codec.c_str(),
"_vaapi") != NULL) {
173 new_codec = avcodec_find_encoder_by_name(
codec.c_str());
178 }
else if (strstr(
codec.c_str(),
"_nvenc") != NULL) {
179 new_codec = avcodec_find_encoder_by_name(
codec.c_str());
185 new_codec = avcodec_find_encoder_by_name(
codec.c_str());
189 #elif defined(_WIN32)
190 if (strstr(
codec.c_str(),
"_dxva2") != NULL) {
191 new_codec = avcodec_find_encoder_by_name(
codec.c_str());
196 }
else if (strstr(
codec.c_str(),
"_nvenc") != NULL) {
197 new_codec = avcodec_find_encoder_by_name(
codec.c_str());
203 new_codec = avcodec_find_encoder_by_name(
codec.c_str());
207 #elif defined(__APPLE__)
208 if (strstr(
codec.c_str(),
"_videotoolbox") != NULL) {
209 new_codec = avcodec_find_encoder_by_name(
codec.c_str());
215 new_codec = avcodec_find_encoder_by_name(
codec.c_str());
220 new_codec = avcodec_find_encoder_by_name(
codec.c_str());
221 #endif //__linux__/_WIN32/__APPLE__
222 #else // USE_HW_ACCEL
223 new_codec = avcodec_find_encoder_by_name(
codec.c_str());
224 #endif // USE_HW_ACCEL
225 if (new_codec == NULL)
226 throw InvalidCodec(
"A valid video codec could not be found for this file.", path);
245 if (pixel_ratio.
num > 0) {
249 if (bit_rate >= 1000)
251 if ((bit_rate >= 0) && (bit_rate < 256))
268 "FFmpegWriter::SetVideoOptions (" +
codec +
")",
269 "width", width,
"height", height,
270 "size.num", size.
num,
"size.den", size.
den,
271 "fps.num", fps.
num,
"fps.den", fps.
den);
281 true,
codec, fps, width, height,
290 if (
codec.length() > 0) {
291 const AVCodec *new_codec = avcodec_find_encoder_by_name(
codec.c_str());
292 if (new_codec == NULL)
293 throw InvalidCodec(
"A valid audio codec could not be found for this file.", path);
299 if (sample_rate > 7999)
308 if (original_sample_rate == 0)
310 if (original_channels == 0)
314 "FFmpegWriter::SetAudioOptions (" +
codec +
")",
315 "sample_rate", sample_rate,
316 "channels", channels,
317 "bit_rate", bit_rate);
328 true,
codec, sample_rate, 2,
337 AVCodecContext *c = NULL;
339 std::stringstream convert(value);
358 throw NoStreamsFound(
"The stream was not found. Be sure to call PrepareStreams() first.", path);
361 const AVOption *option = NULL;
369 if (option || (name ==
"g" || name ==
"qmin" || name ==
"qmax" || name ==
"max_b_frames" || name ==
"mb_decision" ||
370 name ==
"level" || name ==
"profile" || name ==
"slices" || name ==
"rc_min_rate" || name ==
"rc_max_rate" ||
371 name ==
"rc_buffer_size" || name ==
"crf" || name ==
"cqp" || name ==
"qp" || name ==
"allow_b_frames")) {
375 convert >> c->gop_size;
377 else if (name ==
"qmin")
381 else if (name ==
"qmax")
385 else if (name ==
"max_b_frames")
387 convert >> c->max_b_frames;
389 else if (name ==
"allow_b_frames")
392 allow_b_frames = (value ==
"1" || value ==
"true" || value ==
"yes" || value ==
"on");
394 else if (name ==
"mb_decision")
396 convert >> c->mb_decision;
398 else if (name ==
"level")
402 else if (name ==
"profile")
404 convert >> c->profile;
406 else if (name ==
"slices")
408 convert >> c->slices;
410 else if (name ==
"rc_min_rate")
412 convert >> c->rc_min_rate;
414 else if (name ==
"rc_max_rate")
416 convert >> c->rc_max_rate;
418 else if (name ==
"rc_buffer_size")
420 convert >> c->rc_buffer_size;
422 else if (name ==
"cqp") {
426 av_opt_set_int(c->priv_data,
"qp", std::min(std::stoi(value),63), 0);
428 #endif // USE_HW_ACCEL
430 switch (c->codec_id) {
431 #if (LIBAVCODEC_VERSION_MAJOR >= 58)
433 case AV_CODEC_ID_AV1 :
435 av_opt_set_int(c->priv_data,
"qp", std::min(std::stoi(value),63), 0);
438 case AV_CODEC_ID_VP8 :
439 c->bit_rate = 10000000;
440 av_opt_set_int(c->priv_data,
"qp", std::max(std::min(std::stoi(value), 63), 4), 0);
442 case AV_CODEC_ID_VP9 :
444 av_opt_set_int(c->priv_data,
"qp", std::min(std::stoi(value), 63), 0);
445 if (std::stoi(value) == 0) {
446 av_opt_set(c->priv_data,
"preset",
"veryslow", 0);
447 av_opt_set_int(c->priv_data,
"lossless", 1, 0);
450 case AV_CODEC_ID_H264 :
451 av_opt_set_int(c->priv_data,
"qp", std::min(std::stoi(value), 51), 0);
452 if (std::stoi(value) == 0) {
453 av_opt_set(c->priv_data,
"preset",
"veryslow", 0);
457 case AV_CODEC_ID_HEVC :
458 av_opt_set_int(c->priv_data,
"qp", std::min(std::stoi(value), 51), 0);
459 if (std::stoi(value) == 0) {
460 av_opt_set(c->priv_data,
"preset",
"veryslow", 0);
461 av_opt_set_int(c->priv_data,
"lossless", 1, 0);
466 av_opt_set_int(c->priv_data,
"qp", std::min(std::stoi(value), 63), 0);
470 }
else if (name ==
"crf") {
474 double mbs = 15000000.0;
483 c->bit_rate = (int)(mbs);
485 #endif // USE_HW_ACCEL
487 switch (c->codec_id) {
488 #if (LIBAVCODEC_VERSION_MAJOR >= 58)
490 case AV_CODEC_ID_AV1 :
493 av_opt_set_int(c->priv_data,
"crf", std::min(std::stoi(value),63), 0);
496 case AV_CODEC_ID_VP8 :
497 c->bit_rate = 10000000;
498 av_opt_set_int(c->priv_data,
"crf", std::max(std::min(std::stoi(value), 63), 4), 0);
500 case AV_CODEC_ID_VP9 :
502 av_opt_set_int(c->priv_data,
"crf", std::min(std::stoi(value), 63), 0);
503 if (std::stoi(value) == 0) {
504 av_opt_set(c->priv_data,
"preset",
"veryslow", 0);
505 av_opt_set_int(c->priv_data,
"lossless", 1, 0);
508 case AV_CODEC_ID_H264 :
509 av_opt_set_int(c->priv_data,
"crf", std::min(std::stoi(value), 51), 0);
510 if (std::stoi(value) == 0) {
511 av_opt_set(c->priv_data,
"preset",
"veryslow", 0);
515 case AV_CODEC_ID_HEVC :
516 if (strstr(
info.
vcodec.c_str(),
"svt_hevc") != NULL) {
517 av_opt_set_int(c->priv_data,
"preset", 7, 0);
518 av_opt_set_int(c->priv_data,
"forced-idr",1,0);
519 av_opt_set_int(c->priv_data,
"qp",std::min(std::stoi(value), 51),0);
522 av_opt_set_int(c->priv_data,
"crf", std::min(std::stoi(value), 51), 0);
524 if (std::stoi(value) == 0) {
525 av_opt_set(c->priv_data,
"preset",
"veryslow", 0);
526 av_opt_set_int(c->priv_data,
"lossless", 1, 0);
532 double mbs = 15000000.0;
540 c->bit_rate = (int) (mbs);
543 }
else if (name ==
"qp") {
545 #if (LIBAVCODEC_VERSION_MAJOR >= 58)
547 switch (c->codec_id) {
548 case AV_CODEC_ID_AV1 :
550 if (strstr(
info.
vcodec.c_str(),
"svtav1") != NULL) {
551 av_opt_set_int(c->priv_data,
"qp", std::min(std::stoi(value),63), 0);
553 else if (strstr(
info.
vcodec.c_str(),
"rav1e") != NULL) {
556 av_opt_set_int(c->priv_data,
"qp", std::min(std::stoi(value),255), 0);
558 else if (strstr(
info.
vcodec.c_str(),
"aom") != NULL) {
562 av_opt_set_int(c->priv_data,
"crf", std::min(std::stoi(value),63), 0);
565 av_opt_set_int(c->priv_data,
"crf", std::min(std::stoi(value),63), 0);
567 case AV_CODEC_ID_HEVC :
569 if (strstr(
info.
vcodec.c_str(),
"svt_hevc") != NULL) {
570 av_opt_set_int(c->priv_data,
"qp", std::min(std::stoi(value),51), 0);
571 av_opt_set_int(c->priv_data,
"preset", 7, 0);
572 av_opt_set_int(c->priv_data,
"forced-idr",1,0);
576 #endif // FFmpeg 4.0+
579 AV_OPTION_SET(st, c->priv_data, name.c_str(), value.c_str(), c);
583 "FFmpegWriter::SetOption (" + (std::string)name +
")",
588 }
else if (name ==
"muxing_preset") {
589 if (value ==
"mp4_faststart") {
591 av_dict_set(&
mux_dict,
"movflags",
"faststart", 0);
592 }
else if (value ==
"mp4_fragmented") {
594 av_dict_set(&
mux_dict,
"movflags",
"frag_keyframe", 0);
595 av_dict_set(&
mux_dict,
"min_frag_duration",
"8000000", 0);
598 throw InvalidOptions(
"The option is not valid for this codec.", path);
609 return avcodec_find_encoder_by_name(codec_name.c_str()) != NULL;
615 throw InvalidOptions(
"No video or audio options have been set. You must set has_video or has_audio (or both).", path);
618 "FFmpegWriter::PrepareStreams [" + path +
"]",
623 initialize_streams();
626 prepare_streams =
true;
632 throw InvalidOptions(
"No video or audio options have been set. You must set has_video or has_audio (or both).", path);
635 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
636 if (avio_open(&oc->pb, path.c_str(), AVIO_FLAG_WRITE) < 0)
637 throw InvalidFile(
"Could not open or write file.", path);
645 av_dict_set(&oc->metadata, iter->first.c_str(), iter->second.c_str(), 0);
649 AVDictionary *dict = NULL;
655 if (avformat_write_header(oc, &dict) != 0) {
657 "FFmpegWriter::WriteHeader (avformat_write_header)");
658 throw InvalidFile(
"Could not write header to file.", path);
662 if (dict) av_dict_free(&dict);
675 throw WriterClosed(
"The FFmpegWriter is closed. Call Open() before calling this method.", path);
678 "FFmpegWriter::WriteFrame",
679 "frame->number", frame->number,
680 "is_writing", is_writing);
690 void FFmpegWriter::write_frame(std::shared_ptr<Frame> frame) {
695 bool has_error_encoding_video =
false;
699 write_audio_packets(
false, frame);
703 process_video_packet(frame);
707 if (av_frames.count(frame)) {
709 AVFrame *frame_final = av_frames[frame];
712 if (!write_video_packet(frame, frame_final)) {
713 has_error_encoding_video =
true;
717 av_freep(&(frame_final->data[0]));
719 av_frames.erase(frame);
727 if (has_error_encoding_video)
734 "FFmpegWriter::WriteFrame (from Reader)",
739 for (int64_t number = start; number <= length; number++) {
741 std::shared_ptr<Frame> f = reader->
GetFrame(number);
752 write_audio_packets(
true, NULL);
761 av_write_trailer(oc);
764 write_trailer =
true;
770 void FFmpegWriter::flush_encoders() {
773 #if (LIBAVFORMAT_VERSION_MAJOR < 58)
787 video_timestamp += av_rescale_q(1, av_make_q(
info.
fps.
den,
info.
fps.
num), video_codec_ctx->time_base);
790 AVPacket* pkt = av_packet_alloc();
804 error_code = avcodec_send_frame(video_codec_ctx, NULL);
806 while (error_code >= 0) {
807 error_code = avcodec_receive_packet(video_codec_ctx, pkt);
808 if (error_code == AVERROR(EAGAIN)|| error_code == AVERROR_EOF) {
811 avcodec_flush_buffers(video_codec_ctx);
814 if (pkt->duration <= 0) {
815 pkt->duration = av_rescale_q(1, av_make_q(
info.
fps.
den,
info.
fps.
num), video_codec_ctx->time_base);
817 av_packet_rescale_ts(pkt, video_codec_ctx->time_base, video_st->time_base);
818 pkt->stream_index = video_st->index;
819 error_code = av_interleaved_write_frame(oc, pkt);
821 #else // IS_FFMPEG_3_2
824 error_code = avcodec_encode_video2(video_codec_ctx, pkt, NULL, &got_packet);
826 #endif // IS_FFMPEG_3_2
828 if (error_code < 0) {
830 "FFmpegWriter::flush_encoders ERROR ["
831 + av_err2string(error_code) +
"]",
832 "error_code", error_code);
839 if (pkt->duration <= 0) {
840 pkt->duration = av_rescale_q(1, av_make_q(
info.
fps.
den,
info.
fps.
num), video_codec_ctx->time_base);
842 av_packet_rescale_ts(pkt, video_codec_ctx->time_base, video_st->time_base);
843 pkt->stream_index = video_st->index;
846 error_code = av_interleaved_write_frame(oc, pkt);
847 if (error_code < 0) {
849 "FFmpegWriter::flush_encoders ERROR ["
850 + av_err2string(error_code) +
"]",
851 "error_code", error_code);
860 AVPacket* pkt = av_packet_alloc();
867 pkt->pts = pkt->dts = audio_timestamp;
873 error_code = avcodec_send_frame(audio_codec_ctx, NULL);
875 error_code = avcodec_encode_audio2(audio_codec_ctx, pkt, NULL, &got_packet);
877 if (error_code < 0) {
879 "FFmpegWriter::flush_encoders ERROR ["
880 + av_err2string(error_code) +
"]",
881 "error_code", error_code);
889 pkt->pts = pkt->dts = audio_timestamp;
892 av_packet_rescale_ts(pkt, audio_codec_ctx->time_base, audio_st->time_base);
895 pkt->stream_index = audio_st->index;
896 pkt->flags |= AV_PKT_FLAG_KEY;
899 error_code = av_interleaved_write_frame(oc, pkt);
900 if (error_code < 0) {
902 "FFmpegWriter::flush_encoders ERROR ["
903 + av_err2string(error_code) +
"]",
904 "error_code", error_code);
908 audio_timestamp += pkt->duration;
918 void FFmpegWriter::close_video(AVFormatContext *oc, AVStream *st)
923 av_buffer_unref(&hw_device_ctx);
924 hw_device_ctx = NULL;
927 #endif // USE_HW_ACCEL
930 if (video_codec_ctx !=
nullptr) {
932 av_free(video_codec_ctx);
937 void FFmpegWriter::close_audio(AVFormatContext *oc, AVStream *st)
941 delete[] audio_outbuf;
942 delete[] audio_encoder_buffer;
945 audio_encoder_buffer = NULL;
961 if (audio_codec_ctx !=
nullptr) {
963 av_free(audio_codec_ctx);
975 close_video(oc, video_st);
977 close_audio(oc, audio_st);
981 sws_freeContext(img_convert_ctx);
983 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
993 avformat_free_context(oc);
998 prepare_streams =
false;
999 write_header =
false;
1000 write_trailer =
false;
1006 void FFmpegWriter::add_avframe(std::shared_ptr<Frame> frame, AVFrame *av_frame) {
1008 if (!av_frames.count(frame)) {
1010 av_frames[frame] = av_frame;
1018 AVStream *FFmpegWriter::add_audio_stream() {
1020 const AVCodec *
codec = avcodec_find_encoder_by_name(
info.
acodec.c_str());
1022 throw InvalidCodec(
"A valid audio codec could not be found for this file.", path);
1025 if (audio_codec_ctx !=
nullptr) {
1030 AVStream* st = avformat_new_stream(oc,
codec);
1032 throw OutOfMemory(
"Could not allocate memory for the audio stream.", path);
1036 #if (LIBAVFORMAT_VERSION_MAJOR >= 58)
1037 st->codecpar->codec_id =
codec->id;
1039 AVCodecContext* c = audio_codec_ctx;
1041 c->codec_id =
codec->id;
1042 c->codec_type = AVMEDIA_TYPE_AUDIO;
1051 if (
codec->supported_samplerates) {
1053 for (i = 0;
codec->supported_samplerates[i] != 0; i++)
1059 if (
codec->supported_samplerates[i] == 0)
1060 throw InvalidSampleRate(
"An invalid sample rate was detected for this codec.", path);
1068 AVChannelLayout ch_layout;
1070 if (
codec->ch_layouts) {
1072 for (i = 0; av_channel_layout_check(&
codec->ch_layouts[i]); i++)
1073 if (av_channel_layout_compare(&ch_layout, &
codec->ch_layouts[i])) {
1075 av_channel_layout_copy(&c->ch_layout, &ch_layout);
1078 if (!av_channel_layout_check(&
codec->ch_layouts[i]))
1079 throw InvalidChannels(
"An invalid channel layout was detected (i.e. MONO / STEREO).", path);
1082 av_channel_layout_copy(&c->ch_layout, &ch_layout);
1085 if (
codec->channel_layouts) {
1087 for (i = 0;
codec->channel_layouts[i] != 0; i++)
1088 if (channel_layout ==
codec->channel_layouts[i]) {
1090 c->channel_layout = channel_layout;
1093 if (
codec->channel_layouts[i] == 0)
1094 throw InvalidChannels(
"An invalid channel layout was detected (i.e. MONO / STEREO).", path);
1097 c->channel_layout = channel_layout;
1101 if (
codec->sample_fmts) {
1102 for (
int i = 0;
codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
1104 c->sample_fmt =
codec->sample_fmts[i];
1108 if (c->sample_fmt == AV_SAMPLE_FMT_NONE) {
1110 c->sample_fmt = AV_SAMPLE_FMT_S16;
1114 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
1115 #if (LIBAVCODEC_VERSION_MAJOR >= 57)
1117 c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
1119 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
1125 const char* nb_channels_label;
1126 const char* channel_layout_label;
1129 nb_channels = c->ch_layout.nb_channels;
1130 channel_layout = c->ch_layout.u.mask;
1131 nb_channels_label =
"c->ch_layout.nb_channels";
1132 channel_layout_label =
"c->ch_layout.u.mask";
1134 nb_channels = c->channels;
1135 nb_channels_label =
"c->channels";
1136 channel_layout_label =
"c->channel_layout";
1140 "FFmpegWriter::add_audio_stream",
1141 "c->codec_id", c->codec_id,
1142 "c->bit_rate", c->bit_rate,
1143 nb_channels_label, nb_channels,
1144 "c->sample_fmt", c->sample_fmt,
1145 channel_layout_label, channel_layout,
1146 "c->sample_rate", c->sample_rate);
1152 AVStream *FFmpegWriter::add_video_stream() {
1154 const AVCodec *
codec = avcodec_find_encoder_by_name(
info.
vcodec.c_str());
1156 throw InvalidCodec(
"A valid video codec could not be found for this file.", path);
1159 if (video_codec_ctx !=
nullptr) {
1164 AVStream* st = avformat_new_stream(oc,
codec);
1166 throw OutOfMemory(
"Could not allocate memory for the video stream.", path);
1170 #if (LIBAVFORMAT_VERSION_MAJOR >= 58)
1171 st->codecpar->codec_id =
codec->id;
1174 AVCodecContext* c = video_codec_ctx;
1176 c->codec_id =
codec->id;
1177 c->codec_type = AVMEDIA_TYPE_VIDEO;
1185 #
if (LIBAVCODEC_VERSION_MAJOR >= 58)
1186 && c->codec_id != AV_CODEC_ID_AV1
1191 if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
1200 switch (c->codec_id) {
1201 #if (LIBAVCODEC_VERSION_MAJOR >= 58)
1203 case AV_CODEC_ID_AV1 :
1207 if (strstr(
info.
vcodec.c_str(),
"aom") != NULL) {
1208 int calculated_quality = 35;
1211 av_opt_set_int(c->priv_data,
"crf", calculated_quality, 0);
1214 int calculated_quality = 50;
1217 av_opt_set_int(c->priv_data,
"qp", calculated_quality, 0);
1221 if (strstr(
info.
vcodec.c_str(),
"svtav1") != NULL) {
1222 av_opt_set_int(c->priv_data,
"preset", 6, 0);
1223 av_opt_set_int(c->priv_data,
"forced-idr",1,0);
1225 else if (strstr(
info.
vcodec.c_str(),
"rav1e") != NULL) {
1226 av_opt_set_int(c->priv_data,
"speed", 7, 0);
1227 av_opt_set_int(c->priv_data,
"tile-rows", 2, 0);
1228 av_opt_set_int(c->priv_data,
"tile-columns", 4, 0);
1230 else if (strstr(
info.
vcodec.c_str(),
"aom") != NULL) {
1233 av_opt_set_int(c->priv_data,
"tile-rows", 1, 0);
1234 av_opt_set_int(c->priv_data,
"tile-columns", 2, 0);
1235 av_opt_set_int(c->priv_data,
"row-mt", 1, 0);
1236 av_opt_set_int(c->priv_data,
"cpu-used", 3, 0);
1240 case AV_CODEC_ID_VP9 :
1241 case AV_CODEC_ID_HEVC :
1242 case AV_CODEC_ID_VP8 :
1243 case AV_CODEC_ID_H264 :
1279 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(56, 26, 0)
1280 c->framerate = av_inv_q(c->time_base);
1282 st->avg_frame_rate = av_inv_q(c->time_base);
1283 st->r_frame_rate = av_inv_q(c->time_base);
1288 c->max_b_frames = 10;
1289 if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1291 c->max_b_frames = 2;
1292 if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO)
1298 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
1299 #if (LIBAVCODEC_VERSION_MAJOR >= 57)
1301 c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
1303 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
1308 while (supported_pixel_formats != NULL && *supported_pixel_formats !=
PIX_FMT_NONE) {
1311 c->pix_fmt = *supported_pixel_formats;
1312 ++supported_pixel_formats;
1317 if (oc->oformat->video_codec == AV_CODEC_ID_RAWVIDEO) {
1321 #if (LIBAVFORMAT_VERSION_MAJOR < 58)
1323 if (strcmp(oc->oformat->name,
"gif") != 0)
1326 oc->oformat->flags |= AVFMT_RAWPICTURE;
1336 "FFmpegWriter::add_video_stream ("
1337 + (std::string)oc->oformat->name +
" : "
1338 + (std::string)av_get_pix_fmt_name(c->pix_fmt) +
")",
1339 "c->codec_id", c->codec_id,
1340 "c->bit_rate", c->bit_rate,
1341 "c->pix_fmt", c->pix_fmt,
1342 "oc->oformat->flags", oc->oformat->flags);
1347 void FFmpegWriter::open_audio(AVFormatContext *oc, AVStream *st) {
1348 const AVCodec *
codec;
1357 codec = avcodec_find_encoder(audio_codec_ctx->codec_id);
1362 AVDictionary *
opts = NULL;
1363 av_dict_set(&
opts,
"strict",
"experimental", 0);
1366 if (avcodec_open2(audio_codec_ctx,
codec, &
opts) < 0)
1367 throw InvalidCodec(
"Could not open audio codec", path);
1371 av_dict_free(&
opts);
1375 if (audio_codec_ctx->frame_size <= 1) {
1381 case AV_CODEC_ID_PCM_S16LE:
1382 case AV_CODEC_ID_PCM_S16BE:
1383 case AV_CODEC_ID_PCM_U16LE:
1384 case AV_CODEC_ID_PCM_U16BE:
1385 audio_input_frame_size >>= 1;
1392 audio_input_frame_size = audio_codec_ctx->frame_size;
1396 initial_audio_input_frame_size = audio_input_frame_size;
1403 audio_outbuf =
new uint8_t[audio_outbuf_size];
1407 audio_encoder_buffer =
new uint8_t[audio_encoder_buffer_size];
1410 for (std::map<std::string, std::string>::iterator iter =
info.
metadata.begin(); iter !=
info.
metadata.end(); ++iter) {
1411 av_dict_set(&st->metadata, iter->first.c_str(), iter->second.c_str(), 0);
1415 "FFmpegWriter::open_audio",
1416 "audio_codec_ctx->thread_count", audio_codec_ctx->thread_count,
1417 "audio_input_frame_size", audio_input_frame_size,
1422 void FFmpegWriter::open_video(AVFormatContext *oc, AVStream *st) {
1423 const AVCodec *
codec;
1433 char *adapter_ptr = NULL;
1437 std::clog <<
"Encoding Device Nr: " << adapter_num <<
"\n";
1438 if (adapter_num < 3 && adapter_num >=0) {
1439 #if defined(__linux__)
1440 snprintf(adapter,
sizeof(adapter),
"/dev/dri/renderD%d", adapter_num+128);
1442 adapter_ptr = adapter;
1443 #elif defined(_WIN32) || defined(__APPLE__)
1451 #if defined(__linux__)
1452 if( adapter_ptr != NULL && access( adapter_ptr, W_OK ) == 0 ) {
1453 #elif defined(_WIN32) || defined(__APPLE__)
1454 if( adapter_ptr != NULL ) {
1457 "Encode Device present using device",
1458 "adapter", adapter_num);
1463 "Encode Device not present, using default");
1465 if (av_hwdevice_ctx_create(&hw_device_ctx,
1469 "FFmpegWriter::open_video ERROR creating hwdevice, Codec name:",
1474 #endif // USE_HW_ACCEL
1485 if (!allow_b_frames && video_codec_ctx->max_b_frames &&
1486 video_codec_ctx->codec_id != AV_CODEC_ID_MPEG4 &&
1487 video_codec_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO &&
1488 video_codec_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO)
1489 video_codec_ctx->max_b_frames = 0;
1493 av_dict_set(&
opts,
"strict",
"experimental", 0);
1507 if (av_opt_get_int(video_codec_ctx->priv_data,
"qp", 0, &qp) != 0 || qp == 0) {
1509 av_opt_set(video_codec_ctx->priv_data,
"rc_mode",
"VBR", 0);
1513 video_codec_ctx->rc_max_rate = video_codec_ctx->bit_rate;
1517 switch (video_codec_ctx->codec_id) {
1518 case AV_CODEC_ID_H264:
1519 video_codec_ctx->max_b_frames = 0;
1520 video_codec_ctx->profile = AV_PROFILE_H264_CONSTRAINED_BASELINE;
1521 av_opt_set(video_codec_ctx->priv_data,
"preset",
"slow", 0);
1522 av_opt_set(video_codec_ctx->priv_data,
"tune",
"zerolatency", 0);
1523 av_opt_set(video_codec_ctx->priv_data,
"vprofile",
"baseline", AV_OPT_SEARCH_CHILDREN);
1525 case AV_CODEC_ID_HEVC:
1528 case AV_CODEC_ID_VP9:
1533 "No codec-specific options defined for this codec. HW encoding may fail",
1534 "codec_id", video_codec_ctx->codec_id);
1543 "FFmpegWriter::open_video (set_hwframe_ctx) ERROR faled to set hwframe context",
1546 av_err2string(err), -1);
1549 #endif // USE_HW_ACCEL
1554 video_codec_ctx->codec_tag = MKTAG(
'h',
'v',
'c',
'1');
1557 if (video_codec_ctx->codec_id == AV_CODEC_ID_HEVC) {
1558 video_codec_ctx->codec_tag = MKTAG(
'h',
'v',
'c',
'1');
1563 if (avcodec_open2(video_codec_ctx,
codec, &
opts) < 0)
1564 throw InvalidCodec(
"Could not open video codec", path);
1570 av_dict_free(&
opts);
1574 av_dict_set(&st->metadata, iter->first.c_str(), iter->second.c_str(), 0);
1578 "FFmpegWriter::open_video",
1579 "video_codec_ctx->thread_count", video_codec_ctx->thread_count);
1584 void FFmpegWriter::write_audio_packets(
bool is_final, std::shared_ptr<openshot::Frame> frame) {
1585 if (!frame && !is_final)
1589 int total_frame_samples = 0;
1590 int frame_position = 0;
1591 int channels_in_frame = 0;
1592 int sample_rate_in_frame = 0;
1593 int samples_in_frame = 0;
1598 int16_t *all_queued_samples = (int16_t *) av_malloc(all_queued_samples_size);
1599 int16_t *all_resampled_samples = NULL;
1600 int16_t *final_samples_planar = NULL;
1601 int16_t *final_samples = NULL;
1604 float *frame_samples_float = NULL;
1608 sample_rate_in_frame = frame->SampleRate();
1609 samples_in_frame = frame->GetAudioSamplesCount();
1610 channels_in_frame = frame->GetAudioChannelsCount();
1611 channel_layout_in_frame = frame->ChannelsLayout();
1614 frame_samples_float = frame->GetInterleavedAudioSamples(&samples_in_frame);
1618 total_frame_samples = samples_in_frame * channels_in_frame;
1621 const int16_t max16 = 32767;
1622 const int16_t min16 = -32768;
1623 for (
int s = 0; s < total_frame_samples; s++, frame_position++) {
1624 float valF = frame_samples_float[s] * (1 << 15);
1628 }
else if (valF < min16) {
1631 conv = int(valF + 32768.5) - 32768;
1635 all_queued_samples[frame_position] = conv;
1639 delete[] frame_samples_float;
1643 total_frame_samples = frame_position;
1644 int remaining_frame_samples = total_frame_samples;
1645 int samples_position = 0;
1649 "FFmpegWriter::write_audio_packets",
1650 "is_final", is_final,
1651 "total_frame_samples", total_frame_samples,
1652 "channel_layout_in_frame", channel_layout_in_frame,
1653 "channels_in_frame", channels_in_frame,
1654 "samples_in_frame", samples_in_frame,
1658 AVSampleFormat output_sample_fmt = audio_codec_ctx->sample_fmt;
1660 AVFrame *audio_frame = NULL;
1665 audio_frame->nb_samples = total_frame_samples / channels_in_frame;
1668 int error_code = avcodec_fill_audio_frame(audio_frame, channels_in_frame, AV_SAMPLE_FMT_S16, (uint8_t *) all_queued_samples, all_queued_samples_size, 0);
1669 if (error_code < 0) {
1671 "FFmpegWriter::write_audio_packets ERROR ["
1672 + av_err2string(error_code) +
"]",
1673 "error_code", error_code);
1677 switch (audio_codec_ctx->sample_fmt) {
1678 case AV_SAMPLE_FMT_FLTP: {
1679 output_sample_fmt = AV_SAMPLE_FMT_FLT;
1682 case AV_SAMPLE_FMT_S32P: {
1683 output_sample_fmt = AV_SAMPLE_FMT_S32;
1686 case AV_SAMPLE_FMT_S16P: {
1687 output_sample_fmt = AV_SAMPLE_FMT_S16;
1690 case AV_SAMPLE_FMT_U8P: {
1691 output_sample_fmt = AV_SAMPLE_FMT_U8;
1701 total_frame_samples *= (float(
info.
sample_rate) / sample_rate_in_frame);
1702 total_frame_samples *= (float(
info.
channels) / channels_in_frame);
1707 audio_converted->nb_samples = total_frame_samples / channels_in_frame;
1708 av_samples_alloc(audio_converted->data, audio_converted->linesize,
info.
channels, audio_converted->nb_samples, output_sample_fmt, 0);
1711 "FFmpegWriter::write_audio_packets (1st resampling)",
1712 "in_sample_fmt", AV_SAMPLE_FMT_S16,
1713 "out_sample_fmt", output_sample_fmt,
1714 "in_sample_rate", sample_rate_in_frame,
1716 "in_channels", channels_in_frame,
1723 AVChannelLayout in_chlayout = ffmpeg_default_channel_layout(channels_in_frame);
1724 AVChannelLayout out_chlayout = ffmpeg_default_channel_layout(
info.
channels);
1725 if (channel_layout_in_frame > 0) {
1726 av_channel_layout_from_mask(&in_chlayout, channel_layout_in_frame);
1731 av_opt_set_chlayout(avr,
"in_chlayout", &in_chlayout, 0);
1732 av_opt_set_chlayout(avr,
"out_chlayout", &out_chlayout, 0);
1734 av_opt_set_int(avr,
"in_channel_layout", channel_layout_in_frame, 0);
1736 av_opt_set_int(avr,
"in_channels", channels_in_frame, 0);
1739 av_opt_set_int(avr,
"in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
1740 av_opt_set_int(avr,
"out_sample_fmt", output_sample_fmt, 0);
1741 av_opt_set_int(avr,
"in_sample_rate", sample_rate_in_frame, 0);
1748 audio_converted->data,
1749 audio_converted->linesize[0],
1750 audio_converted->nb_samples,
1752 audio_frame->linesize[0],
1753 audio_frame->nb_samples
1757 remaining_frame_samples = total_frame_samples;
1760 all_resampled_samples = (int16_t *) av_malloc(
1762 * (av_get_bytes_per_sample(output_sample_fmt) /
1763 av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) )
1767 memcpy(all_resampled_samples, audio_converted->data[0],
1768 static_cast<size_t>(nb_samples)
1770 * av_get_bytes_per_sample(output_sample_fmt));
1773 av_freep(&(audio_frame->data[0]));
1775 av_freep(&audio_converted->data[0]);
1777 all_queued_samples = NULL;
1780 "FFmpegWriter::write_audio_packets (Successfully completed 1st resampling)",
1781 "nb_samples", nb_samples,
1782 "remaining_frame_samples", remaining_frame_samples);
1786 while (remaining_frame_samples > 0 || is_final) {
1788 int remaining_packet_samples = (audio_input_frame_size *
info.
channels) - audio_input_position;
1792 if (remaining_frame_samples >= remaining_packet_samples) {
1793 diff = remaining_packet_samples;
1795 diff = remaining_frame_samples;
1802 samples + (audio_input_position
1803 * (av_get_bytes_per_sample(output_sample_fmt) /
1804 av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) )
1806 all_resampled_samples + samples_position,
1807 static_cast<size_t>(diff)
1808 * av_get_bytes_per_sample(output_sample_fmt)
1812 audio_input_position += diff;
1813 samples_position += diff * (av_get_bytes_per_sample(output_sample_fmt) / av_get_bytes_per_sample(AV_SAMPLE_FMT_S16));
1814 remaining_frame_samples -= diff;
1817 if (audio_input_position < (audio_input_frame_size *
info.
channels) && !is_final)
1824 if (av_sample_fmt_is_planar(audio_codec_ctx->sample_fmt)) {
1826 "FFmpegWriter::write_audio_packets (2nd resampling for Planar formats)",
1827 "in_sample_fmt", output_sample_fmt,
1828 "out_sample_fmt", audio_codec_ctx->sample_fmt,
1839 AVChannelLayout layout = ffmpeg_default_channel_layout(
info.
channels);
1843 av_opt_set_chlayout(avr_planar,
"in_chlayout", &layout, 0);
1844 av_opt_set_chlayout(avr_planar,
"out_chlayout", &layout, 0);
1848 av_opt_set_int(avr_planar,
"in_channels",
info.
channels, 0);
1849 av_opt_set_int(avr_planar,
"out_channels",
info.
channels, 0);
1851 av_opt_set_int(avr_planar,
"in_sample_fmt", output_sample_fmt, 0);
1852 av_opt_set_int(avr_planar,
"out_sample_fmt", audio_codec_ctx->sample_fmt, 0);
1861 audio_frame->nb_samples = audio_input_position /
info.
channels;
1864 final_samples_planar = (int16_t *) av_malloc(
1865 sizeof(int16_t) * audio_frame->nb_samples *
info.
channels
1866 * (av_get_bytes_per_sample(output_sample_fmt) /
1867 av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) )
1871 memcpy(final_samples_planar, samples,
1872 static_cast<size_t>(audio_frame->nb_samples)
1874 * av_get_bytes_per_sample(output_sample_fmt));
1877 avcodec_fill_audio_frame(audio_frame,
info.
channels, output_sample_fmt,
1878 (uint8_t *) final_samples_planar, audio_encoder_buffer_size, 0);
1881 frame_final->nb_samples = audio_input_frame_size;
1888 frame_final->format = audio_codec_ctx->sample_fmt;
1889 av_samples_alloc(frame_final->data, frame_final->linesize,
info.
channels,
1890 frame_final->nb_samples, audio_codec_ctx->sample_fmt, 0);
1896 frame_final->linesize[0],
1897 frame_final->nb_samples,
1899 audio_frame->linesize[0],
1900 audio_frame->nb_samples
1904 const auto copy_length =
static_cast<size_t>(nb_samples)
1905 * av_get_bytes_per_sample(audio_codec_ctx->sample_fmt)
1909 memcpy(samples, frame_final->data[0], copy_length);
1912 av_freep(&(audio_frame->data[0]));
1914 all_queued_samples = NULL;
1917 "FFmpegWriter::write_audio_packets (Successfully completed 2nd resampling for Planar formats)",
1918 "nb_samples", nb_samples);
1922 const auto buf_size =
static_cast<size_t>(audio_input_position)
1923 * (av_get_bytes_per_sample(audio_codec_ctx->sample_fmt) /
1924 av_get_bytes_per_sample(AV_SAMPLE_FMT_S16)
1926 final_samples =
reinterpret_cast<int16_t*
>(
1927 av_malloc(
sizeof(int16_t) * buf_size));
1930 memcpy(final_samples, samples,
1931 audio_input_position * av_get_bytes_per_sample(audio_codec_ctx->sample_fmt));
1934 frame_final->nb_samples = audio_input_frame_size;
1938 int nb_channels = audio_codec_ctx->ch_layout.nb_channels;
1940 int nb_channels = audio_codec_ctx->channels;
1942 avcodec_fill_audio_frame(frame_final, nb_channels,
1943 audio_codec_ctx->sample_fmt, (uint8_t *) final_samples,
1944 audio_encoder_buffer_size, 0);
1948 frame_final->pts = audio_timestamp;
1952 AVPacket* pkt = av_packet_alloc();
1955 av_init_packet(pkt);
1957 pkt->data = audio_encoder_buffer;
1958 pkt->size = audio_encoder_buffer_size;
1961 pkt->pts = pkt->dts = audio_timestamp;
1964 int got_packet_ptr = 0;
1970 int frame_finished = 0;
1971 error_code = ret = avcodec_send_frame(audio_codec_ctx, frame_final);
1972 if (ret < 0 && ret != AVERROR(EINVAL) && ret != AVERROR_EOF) {
1973 avcodec_send_frame(audio_codec_ctx, NULL);
1978 ret = avcodec_receive_packet(audio_codec_ctx, pkt);
1981 if(ret == AVERROR(EINVAL) || ret == AVERROR_EOF) {
1982 avcodec_flush_buffers(audio_codec_ctx);
1986 ret = frame_finished;
1989 if (!pkt->data && !frame_finished)
1993 got_packet_ptr = ret;
1996 int error_code = avcodec_encode_audio2(audio_codec_ctx, pkt, frame_final, &got_packet_ptr);
1999 if (error_code == 0 && got_packet_ptr) {
2003 pkt->pts = pkt->dts = audio_timestamp;
2006 av_packet_rescale_ts(pkt, audio_codec_ctx->time_base, audio_st->time_base);
2009 pkt->stream_index = audio_st->index;
2010 pkt->flags |= AV_PKT_FLAG_KEY;
2013 error_code = av_interleaved_write_frame(oc, pkt);
2016 if (error_code < 0) {
2018 "FFmpegWriter::write_audio_packets ERROR ["
2019 + av_err2string(error_code) +
"]",
2020 "error_code", error_code);
2024 audio_timestamp += FFMIN(audio_input_frame_size, audio_input_position);
2027 av_freep(&(frame_final->data[0]));
2034 audio_input_position = 0;
2039 if (all_resampled_samples) {
2040 av_freep(&all_resampled_samples);
2041 all_resampled_samples = NULL;
2043 if (all_queued_samples) {
2044 av_freep(&all_queued_samples);
2045 all_queued_samples = NULL;
2050 AVFrame *FFmpegWriter::allocate_avframe(
PixelFormat pix_fmt,
int width,
int height,
int *buffer_size, uint8_t *new_buffer) {
2052 AVFrame *new_av_frame = NULL;
2056 if (new_av_frame == NULL)
2057 throw OutOfMemory(
"Could not allocate AVFrame", path);
2065 new_buffer = (uint8_t *) av_malloc(*buffer_size *
sizeof(uint8_t));
2068 new_av_frame->width = width;
2069 new_av_frame->height = height;
2070 new_av_frame->format = pix_fmt;
2074 return new_av_frame;
2078 void FFmpegWriter::process_video_packet(std::shared_ptr<Frame> frame) {
2080 int src_w = frame->GetWidth();
2081 int src_h = frame->GetHeight();
2084 if (src_w == 1 && src_h == 1)
2088 const uchar* pixels = frame->GetPixels();
2089 if (!persistent_src_frame) {
2090 persistent_src_frame = av_frame_alloc();
2091 if (!persistent_src_frame)
2092 throw OutOfMemory(
"Could not allocate persistent_src_frame", path);
2093 persistent_src_frame->format = AV_PIX_FMT_RGBA;
2094 persistent_src_frame->width = src_w;
2095 persistent_src_frame->height = src_h;
2096 persistent_src_frame->linesize[0] = src_w * 4;
2098 persistent_src_frame->data[0] =
const_cast<uint8_t*
>(
2099 reinterpret_cast<const uint8_t*
>(pixels)
2103 if (!persistent_dst_frame) {
2104 persistent_dst_frame = av_frame_alloc();
2105 if (!persistent_dst_frame)
2106 throw OutOfMemory(
"Could not allocate persistent_dst_frame", path);
2109 AVPixelFormat dst_fmt = video_codec_ctx->pix_fmt;
2112 dst_fmt = AV_PIX_FMT_NV12;
2115 persistent_dst_frame->format = dst_fmt;
2116 persistent_dst_frame->width =
info.
width;
2119 persistent_dst_size = av_image_get_buffer_size(
2122 if (persistent_dst_size < 0)
2125 persistent_dst_buffer =
static_cast<uint8_t*
>(
2126 av_malloc(persistent_dst_size)
2128 if (!persistent_dst_buffer)
2129 throw OutOfMemory(
"Could not allocate persistent_dst_buffer", path);
2131 av_image_fill_arrays(
2132 persistent_dst_frame->data,
2133 persistent_dst_frame->linesize,
2134 persistent_dst_buffer,
2143 if (!img_convert_ctx) {
2144 int flags = SWS_FAST_BILINEAR;
2146 flags = SWS_BICUBIC;
2148 AVPixelFormat dst_fmt = video_codec_ctx->pix_fmt;
2151 dst_fmt = AV_PIX_FMT_NV12;
2154 img_convert_ctx = sws_getContext(
2155 src_w, src_h, AV_PIX_FMT_RGBA,
2157 flags, NULL, NULL, NULL
2159 if (!img_convert_ctx)
2166 persistent_src_frame->data,
2167 persistent_src_frame->linesize,
2169 persistent_dst_frame->data,
2170 persistent_dst_frame->linesize
2174 int bytes_final = 0;
2175 AVPixelFormat dst_fmt = video_codec_ctx->pix_fmt;
2178 dst_fmt = AV_PIX_FMT_NV12;
2182 AVFrame* new_frame = allocate_avframe(
2190 throw OutOfMemory(
"Could not allocate new_frame via allocate_avframe", path);
2195 persistent_dst_buffer,
2196 static_cast<size_t>(bytes_final)
2200 add_avframe(frame, new_frame);
2204 bool FFmpegWriter::write_video_packet(std::shared_ptr<Frame> frame, AVFrame *frame_final) {
2205 #if (LIBAVFORMAT_VERSION_MAJOR >= 58)
2208 "FFmpegWriter::write_video_packet",
2209 "frame->number", frame->number,
2210 "oc->oformat->flags", oc->oformat->flags);
2218 "FFmpegWriter::write_video_packet",
2219 "frame->number", frame->number,
2220 "oc->oformat->flags & AVFMT_RAWPICTURE", oc->oformat->flags & AVFMT_RAWPICTURE);
2222 if (oc->oformat->flags & AVFMT_RAWPICTURE) {
2226 AVPacket* pkt = av_packet_alloc();
2229 av_init_packet(pkt);
2232 av_packet_from_data(
2233 pkt, frame_final->data[0],
2234 frame_final->linesize[0] * frame_final->height);
2236 pkt->flags |= AV_PKT_FLAG_KEY;
2237 pkt->stream_index = video_st->index;
2240 pkt->pts = video_timestamp;
2241 pkt->duration = av_rescale_q(1, av_make_q(
info.
fps.
den,
info.
fps.
num), video_codec_ctx->time_base);
2244 int error_code = av_interleaved_write_frame(oc, pkt);
2245 if (error_code < 0) {
2247 "FFmpegWriter::write_video_packet ERROR ["
2248 + av_err2string(error_code) +
"]",
2249 "error_code", error_code);
2260 AVPacket* pkt = av_packet_alloc();
2263 av_init_packet(pkt);
2267 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
2270 frame_final->pts = video_timestamp;
2273 if (!(
hw_frame = av_frame_alloc())) {
2274 std::clog <<
"Error code: av_hwframe_alloc\n";
2276 if (av_hwframe_get_buffer(video_codec_ctx->hw_frames_ctx,
hw_frame, 0) < 0) {
2277 std::clog <<
"Error code: av_hwframe_get_buffer\n";
2280 std::clog <<
"Error hw_frames_ctx.\n";
2282 hw_frame->format = AV_PIX_FMT_NV12;
2283 if ( av_hwframe_transfer_data(
hw_frame, frame_final, 0) < 0) {
2284 std::clog <<
"Error while transferring frame data to surface.\n";
2286 av_frame_copy_props(
hw_frame, frame_final);
2288 #endif // USE_HW_ACCEL
2290 int got_packet_ptr = 0;
2298 ret = avcodec_send_frame(video_codec_ctx,
hw_frame);
2300 #endif // USE_HW_ACCEL
2302 ret = avcodec_send_frame(video_codec_ctx, frame_final);
2307 "FFmpegWriter::write_video_packet (Frame not sent)");
2308 if (ret == AVERROR(EAGAIN) ) {
2309 std::clog <<
"Frame EAGAIN\n";
2311 if (ret == AVERROR_EOF ) {
2312 std::clog <<
"Frame AVERROR_EOF\n";
2314 avcodec_send_frame(video_codec_ctx, NULL);
2318 ret = avcodec_receive_packet(video_codec_ctx, pkt);
2320 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
2332 error_code = avcodec_encode_video2(video_codec_ctx, pkt, frame_final, &got_packet_ptr);
2333 if (error_code != 0) {
2335 "FFmpegWriter::write_video_packet ERROR ["
2336 + av_err2string(error_code) +
"]",
2337 "error_code", error_code);
2339 if (got_packet_ptr == 0) {
2341 "FFmpegWriter::write_video_packet (Frame gotpacket error)");
2343 #endif // IS_FFMPEG_3_2
2346 if (error_code == 0 && got_packet_ptr) {
2348 if (pkt->duration <= 0) {
2349 pkt->duration = av_rescale_q(1, av_make_q(
info.
fps.
den,
info.
fps.
num), video_codec_ctx->time_base);
2351 av_packet_rescale_ts(pkt, video_codec_ctx->time_base, video_st->time_base);
2352 pkt->stream_index = video_st->index;
2355 int result = av_interleaved_write_frame(oc, pkt);
2358 "FFmpegWriter::write_video_packet ERROR ["
2359 + av_err2string(result) +
"]",
2374 #endif // USE_HW_ACCEL
2378 video_timestamp += av_rescale_q(1, av_make_q(
info.
fps.
den,
info.
fps.
num), video_codec_ctx->time_base);
2387 av_dump_format(oc, 0, path.c_str(), 1);
2392 original_sample_rate = sample_rate;
2393 original_channels = channels;
2402 oc->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
2404 #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 0, 0)
2406 int proj = av_spherical_from_name(projection.c_str());
2408 proj = AV_SPHERICAL_EQUIRECTANGULAR;
2412 AVSphericalMapping* map = av_spherical_alloc(&sd_size);
2416 map->projection =
static_cast<AVSphericalProjection
>(proj);
2418 map->yaw =
static_cast<int32_t
>(yaw_deg * (1 << 16));
2419 map->pitch =
static_cast<int32_t
>(pitch_deg * (1 << 16));
2420 map->roll =
static_cast<int32_t
>(roll_deg * (1 << 16));
2422 ffmpeg_stream_add_side_data(video_st, AV_PKT_DATA_SPHERICAL,
2423 reinterpret_cast<uint8_t*
>(map), sd_size);