3 #include "ffmpeg_consumer.h"
5 #include "../ffmpeg_error.h"
6 #include "../producer/util/util.h"
7 #include "../producer/filter/filter.h"
8 #include "../producer/filter/audio_filter.h"
10 #include <common/except.h>
11 #include <common/executor.h>
12 #include <common/assert.h>
13 #include <common/utf.h>
14 #include <common/future.h>
15 #include <common/diagnostics/graph.h>
16 #include <common/env.h>
17 #include <common/scope_exit.h>
18 #include <common/ptree.h>
19 #include <common/param.h>
20 #include <common/semaphore.h>
22 #include <core/consumer/frame_consumer.h>
23 #include <core/frame/frame.h>
24 #include <core/frame/audio_channel_layout.h>
25 #include <core/video_format.h>
26 #include <core/monitor/monitor.h>
27 #include <core/help/help_repository.h>
28 #include <core/help/help_sink.h>
30 #include <boost/noncopyable.hpp>
31 #include <boost/rational.hpp>
32 #include <boost/format.hpp>
33 #include <boost/algorithm/string/predicate.hpp>
34 #include <boost/property_tree/ptree.hpp>
37 #pragma warning(disable: 4244)
38 #pragma warning(disable: 4245)
39 #include <boost/crc.hpp>
42 #include <tbb/atomic.h>
43 #include <tbb/concurrent_queue.h>
44 #include <tbb/parallel_invoke.h>
45 #include <tbb/parallel_for.h>
50 #pragma warning(disable: 4244)
54 #define __STDC_CONSTANT_MACROS
55 #define __STDC_LIMIT_MACROS
56 #include <libavformat/avformat.h>
57 #include <libavcodec/avcodec.h>
58 #include <libavutil/avutil.h>
59 #include <libavutil/frame.h>
60 #include <libavutil/opt.h>
61 #include <libavutil/imgutils.h>
62 #include <libavutil/parseutils.h>
63 #include <libavfilter/avfilter.h>
64 #include <libavfilter/buffersink.h>
65 #include <libavfilter/buffersrc.h>
70 namespace caspar { namespace ffmpeg {
72 void set_pixel_format(AVFilterContext* sink, AVPixelFormat pix_fmt)
74 #pragma warning (push)
75 #pragma warning (disable : 4245)
77 FF(av_opt_set_int_list(
80 std::vector<AVPixelFormat>({ pix_fmt, AVPixelFormat::AV_PIX_FMT_NONE }).data(),
82 AV_OPT_SEARCH_CHILDREN));
87 void adjust_video_filter(const AVCodec& codec, const core::video_format_desc& in_format, AVFilterContext* sink, std::string& filter)
91 case AV_CODEC_ID_DVVIDEO:
93 if (in_format.format == core::video_format::ntsc)
94 filter = u8(append_filter(u16(filter), L"crop=720:480:0:2"));
96 // Pixel format selection
97 if (in_format.format == core::video_format::ntsc)
98 set_pixel_format(sink, AVPixelFormat::AV_PIX_FMT_YUV411P);
99 else if (in_format.format == core::video_format::pal)
100 set_pixel_format(sink, AVPixelFormat::AV_PIX_FMT_YUV420P);
102 set_pixel_format(sink, AVPixelFormat::AV_PIX_FMT_YUV422P);
105 if (in_format.height == 1080)
106 filter = u8(append_filter(u16(filter), in_format.duration == 1001
108 : L"scale=1440:1080"));
109 else if (in_format.height == 720)
110 filter = u8(append_filter(u16(filter), L"scale=960:720"));
116 void setup_codec_defaults(AVCodecContext& encoder)
118 static const int MEGABIT = 1000000;
120 switch (encoder.codec_id)
122 case AV_CODEC_ID_DNXHD:
123 encoder.bit_rate = 220 * MEGABIT;
126 case AV_CODEC_ID_PRORES:
127 encoder.bit_rate = encoder.width < 1280
132 case AV_CODEC_ID_H264:
133 av_opt_set(encoder.priv_data, "preset", "ultrafast", 0);
134 av_opt_set(encoder.priv_data, "tune", "fastdecode", 0);
135 av_opt_set(encoder.priv_data, "crf", "5", 0);
141 bool is_pcm_s24le_not_supported(const AVFormatContext& container)
143 auto name = std::string(container.oformat->name);
145 if (name == "mp4" || name == "dv")
151 template<typename Out, typename In>
152 std::vector<Out> from_terminated_array(const In* array, In terminator)
154 std::vector<Out> result;
156 while (array != nullptr && *array != terminator)
159 Out casted = static_cast<Out>(val);
161 result.push_back(casted);
169 class ffmpeg_consumer
172 const spl::shared_ptr<diagnostics::graph> graph_;
173 core::monitor::subject subject_;
175 boost::filesystem::path full_path_;
177 std::map<std::string, std::string> options_;
180 core::video_format_desc in_video_format_;
181 core::audio_channel_layout in_channel_layout_ = core::audio_channel_layout::invalid();
183 std::shared_ptr<AVFormatContext> oc_;
184 tbb::atomic<bool> abort_request_;
186 std::shared_ptr<AVStream> video_st_;
187 std::vector<std::shared_ptr<AVStream>> audio_sts_;
189 std::int64_t video_pts_ = 0;
190 std::int64_t audio_pts_ = 0;
192 std::unique_ptr<audio_filter> audio_filter_;
194 // TODO: make use of already existent avfilter abstraction for video also
195 AVFilterContext* video_graph_in_;
196 AVFilterContext* video_graph_out_;
197 std::shared_ptr<AVFilterGraph> video_graph_;
199 executor video_encoder_executor_;
200 executor audio_encoder_executor_;
202 semaphore tokens_ { 0 };
204 tbb::atomic<int64_t> current_encoding_delay_;
206 executor write_executor_;
216 , mono_streams_(mono_streams)
217 , audio_encoder_executor_(print() + L" audio_encoder")
218 , video_encoder_executor_(print() + L" video_encoder")
219 , write_executor_(print() + L" io")
221 abort_request_ = false;
222 current_encoding_delay_ = 0;
225 boost::sregex_iterator(
228 boost::regex("-(?<NAME>[^-\\s]+)(\\s+(?<VALUE>[^\\s]+))?"));
229 it != boost::sregex_iterator();
232 options_[(*it)["NAME"].str()] = (*it)["VALUE"].matched ? (*it)["VALUE"].str() : "";
235 if (options_.find("threads") == options_.end())
236 options_["threads"] = "auto";
243 boost::regex("tokens")).get_value_or(2)));
250 video_encoder_executor_.begin_invoke([&] { encode_video(core::const_frame::empty(), nullptr); });
251 audio_encoder_executor_.begin_invoke([&] { encode_audio(core::const_frame::empty(), nullptr); });
253 video_encoder_executor_.stop();
254 audio_encoder_executor_.stop();
255 video_encoder_executor_.join();
256 audio_encoder_executor_.join();
258 video_graph_.reset();
259 audio_filter_.reset();
263 write_packet(nullptr, nullptr);
265 write_executor_.stop();
266 write_executor_.join();
268 FF(av_write_trailer(oc_.get()));
270 if (!(oc_->oformat->flags & AVFMT_NOFILE) && oc_->pb)
278 const core::video_format_desc& format_desc,
279 const core::audio_channel_layout& channel_layout)
283 static boost::regex prot_exp("^.+:.*" );
285 if(!boost::regex_match(
289 if(!full_path_.is_complete())
293 env::media_folder()) +
297 if(boost::filesystem::exists(full_path_))
298 boost::filesystem::remove(full_path_);
300 boost::filesystem::create_directories(full_path_.parent_path());
303 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
304 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
305 graph_->set_text(print());
306 diagnostics::register_graph(graph_);
308 const auto oformat_name =
309 try_remove_arg<std::string>(
311 boost::regex("^f|format$"));
315 FF(avformat_alloc_output_context2(
318 oformat_name && !oformat_name->empty() ? oformat_name->c_str() : nullptr,
319 full_path_.string().c_str()));
323 avformat_free_context);
325 CASPAR_VERIFY(oc_->oformat);
327 oc_->interrupt_callback.callback = ffmpeg_consumer::interrupt_cb;
328 oc_->interrupt_callback.opaque = this;
330 CASPAR_VERIFY(format_desc.format != core::video_format::invalid);
332 in_video_format_ = format_desc;
333 in_channel_layout_ = channel_layout;
335 CASPAR_VERIFY(oc_->oformat);
337 const auto video_codec_name =
338 try_remove_arg<std::string>(
340 boost::regex("^c:v|codec:v|vcodec$"));
342 const auto video_codec =
344 ? avcodec_find_encoder_by_name(video_codec_name->c_str())
345 : avcodec_find_encoder(oc_->oformat->video_codec);
347 const auto audio_codec_name =
348 try_remove_arg<std::string>(
350 boost::regex("^c:a|codec:a|acodec$"));
352 const auto audio_codec =
354 ? avcodec_find_encoder_by_name(audio_codec_name->c_str())
355 : (is_pcm_s24le_not_supported(*oc_)
356 ? avcodec_find_encoder(oc_->oformat->audio_codec)
357 : avcodec_find_encoder_by_name("pcm_s24le"));
360 CASPAR_THROW_EXCEPTION(user_error() << msg_info(
361 "Failed to find video codec " + (video_codec_name
363 : "with id " + boost::lexical_cast<std::string>(
364 oc_->oformat->video_codec))));
366 CASPAR_THROW_EXCEPTION(user_error() << msg_info(
367 "Failed to find audio codec " + (audio_codec_name
369 : "with id " + boost::lexical_cast<std::string>(
370 oc_->oformat->audio_codec))));
375 configure_video_filters(
377 try_remove_arg<std::string>(options_,
378 boost::regex("vf|f:v|filter:v")).get_value_or(""));
380 configure_audio_filters(
382 try_remove_arg<std::string>(options_,
383 boost::regex("af|f:a|filter:a")).get_value_or(""));
389 auto video_options = options_;
390 auto audio_options = options_;
392 video_st_ = open_encoder(
397 for (int i = 0; i < audio_filter_->get_num_output_pads(); ++i)
398 audio_sts_.push_back(open_encoder(
403 auto it = options_.begin();
404 while(it != options_.end())
406 if(video_options.find(it->first) == video_options.end() || audio_options.find(it->first) == audio_options.end())
407 it = options_.erase(it);
415 AVDictionary* av_opts = nullptr;
419 std::move(options_));
423 av_dict_free(&av_opts);
426 if (!(oc_->oformat->flags & AVFMT_NOFILE))
430 full_path_.string().c_str(),
432 &oc_->interrupt_callback,
436 FF(avformat_write_header(
440 options_ = to_map(av_opts);
451 for (const auto& option : options_)
454 << L"Invalid option: -"
457 << u16(option.second);
469 core::monitor::subject& monitor_output()
474 void send(core::const_frame frame)
476 CASPAR_VERIFY(in_video_format_.format != core::video_format::invalid);
478 auto frame_timer = spl::make_shared<caspar::timer>();
480 std::shared_ptr<void> token(
482 [this, frame, frame_timer](void*)
485 current_encoding_delay_ = frame.get_age_millis();
486 graph_->set_value("frame-time", frame_timer->elapsed() * in_video_format_.fps * 0.5);
490 video_encoder_executor_.begin_invoke([=]() mutable
497 audio_encoder_executor_.begin_invoke([=]() mutable
505 bool ready_for_frame() const
507 return tokens_.permits() > 0;
512 graph_->set_tag(diagnostics::tag_severity::WARNING, "dropped-frame");
515 std::wstring print() const
517 return L"ffmpeg_consumer[" + u16(path_) + L"]";
520 int64_t presentation_frame_age_millis() const
522 return current_encoding_delay_;
527 static int interrupt_cb(void* ctx)
530 return reinterpret_cast<ffmpeg_consumer*>(ctx)->abort_request_;
533 std::shared_ptr<AVStream> open_encoder(
534 const AVCodec& codec,
535 std::map<std::string,
536 std::string>& options,
537 int stream_number_for_media_type)
545 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("avformat_new_stream"));
547 auto enc = st->codec;
551 switch(enc->codec_type)
553 case AVMEDIA_TYPE_VIDEO:
555 enc->time_base = video_graph_out_->inputs[0]->time_base;
556 enc->pix_fmt = static_cast<AVPixelFormat>(video_graph_out_->inputs[0]->format);
557 enc->sample_aspect_ratio = st->sample_aspect_ratio = video_graph_out_->inputs[0]->sample_aspect_ratio;
558 enc->width = video_graph_out_->inputs[0]->w;
559 enc->height = video_graph_out_->inputs[0]->h;
560 enc->bit_rate_tolerance = 400 * 1000000;
564 case AVMEDIA_TYPE_AUDIO:
566 enc->time_base = audio_filter_->get_output_pad_info(stream_number_for_media_type).time_base;
567 enc->sample_fmt = static_cast<AVSampleFormat>(audio_filter_->get_output_pad_info(stream_number_for_media_type).format);
568 enc->sample_rate = audio_filter_->get_output_pad_info(stream_number_for_media_type).sample_rate;
569 enc->channel_layout = audio_filter_->get_output_pad_info(stream_number_for_media_type).channel_layout;
570 enc->channels = audio_filter_->get_output_pad_info(stream_number_for_media_type).channels;
576 setup_codec_defaults(*enc);
578 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
579 enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
581 static const std::array<std::string, 4> char_id_map = {{"v", "a", "d", "s"}};
583 const auto char_id = char_id_map.at(enc->codec_type);
585 const auto codec_opts =
588 boost::regex("^(" + char_id + "?[^:]+):" + char_id + "$"));
590 AVDictionary* av_codec_opts = nullptr;
605 av_codec_opts ? &av_codec_opts : nullptr));
614 AV_DICT_IGNORE_SUFFIX);
618 options[t->key + (codec_opts.find(t->key) != codec_opts.end() ? ":" + char_id : "")] = t->value;
624 AV_DICT_IGNORE_SUFFIX);
627 av_dict_free(&av_codec_opts);
630 if(enc->codec_type == AVMEDIA_TYPE_AUDIO && !(codec.capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
632 CASPAR_ASSERT(enc->frame_size > 0);
633 audio_filter_->set_guaranteed_output_num_samples_per_frame(
634 stream_number_for_media_type,
638 return std::shared_ptr<AVStream>(st, [this](AVStream* st)
640 avcodec_close(st->codec);
644 void configure_video_filters(
645 const AVCodec& codec,
646 std::string filtergraph)
649 avfilter_graph_alloc(),
652 avfilter_graph_free(&p);
655 video_graph_->nb_threads = boost::thread::hardware_concurrency()/2;
656 video_graph_->thread_type = AVFILTER_THREAD_SLICE;
658 const auto sample_aspect_ratio =
659 boost::rational<int>(
660 in_video_format_.square_width,
661 in_video_format_.square_height) /
662 boost::rational<int>(
663 in_video_format_.width,
664 in_video_format_.height);
666 const auto vsrc_options = (boost::format("video_size=%1%x%2%:pix_fmt=%3%:time_base=%4%/%5%:pixel_aspect=%6%/%7%:frame_rate=%8%/%9%")
667 % in_video_format_.width % in_video_format_.height
668 % AVPixelFormat::AV_PIX_FMT_BGRA
669 % in_video_format_.duration % in_video_format_.time_scale
670 % sample_aspect_ratio.numerator() % sample_aspect_ratio.denominator()
671 % in_video_format_.time_scale % in_video_format_.duration).str();
673 AVFilterContext* filt_vsrc = nullptr;
674 FF(avfilter_graph_create_filter(
676 avfilter_get_by_name("buffer"),
677 "ffmpeg_consumer_buffer",
678 vsrc_options.c_str(),
680 video_graph_.get()));
682 AVFilterContext* filt_vsink = nullptr;
683 FF(avfilter_graph_create_filter(
685 avfilter_get_by_name("buffersink"),
686 "ffmpeg_consumer_buffersink",
689 video_graph_.get()));
691 #pragma warning (push)
692 #pragma warning (disable : 4245)
694 FF(av_opt_set_int_list(
699 AV_OPT_SEARCH_CHILDREN));
701 #pragma warning (pop)
703 adjust_video_filter(codec, in_video_format_, filt_vsink, filtergraph);
705 configure_filtergraph(
711 video_graph_in_ = filt_vsrc;
712 video_graph_out_ = filt_vsink;
715 << u16(std::string("\n")
716 + avfilter_graph_dump(
721 void configure_audio_filters(
722 const AVCodec& codec,
723 std::string filtergraph)
725 int num_output_pads = 1;
729 num_output_pads = in_channel_layout_.num_channels;
732 if (num_output_pads > 1)
734 std::string splitfilter = "[a:0]channelsplit=channel_layout=";
736 splitfilter += (boost::format("0x%|1$x|") % create_channel_layout_bitmask(in_channel_layout_.num_channels)).str();
738 for (int i = 0; i < num_output_pads; ++i)
739 splitfilter += "[aout:" + boost::lexical_cast<std::string>(i) + "]";
741 filtergraph = u8(append_filter(u16(filtergraph), u16(splitfilter)));
744 std::vector<audio_output_pad> output_pads(
747 from_terminated_array<int>( codec.supported_samplerates, 0),
748 from_terminated_array<AVSampleFormat>( codec.sample_fmts, AVSampleFormat::AV_SAMPLE_FMT_NONE),
749 from_terminated_array<uint64_t>( codec.channel_layouts, static_cast<uint64_t>(0))));
751 audio_filter_.reset(new audio_filter(
753 boost::rational<int>(1, in_video_format_.audio_sample_rate),
754 in_video_format_.audio_sample_rate,
755 AVSampleFormat::AV_SAMPLE_FMT_S32,
756 create_channel_layout_bitmask(in_channel_layout_.num_channels)) },
761 void configure_filtergraph(
762 AVFilterGraph& graph,
763 const std::string& filtergraph,
764 AVFilterContext& source_ctx,
765 AVFilterContext& sink_ctx)
767 AVFilterInOut* outputs = nullptr;
768 AVFilterInOut* inputs = nullptr;
770 if(!filtergraph.empty())
772 outputs = avfilter_inout_alloc();
773 inputs = avfilter_inout_alloc();
777 CASPAR_VERIFY(outputs && inputs);
779 outputs->name = av_strdup("in");
780 outputs->filter_ctx = &source_ctx;
781 outputs->pad_idx = 0;
782 outputs->next = nullptr;
784 inputs->name = av_strdup("out");
785 inputs->filter_ctx = &sink_ctx;
787 inputs->next = nullptr;
791 avfilter_inout_free(&outputs);
792 avfilter_inout_free(&inputs);
796 FF(avfilter_graph_parse(
812 FF(avfilter_graph_config(
817 void encode_video(core::const_frame frame_ptr, std::shared_ptr<void> token)
822 auto enc = video_st_->codec;
824 if(frame_ptr != core::const_frame::empty())
826 auto src_av_frame = create_frame();
828 const auto sample_aspect_ratio =
829 boost::rational<int>(
830 in_video_format_.square_width,
831 in_video_format_.square_height) /
832 boost::rational<int>(
833 in_video_format_.width,
834 in_video_format_.height);
836 src_av_frame->format = AVPixelFormat::AV_PIX_FMT_BGRA;
837 src_av_frame->width = in_video_format_.width;
838 src_av_frame->height = in_video_format_.height;
839 src_av_frame->sample_aspect_ratio.num = sample_aspect_ratio.numerator();
840 src_av_frame->sample_aspect_ratio.den = sample_aspect_ratio.denominator();
841 src_av_frame->pts = video_pts_;
846 << core::monitor::message("/frame") % video_pts_
847 << core::monitor::message("/path") % path_
848 << core::monitor::message("/fps") % in_video_format_.fps;
850 FF(av_image_fill_arrays(
852 src_av_frame->linesize,
853 frame_ptr.image_data().begin(),
854 static_cast<AVPixelFormat>(src_av_frame->format),
855 in_video_format_.width,
856 in_video_format_.height,
859 FF(av_buffersrc_add_frame(
861 src_av_frame.get()));
868 auto filt_frame = create_frame();
870 ret = av_buffersink_get_frame(
874 video_encoder_executor_.begin_invoke([=]
876 if(ret == AVERROR_EOF)
878 if(enc->codec->capabilities & CODEC_CAP_DELAY)
880 while(encode_av_frame(
882 avcodec_encode_video2,
885 boost::this_thread::yield(); // TODO:
889 else if(ret != AVERROR(EAGAIN))
891 FF_RET(ret, "av_buffersink_get_frame");
893 if (filt_frame->interlaced_frame)
895 if (enc->codec->id == AV_CODEC_ID_MJPEG)
896 enc->field_order = filt_frame->top_field_first ? AV_FIELD_TT : AV_FIELD_BB;
898 enc->field_order = filt_frame->top_field_first ? AV_FIELD_TB : AV_FIELD_BT;
901 enc->field_order = AV_FIELD_PROGRESSIVE;
903 filt_frame->quality = enc->global_quality;
905 if (!enc->me_threshold)
906 filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
910 avcodec_encode_video2,
914 boost::this_thread::yield(); // TODO:
920 void encode_audio(core::const_frame frame_ptr, std::shared_ptr<void> token)
922 if(audio_sts_.empty())
925 if(frame_ptr != core::const_frame::empty())
927 auto src_av_frame = create_frame();
929 src_av_frame->channels = in_channel_layout_.num_channels;
930 src_av_frame->channel_layout = create_channel_layout_bitmask(in_channel_layout_.num_channels);
931 src_av_frame->sample_rate = in_video_format_.audio_sample_rate;
932 src_av_frame->nb_samples = static_cast<int>(frame_ptr.audio_data().size()) / src_av_frame->channels;
933 src_av_frame->format = AV_SAMPLE_FMT_S32;
934 src_av_frame->pts = audio_pts_;
936 audio_pts_ += src_av_frame->nb_samples;
938 FF(av_samples_fill_arrays(
939 src_av_frame->extended_data,
940 src_av_frame->linesize,
941 reinterpret_cast<const std::uint8_t*>(&*frame_ptr.audio_data().begin()),
942 src_av_frame->channels,
943 src_av_frame->nb_samples,
944 static_cast<AVSampleFormat>(src_av_frame->format),
947 audio_filter_->push(0, src_av_frame);
950 for (int pad_id = 0; pad_id < audio_filter_->get_num_output_pads(); ++pad_id)
952 for (auto filt_frame : audio_filter_->poll_all(pad_id))
954 audio_encoder_executor_.begin_invoke([=]
957 *audio_sts_.at(pad_id),
958 avcodec_encode_audio2,
962 boost::this_thread::yield(); // TODO:
967 bool eof = frame_ptr == core::const_frame::empty();
971 audio_encoder_executor_.begin_invoke([=]
973 for (int pad_id = 0; pad_id < audio_filter_->get_num_output_pads(); ++pad_id)
975 auto enc = audio_sts_.at(pad_id)->codec;
977 if (enc->codec->capabilities & CODEC_CAP_DELAY)
979 while (encode_av_frame(
980 *audio_sts_.at(pad_id),
981 avcodec_encode_audio2,
985 boost::this_thread::yield(); // TODO:
994 bool encode_av_frame(
997 const std::shared_ptr<AVFrame>& src_av_frame,
998 std::shared_ptr<void> token)
1001 av_init_packet(&pkt);
1011 if(!got_packet || pkt.size <= 0)
1014 pkt.stream_index = st.index;
1016 if (pkt.pts != AV_NOPTS_VALUE)
1021 st.codec->time_base,
1025 if (pkt.dts != AV_NOPTS_VALUE)
1030 st.codec->time_base,
1038 st.codec->time_base, st.time_base));
1041 std::shared_ptr<AVPacket>(
1053 const std::shared_ptr<AVPacket>& pkt_ptr,
1054 std::shared_ptr<void> token)
1056 write_executor_.begin_invoke([this, pkt_ptr, token]() mutable
1058 FF(av_interleaved_write_frame(
1064 template<typename T>
1065 static boost::optional<T> try_remove_arg(
1066 std::map<std::string, std::string>& options,
1067 const boost::regex& expr)
1069 for(auto it = options.begin(); it != options.end(); ++it)
1071 if(boost::regex_search(it->first, expr))
1073 auto arg = it->second;
1075 return boost::lexical_cast<T>(arg);
1079 return boost::optional<T>();
1082 static std::map<std::string, std::string> remove_options(
1083 std::map<std::string, std::string>& options,
1084 const boost::regex& expr)
1086 std::map<std::string, std::string> result;
1088 auto it = options.begin();
1089 while(it != options.end())
1092 if(boost::regex_search(it->first, what, expr))
1095 what.size() > 0 && what[1].matched
1097 : it->first] = it->second;
1098 it = options.erase(it);
1107 static void to_dict(AVDictionary** dest, const std::map<std::string, std::string>& c)
1109 for (const auto& entry : c)
1113 entry.first.c_str(),
1114 entry.second.c_str(), 0);
1118 static std::map<std::string, std::string> to_map(AVDictionary* dict)
1120 std::map<std::string, std::string> result;
1127 AV_DICT_IGNORE_SUFFIX)
1134 AV_DICT_IGNORE_SUFFIX))
1136 result[t->key] = t->value;
1143 int crc16(const std::string& str)
1145 boost::crc_16_type result;
1147 result.process_bytes(str.data(), str.length());
1149 return result.checksum();
1152 struct ffmpeg_consumer_proxy : public core::frame_consumer
1154 const std::string path_;
1155 const std::string options_;
1156 const bool separate_key_;
1157 const bool mono_streams_;
1158 const bool compatibility_mode_;
1159 int consumer_index_offset_;
1161 std::unique_ptr<ffmpeg_consumer> consumer_;
1162 std::unique_ptr<ffmpeg_consumer> key_only_consumer_;
1166 ffmpeg_consumer_proxy(const std::string& path, const std::string& options, bool separate_key, bool mono_streams, bool compatibility_mode)
1169 , separate_key_(separate_key)
1170 , mono_streams_(mono_streams)
1171 , compatibility_mode_(compatibility_mode)
1172 , consumer_index_offset_(crc16(path))
1176 void initialize(const core::video_format_desc& format_desc, const core::audio_channel_layout& channel_layout, int) override
1179 CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Cannot reinitialize ffmpeg-consumer."));
1181 consumer_.reset(new ffmpeg_consumer(path_, options_, mono_streams_));
1182 consumer_->initialize(format_desc, channel_layout);
1186 boost::filesystem::path fill_file(path_);
1187 auto without_extension = u16(fill_file.parent_path().string() + "/" + fill_file.stem().string());
1188 auto key_file = without_extension + L"_A" + u16(fill_file.extension().string());
1190 key_only_consumer_.reset(new ffmpeg_consumer(u8(key_file), options_, mono_streams_));
1191 key_only_consumer_->initialize(format_desc, channel_layout);
1195 int64_t presentation_frame_age_millis() const override
1197 return consumer_ ? static_cast<int64_t>(consumer_->presentation_frame_age_millis()) : 0;
1200 std::future<bool> send(core::const_frame frame) override
1202 bool ready_for_frame = consumer_->ready_for_frame();
1204 if (ready_for_frame && separate_key_)
1205 ready_for_frame = ready_for_frame && key_only_consumer_->ready_for_frame();
1207 if (ready_for_frame)
1209 consumer_->send(frame);
1212 key_only_consumer_->send(frame.key_only());
1216 consumer_->mark_dropped();
1219 key_only_consumer_->mark_dropped();
1222 return make_ready_future(true);
1225 std::wstring print() const override
1227 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";
1230 std::wstring name() const override
1235 boost::property_tree::wptree info() const override
1237 boost::property_tree::wptree info;
1239 info.add(L"type", L"ffmpeg");
1240 info.add(L"path", u16(path_));
1241 info.add(L"separate_key", separate_key_);
1242 info.add(L"mono_streams", mono_streams_);
1247 bool has_synchronization_clock() const override
1252 int buffer_depth() const override
1257 int index() const override
1259 return compatibility_mode_ ? 200 : 100000 + consumer_index_offset_;
1262 core::monitor::subject& monitor_output() override
1264 return consumer_->monitor_output();
1268 void describe_ffmpeg_consumer(core::help_sink& sink, const core::help_repository& repo)
1270 sink.short_description(L"For streaming/recording the contents of a channel using FFmpeg.");
1271 sink.syntax(L"FILE,STREAM [filename:string],[url:string] {-[ffmpeg_param1:string] [value1:string] {-[ffmpeg_param2:string] [value2:string] {...}}} {[separate_key:SEPARATE_KEY]} {[mono_streams:MONO_STREAMS]}");
1272 sink.para()->text(L"For recording or streaming the contents of a channel using FFmpeg");
1274 ->item(L"filename", L"The filename under the media folder including the extension (decides which kind of container format that will be used).")
1275 ->item(L"url", L"If the filename is given in the form of an URL a network stream will be created instead of a file on disk.")
1276 ->item(L"ffmpeg_paramX", L"A parameter supported by FFmpeg. For example vcodec or acodec etc.")
1277 ->item(L"separate_key", L"If defined will create two files simultaneously -- One for fill and one for key (_A will be appended).")
1278 ->item(L"mono_streams", L"If defined every audio channel will be written to its own audio stream.");
1279 sink.para()->text(L"Examples:");
1280 sink.example(L">> ADD 1 FILE output.mov -vcodec dnxhd");
1281 sink.example(L">> ADD 1 FILE output.mov -vcodec prores");
1282 sink.example(L">> ADD 1 FILE output.mov -vcodec dvvideo");
1283 sink.example(L">> ADD 1 FILE output.mov -vcodec libx264 -preset ultrafast -tune fastdecode -crf 25");
1284 sink.example(L">> ADD 1 FILE output.mov -vcodec dnxhd SEPARATE_KEY", L"for creating output.mov with fill and output_A.mov with key/alpha");
1285 sink.example(L">> ADD 1 FILE output.mxf -vcodec dnxhd MONO_STREAMS", L"for creating output.mxf with every audio channel encoded in its own mono stream.");
1286 sink.example(L">> ADD 1 STREAM udp://<client_ip_address>:9250 -format mpegts -vcodec libx264 -crf 25 -tune zerolatency -preset ultrafast",
1287 L"for streaming over UDP instead of creating a local file.");
1290 spl::shared_ptr<core::frame_consumer> create_ffmpeg_consumer(
1291 const std::vector<std::wstring>& params, core::interaction_sink*, std::vector<spl::shared_ptr<core::video_channel>> channels)
1293 if (params.size() < 1 || (!boost::iequals(params.at(0), L"STREAM") && !boost::iequals(params.at(0), L"FILE")))
1294 return core::frame_consumer::empty();
1296 auto params2 = params;
1297 bool separate_key = get_and_consume_flag(L"SEPARATE_KEY", params2);
1298 bool mono_streams = get_and_consume_flag(L"MONO_STREAMS", params2);
1299 auto compatibility_mode = boost::iequals(params.at(0), L"FILE");
1300 auto path = u8(params2.size() > 1 ? params2.at(1) : L"");
1301 auto args = u8(boost::join(params2, L" "));
1303 return spl::make_shared<ffmpeg_consumer_proxy>(path, args, separate_key, mono_streams, compatibility_mode);
1306 spl::shared_ptr<core::frame_consumer> create_preconfigured_ffmpeg_consumer(
1307 const boost::property_tree::wptree& ptree, core::interaction_sink*, std::vector<spl::shared_ptr<core::video_channel>> channels)
1309 return spl::make_shared<ffmpeg_consumer_proxy>(
1310 u8(ptree_get<std::wstring>(ptree, L"path")),
1311 u8(ptree.get<std::wstring>(L"args", L"")),
1312 ptree.get<bool>(L"separate-key", false),
1313 ptree.get<bool>(L"mono-streams", false),