3 #include "ffmpeg_consumer.h"
5 #include "../ffmpeg_error.h"
6 #include "../producer/util/util.h"
7 #include "../producer/filter/filter.h"
9 #include <common/except.h>
10 #include <common/executor.h>
11 #include <common/assert.h>
12 #include <common/utf.h>
13 #include <common/future.h>
14 #include <common/diagnostics/graph.h>
15 #include <common/env.h>
16 #include <common/scope_exit.h>
17 #include <common/ptree.h>
18 #include <common/param.h>
19 #include <common/semaphore.h>
21 #include <core/consumer/frame_consumer.h>
22 #include <core/frame/frame.h>
23 #include <core/frame/audio_channel_layout.h>
24 #include <core/video_format.h>
25 #include <core/monitor/monitor.h>
26 #include <core/help/help_repository.h>
27 #include <core/help/help_sink.h>
29 #include <boost/noncopyable.hpp>
30 #include <boost/rational.hpp>
31 #include <boost/format.hpp>
32 #include <boost/algorithm/string/predicate.hpp>
33 #include <boost/property_tree/ptree.hpp>
36 #pragma warning(disable: 4244)
37 #pragma warning(disable: 4245)
38 #include <boost/crc.hpp>
41 #include <tbb/atomic.h>
42 #include <tbb/concurrent_queue.h>
43 #include <tbb/parallel_invoke.h>
44 #include <tbb/parallel_for.h>
49 #pragma warning(disable: 4244)
53 #define __STDC_CONSTANT_MACROS
54 #define __STDC_LIMIT_MACROS
55 #include <libavformat/avformat.h>
56 #include <libavcodec/avcodec.h>
57 #include <libavutil/avutil.h>
58 #include <libavutil/frame.h>
59 #include <libavutil/opt.h>
60 #include <libavutil/imgutils.h>
61 #include <libavutil/parseutils.h>
62 #include <libavfilter/avfilter.h>
63 #include <libavfilter/buffersink.h>
64 #include <libavfilter/buffersrc.h>
69 namespace caspar { namespace ffmpeg { namespace {
71 void set_pixel_format(AVFilterContext* sink, AVPixelFormat pix_fmt)
73 #pragma warning (push)
74 #pragma warning (disable : 4245)
76 FF(av_opt_set_int_list(
79 std::vector<AVPixelFormat>({ pix_fmt, AVPixelFormat::AV_PIX_FMT_NONE }).data(),
81 AV_OPT_SEARCH_CHILDREN));
86 void adjust_video_filter(const AVCodec& codec, const core::video_format_desc& in_format, AVFilterContext* sink, std::string& filter)
90 case AV_CODEC_ID_DVVIDEO:
92 if (in_format.format == core::video_format::ntsc)
93 filter = u8(append_filter(u16(filter), L"crop=720:480:0:2"));
95 // Pixel format selection
96 if (in_format.format == core::video_format::ntsc)
97 set_pixel_format(sink, AVPixelFormat::AV_PIX_FMT_YUV411P);
98 else if (in_format.format == core::video_format::pal)
99 set_pixel_format(sink, AVPixelFormat::AV_PIX_FMT_YUV420P);
101 set_pixel_format(sink, AVPixelFormat::AV_PIX_FMT_YUV422P);
104 if (in_format.height == 1080)
105 filter = u8(append_filter(u16(filter), in_format.duration == 1001
107 : L"scale=1440:1080"));
108 else if (in_format.height == 720)
109 filter = u8(append_filter(u16(filter), L"scale=960:720"));
115 void setup_codec_defaults(AVCodecContext& encoder)
117 static const int MEGABIT = 1000000;
119 switch (encoder.codec_id)
121 case AV_CODEC_ID_DNXHD:
122 encoder.bit_rate = 220 * MEGABIT;
125 case AV_CODEC_ID_PRORES:
126 encoder.bit_rate = encoder.width < 1280
131 case AV_CODEC_ID_H264:
132 av_opt_set(encoder.priv_data, "preset", "ultrafast", 0);
133 av_opt_set(encoder.priv_data, "tune", "fastdecode", 0);
134 av_opt_set(encoder.priv_data, "crf", "5", 0);
140 bool is_pcm_s24le_not_supported(const AVFormatContext& container)
142 auto name = std::string(container.oformat->name);
144 if (name == "mp4" || name == "dv")
150 class ffmpeg_consumer
156 const spl::shared_ptr<diagnostics::graph> graph_;
157 core::monitor::subject subject_;
159 boost::filesystem::path full_path_;
161 std::map<std::string, std::string> options_;
163 core::video_format_desc in_video_format_;
164 core::audio_channel_layout in_channel_layout_ = core::audio_channel_layout::invalid();
166 std::shared_ptr<AVFormatContext> oc_;
167 tbb::atomic<bool> abort_request_;
169 std::shared_ptr<AVStream> video_st_;
170 std::shared_ptr<AVStream> audio_st_;
172 std::int64_t video_pts_ = 0;
173 std::int64_t audio_pts_ = 0;
175 AVFilterContext* audio_graph_in_;
176 AVFilterContext* audio_graph_out_;
177 std::shared_ptr<AVFilterGraph> audio_graph_;
179 AVFilterContext* video_graph_in_;
180 AVFilterContext* video_graph_out_;
181 std::shared_ptr<AVFilterGraph> video_graph_;
183 executor video_encoder_executor_;
184 executor audio_encoder_executor_;
186 semaphore tokens_ { 0 };
188 tbb::atomic<int64_t> current_encoding_delay_;
190 executor write_executor_;
199 , audio_encoder_executor_(print() + L" audio_encoder")
200 , video_encoder_executor_(print() + L" video_encoder")
201 , write_executor_(print() + L" io")
203 abort_request_ = false;
204 current_encoding_delay_ = 0;
207 boost::sregex_iterator(
210 boost::regex("-(?<NAME>[^-\\s]+)(\\s+(?<VALUE>[^\\s]+))?"));
211 it != boost::sregex_iterator();
214 options_[(*it)["NAME"].str()] = (*it)["VALUE"].matched ? (*it)["VALUE"].str() : "";
217 if (options_.find("threads") == options_.end())
218 options_["threads"] = "auto";
225 boost::regex("tokens")).get_value_or(2)));
232 video_encoder_executor_.begin_invoke([&] { encode_video(core::const_frame::empty(), nullptr); });
233 audio_encoder_executor_.begin_invoke([&] { encode_audio(core::const_frame::empty(), nullptr); });
235 video_encoder_executor_.stop();
236 audio_encoder_executor_.stop();
237 video_encoder_executor_.join();
238 audio_encoder_executor_.join();
240 video_graph_.reset();
241 audio_graph_.reset();
245 write_packet(nullptr, nullptr);
247 write_executor_.stop();
248 write_executor_.join();
250 FF(av_write_trailer(oc_.get()));
252 if (!(oc_->oformat->flags & AVFMT_NOFILE) && oc_->pb)
260 const core::video_format_desc& format_desc,
261 const core::audio_channel_layout& channel_layout)
265 static boost::regex prot_exp("^.+:.*" );
267 if(!boost::regex_match(
271 if(!full_path_.is_complete())
275 env::media_folder()) +
279 if(boost::filesystem::exists(full_path_))
280 boost::filesystem::remove(full_path_);
282 boost::filesystem::create_directories(full_path_.parent_path());
285 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
286 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
287 graph_->set_text(print());
288 diagnostics::register_graph(graph_);
290 const auto oformat_name =
291 try_remove_arg<std::string>(
293 boost::regex("^f|format$"));
297 FF(avformat_alloc_output_context2(
300 oformat_name && !oformat_name->empty() ? oformat_name->c_str() : nullptr,
301 full_path_.string().c_str()));
305 avformat_free_context);
307 CASPAR_VERIFY(oc_->oformat);
309 oc_->interrupt_callback.callback = ffmpeg_consumer::interrupt_cb;
310 oc_->interrupt_callback.opaque = this;
312 CASPAR_VERIFY(format_desc.format != core::video_format::invalid);
314 in_video_format_ = format_desc;
315 in_channel_layout_ = channel_layout;
317 CASPAR_VERIFY(oc_->oformat);
319 const auto video_codec_name =
320 try_remove_arg<std::string>(
322 boost::regex("^c:v|codec:v|vcodec$"));
324 const auto video_codec =
326 ? avcodec_find_encoder_by_name(video_codec_name->c_str())
327 : avcodec_find_encoder(oc_->oformat->video_codec);
329 const auto audio_codec_name =
330 try_remove_arg<std::string>(
332 boost::regex("^c:a|codec:a|acodec$"));
334 const auto audio_codec =
336 ? avcodec_find_encoder_by_name(audio_codec_name->c_str())
337 : (is_pcm_s24le_not_supported(*oc_)
338 ? avcodec_find_encoder(oc_->oformat->audio_codec)
339 : avcodec_find_encoder_by_name("pcm_s24le"));
342 CASPAR_THROW_EXCEPTION(user_error() << msg_info(
343 "Failed to find video codec " + (video_codec_name
345 : "with id " + boost::lexical_cast<std::string>(
346 oc_->oformat->video_codec))));
348 CASPAR_THROW_EXCEPTION(user_error() << msg_info(
349 "Failed to find audio codec " + (audio_codec_name
351 : "with id " + boost::lexical_cast<std::string>(
352 oc_->oformat->audio_codec))));
357 configure_video_filters(
359 try_remove_arg<std::string>(options_,
360 boost::regex("vf|f:v|filter:v")).get_value_or(""));
362 configure_audio_filters(
364 try_remove_arg<std::string>(options_,
365 boost::regex("af|f:a|filter:a")).get_value_or(""));
371 auto video_options = options_;
372 auto audio_options = options_;
374 video_st_ = open_encoder(
378 audio_st_ = open_encoder(
382 auto it = options_.begin();
383 while(it != options_.end())
385 if(video_options.find(it->first) == video_options.end() || audio_options.find(it->first) == audio_options.end())
386 it = options_.erase(it);
394 AVDictionary* av_opts = nullptr;
398 std::move(options_));
402 av_dict_free(&av_opts);
405 if (!(oc_->oformat->flags & AVFMT_NOFILE))
409 full_path_.string().c_str(),
411 &oc_->interrupt_callback,
415 FF(avformat_write_header(
419 options_ = to_map(av_opts);
430 for (const auto& option : options_)
433 << L"Invalid option: -"
436 << u16(option.second);
448 core::monitor::subject& monitor_output()
453 void send(core::const_frame frame)
455 CASPAR_VERIFY(in_video_format_.format != core::video_format::invalid);
457 auto frame_timer = spl::make_shared<caspar::timer>();
459 std::shared_ptr<void> token(
461 [this, frame, frame_timer](void*)
464 current_encoding_delay_ = frame.get_age_millis();
465 graph_->set_value("frame-time", frame_timer->elapsed() * in_video_format_.fps * 0.5);
469 video_encoder_executor_.begin_invoke([=]() mutable
476 audio_encoder_executor_.begin_invoke([=]() mutable
484 bool ready_for_frame() const
486 return tokens_.permits() > 0;
491 graph_->set_tag(diagnostics::tag_severity::WARNING, "dropped-frame");
494 std::wstring print() const
496 return L"ffmpeg_consumer[" + u16(path_) + L"]";
499 int64_t presentation_frame_age_millis() const
501 return current_encoding_delay_;
506 static int interrupt_cb(void* ctx)
509 return reinterpret_cast<ffmpeg_consumer*>(ctx)->abort_request_;
512 std::shared_ptr<AVStream> open_encoder(
513 const AVCodec& codec,
514 std::map<std::string,
515 std::string>& options)
523 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("avformat_new_stream"));
525 auto enc = st->codec;
529 switch(enc->codec_type)
531 case AVMEDIA_TYPE_VIDEO:
533 enc->time_base = video_graph_out_->inputs[0]->time_base;
534 enc->pix_fmt = static_cast<AVPixelFormat>(video_graph_out_->inputs[0]->format);
535 enc->sample_aspect_ratio = st->sample_aspect_ratio = video_graph_out_->inputs[0]->sample_aspect_ratio;
536 enc->width = video_graph_out_->inputs[0]->w;
537 enc->height = video_graph_out_->inputs[0]->h;
538 enc->bit_rate_tolerance = 400 * 1000000;
542 case AVMEDIA_TYPE_AUDIO:
544 enc->time_base = audio_graph_out_->inputs[0]->time_base;
545 enc->sample_fmt = static_cast<AVSampleFormat>(audio_graph_out_->inputs[0]->format);
546 enc->sample_rate = audio_graph_out_->inputs[0]->sample_rate;
547 enc->channel_layout = audio_graph_out_->inputs[0]->channel_layout;
548 enc->channels = audio_graph_out_->inputs[0]->channels;
554 setup_codec_defaults(*enc);
556 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
557 enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
559 static const std::array<std::string, 4> char_id_map = {{"v", "a", "d", "s"}};
561 const auto char_id = char_id_map.at(enc->codec_type);
563 const auto codec_opts =
566 boost::regex("^(" + char_id + "?[^:]+):" + char_id + "$"));
568 AVDictionary* av_codec_opts = nullptr;
583 av_codec_opts ? &av_codec_opts : nullptr));
592 AV_DICT_IGNORE_SUFFIX);
596 options[t->key + (codec_opts.find(t->key) != codec_opts.end() ? ":" + char_id : "")] = t->value;
602 AV_DICT_IGNORE_SUFFIX);
605 av_dict_free(&av_codec_opts);
608 if(enc->codec_type == AVMEDIA_TYPE_AUDIO && !(codec.capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
610 CASPAR_ASSERT(enc->frame_size > 0);
611 av_buffersink_set_frame_size(audio_graph_out_,
615 return std::shared_ptr<AVStream>(st, [this](AVStream* st)
617 avcodec_close(st->codec);
621 void configure_video_filters(
622 const AVCodec& codec,
623 std::string filtergraph)
626 avfilter_graph_alloc(),
629 avfilter_graph_free(&p);
632 video_graph_->nb_threads = boost::thread::hardware_concurrency()/2;
633 video_graph_->thread_type = AVFILTER_THREAD_SLICE;
635 const auto sample_aspect_ratio =
636 boost::rational<int>(
637 in_video_format_.square_width,
638 in_video_format_.square_height) /
639 boost::rational<int>(
640 in_video_format_.width,
641 in_video_format_.height);
643 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%")
644 % in_video_format_.width % in_video_format_.height
645 % AVPixelFormat::AV_PIX_FMT_BGRA
646 % in_video_format_.duration % in_video_format_.time_scale
647 % sample_aspect_ratio.numerator() % sample_aspect_ratio.denominator()
648 % in_video_format_.time_scale % in_video_format_.duration).str();
650 AVFilterContext* filt_vsrc = nullptr;
651 FF(avfilter_graph_create_filter(
653 avfilter_get_by_name("buffer"),
654 "ffmpeg_consumer_buffer",
655 vsrc_options.c_str(),
657 video_graph_.get()));
659 AVFilterContext* filt_vsink = nullptr;
660 FF(avfilter_graph_create_filter(
662 avfilter_get_by_name("buffersink"),
663 "ffmpeg_consumer_buffersink",
666 video_graph_.get()));
668 #pragma warning (push)
669 #pragma warning (disable : 4245)
671 FF(av_opt_set_int_list(
676 AV_OPT_SEARCH_CHILDREN));
678 #pragma warning (pop)
680 adjust_video_filter(codec, in_video_format_, filt_vsink, filtergraph);
682 configure_filtergraph(
688 video_graph_in_ = filt_vsrc;
689 video_graph_out_ = filt_vsink;
692 << u16(std::string("\n")
693 + avfilter_graph_dump(
698 void configure_audio_filters(
699 const AVCodec& codec,
700 const std::string& filtergraph)
703 avfilter_graph_alloc(),
706 avfilter_graph_free(&p);
709 audio_graph_->nb_threads = boost::thread::hardware_concurrency()/2;
710 audio_graph_->thread_type = AVFILTER_THREAD_SLICE;
712 const auto asrc_options = (boost::format("sample_rate=%1%:sample_fmt=%2%:channels=%3%:time_base=%4%/%5%:channel_layout=%6%")
713 % in_video_format_.audio_sample_rate
714 % av_get_sample_fmt_name(AV_SAMPLE_FMT_S32)
715 % in_channel_layout_.num_channels
716 % 1 % in_video_format_.audio_sample_rate
720 av_get_default_channel_layout(in_channel_layout_.num_channels))).str();
722 AVFilterContext* filt_asrc = nullptr;
723 FF(avfilter_graph_create_filter(
725 avfilter_get_by_name("abuffer"),
726 "ffmpeg_consumer_abuffer",
727 asrc_options.c_str(),
729 audio_graph_.get()));
731 AVFilterContext* filt_asink = nullptr;
732 FF(avfilter_graph_create_filter(
734 avfilter_get_by_name("abuffersink"),
735 "ffmpeg_consumer_abuffersink",
738 audio_graph_.get()));
740 #pragma warning (push)
741 #pragma warning (disable : 4245)
745 "all_channel_counts",
747 AV_OPT_SEARCH_CHILDREN));
749 FF(av_opt_set_int_list(
754 AV_OPT_SEARCH_CHILDREN));
756 FF(av_opt_set_int_list(
759 codec.channel_layouts,
761 AV_OPT_SEARCH_CHILDREN));
763 FF(av_opt_set_int_list(
766 codec.supported_samplerates,
768 AV_OPT_SEARCH_CHILDREN));
770 #pragma warning (pop)
772 configure_filtergraph(
778 audio_graph_in_ = filt_asrc;
779 audio_graph_out_ = filt_asink;
782 << u16(std::string("\n")
783 + avfilter_graph_dump(
788 void configure_filtergraph(
789 AVFilterGraph& graph,
790 const std::string& filtergraph,
791 AVFilterContext& source_ctx,
792 AVFilterContext& sink_ctx)
794 AVFilterInOut* outputs = nullptr;
795 AVFilterInOut* inputs = nullptr;
797 if(!filtergraph.empty())
799 outputs = avfilter_inout_alloc();
800 inputs = avfilter_inout_alloc();
804 CASPAR_VERIFY(outputs && inputs);
806 outputs->name = av_strdup("in");
807 outputs->filter_ctx = &source_ctx;
808 outputs->pad_idx = 0;
809 outputs->next = nullptr;
811 inputs->name = av_strdup("out");
812 inputs->filter_ctx = &sink_ctx;
814 inputs->next = nullptr;
818 avfilter_inout_free(&outputs);
819 avfilter_inout_free(&inputs);
823 FF(avfilter_graph_parse(
839 FF(avfilter_graph_config(
844 void encode_video(core::const_frame frame_ptr, std::shared_ptr<void> token)
849 auto enc = video_st_->codec;
851 if(frame_ptr != core::const_frame::empty())
853 auto src_av_frame = create_frame();
855 const auto sample_aspect_ratio =
856 boost::rational<int>(
857 in_video_format_.square_width,
858 in_video_format_.square_height) /
859 boost::rational<int>(
860 in_video_format_.width,
861 in_video_format_.height);
863 src_av_frame->format = AVPixelFormat::AV_PIX_FMT_BGRA;
864 src_av_frame->width = in_video_format_.width;
865 src_av_frame->height = in_video_format_.height;
866 src_av_frame->sample_aspect_ratio.num = sample_aspect_ratio.numerator();
867 src_av_frame->sample_aspect_ratio.den = sample_aspect_ratio.denominator();
868 src_av_frame->pts = video_pts_;
873 << core::monitor::message("/frame") % video_pts_
874 << core::monitor::message("/path") % path_
875 << core::monitor::message("/fps") % in_video_format_.fps;
877 FF(av_image_fill_arrays(
879 src_av_frame->linesize,
880 frame_ptr.image_data().begin(),
881 static_cast<AVPixelFormat>(src_av_frame->format),
882 in_video_format_.width,
883 in_video_format_.height,
886 FF(av_buffersrc_add_frame(
888 src_av_frame.get()));
895 auto filt_frame = create_frame();
897 ret = av_buffersink_get_frame(
901 video_encoder_executor_.begin_invoke([=]
903 if(ret == AVERROR_EOF)
905 if(enc->codec->capabilities & CODEC_CAP_DELAY)
907 while(encode_av_frame(
909 avcodec_encode_video2,
912 boost::this_thread::yield(); // TODO:
916 else if(ret != AVERROR(EAGAIN))
918 FF_RET(ret, "av_buffersink_get_frame");
920 if (filt_frame->interlaced_frame)
922 if (enc->codec->id == AV_CODEC_ID_MJPEG)
923 enc->field_order = filt_frame->top_field_first ? AV_FIELD_TT : AV_FIELD_BB;
925 enc->field_order = filt_frame->top_field_first ? AV_FIELD_TB : AV_FIELD_BT;
928 enc->field_order = AV_FIELD_PROGRESSIVE;
930 filt_frame->quality = enc->global_quality;
932 if (!enc->me_threshold)
933 filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
937 avcodec_encode_video2,
941 boost::this_thread::yield(); // TODO:
947 void encode_audio(core::const_frame frame_ptr, std::shared_ptr<void> token)
952 auto enc = audio_st_->codec;
954 if(frame_ptr != core::const_frame::empty())
956 auto src_av_frame = create_frame();
958 src_av_frame->channels = in_channel_layout_.num_channels;
959 src_av_frame->channel_layout = av_get_default_channel_layout(in_channel_layout_.num_channels);
960 src_av_frame->sample_rate = in_video_format_.audio_sample_rate;
961 src_av_frame->nb_samples = static_cast<int>(frame_ptr.audio_data().size()) / src_av_frame->channels;
962 src_av_frame->format = AV_SAMPLE_FMT_S32;
963 src_av_frame->pts = audio_pts_;
965 audio_pts_ += src_av_frame->nb_samples;
967 FF(av_samples_fill_arrays(
968 src_av_frame->extended_data,
969 src_av_frame->linesize,
970 reinterpret_cast<const std::uint8_t*>(&*frame_ptr.audio_data().begin()),
971 src_av_frame->channels,
972 src_av_frame->nb_samples,
973 static_cast<AVSampleFormat>(src_av_frame->format),
976 FF(av_buffersrc_add_frame(
978 src_av_frame.get()));
985 auto filt_frame = create_frame();
987 ret = av_buffersink_get_frame(
991 audio_encoder_executor_.begin_invoke([=]
993 if(ret == AVERROR_EOF)
995 if(enc->codec->capabilities & CODEC_CAP_DELAY)
997 while(encode_av_frame(
999 avcodec_encode_audio2,
1003 boost::this_thread::yield(); // TODO:
1007 else if(ret != AVERROR(EAGAIN))
1011 "av_buffersink_get_frame");
1015 avcodec_encode_audio2,
1019 boost::this_thread::yield(); // TODO:
1025 template<typename F>
1026 bool encode_av_frame(
1029 const std::shared_ptr<AVFrame>& src_av_frame,
1030 std::shared_ptr<void> token)
1033 av_init_packet(&pkt);
1043 if(!got_packet || pkt.size <= 0)
1046 pkt.stream_index = st.index;
1048 if (pkt.pts != AV_NOPTS_VALUE)
1053 st.codec->time_base,
1057 if (pkt.dts != AV_NOPTS_VALUE)
1062 st.codec->time_base,
1070 st.codec->time_base, st.time_base));
1073 std::shared_ptr<AVPacket>(
1085 const std::shared_ptr<AVPacket>& pkt_ptr,
1086 std::shared_ptr<void> token)
1088 write_executor_.begin_invoke([this, pkt_ptr, token]() mutable
1090 FF(av_interleaved_write_frame(
1096 template<typename T>
1097 static boost::optional<T> try_remove_arg(
1098 std::map<std::string, std::string>& options,
1099 const boost::regex& expr)
1101 for(auto it = options.begin(); it != options.end(); ++it)
1103 if(boost::regex_search(it->first, expr))
1105 auto arg = it->second;
1107 return boost::lexical_cast<T>(arg);
1111 return boost::optional<T>();
1114 static std::map<std::string, std::string> remove_options(
1115 std::map<std::string, std::string>& options,
1116 const boost::regex& expr)
1118 std::map<std::string, std::string> result;
1120 auto it = options.begin();
1121 while(it != options.end())
1124 if(boost::regex_search(it->first, what, expr))
1127 what.size() > 0 && what[1].matched
1129 : it->first] = it->second;
1130 it = options.erase(it);
1139 static void to_dict(AVDictionary** dest, const std::map<std::string, std::string>& c)
1141 for (const auto& entry : c)
1145 entry.first.c_str(),
1146 entry.second.c_str(), 0);
1150 static std::map<std::string, std::string> to_map(AVDictionary* dict)
1152 std::map<std::string, std::string> result;
1159 AV_DICT_IGNORE_SUFFIX)
1166 AV_DICT_IGNORE_SUFFIX))
1168 result[t->key] = t->value;
1175 int crc16(const std::string& str)
1177 boost::crc_16_type result;
1179 result.process_bytes(str.data(), str.length());
1181 return result.checksum();
1184 struct ffmpeg_consumer_proxy : public core::frame_consumer
1186 const std::string path_;
1187 const std::string options_;
1188 const bool separate_key_;
1189 const bool compatibility_mode_;
1190 int consumer_index_offset_;
1192 std::unique_ptr<ffmpeg_consumer> consumer_;
1193 std::unique_ptr<ffmpeg_consumer> key_only_consumer_;
1197 ffmpeg_consumer_proxy(const std::string& path, const std::string& options, bool separate_key, bool compatibility_mode)
1200 , separate_key_(separate_key)
1201 , compatibility_mode_(compatibility_mode)
1202 , consumer_index_offset_(crc16(path))
1206 void initialize(const core::video_format_desc& format_desc, const core::audio_channel_layout& channel_layout, int) override
1209 CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Cannot reinitialize ffmpeg-consumer."));
1211 consumer_.reset(new ffmpeg_consumer(path_, options_));
1212 consumer_->initialize(format_desc, channel_layout);
1216 boost::filesystem::path fill_file(path_);
1217 auto without_extension = u16(fill_file.parent_path().string() + "/" + fill_file.stem().string());
1218 auto key_file = without_extension + L"_A" + u16(fill_file.extension().string());
1220 key_only_consumer_.reset(new ffmpeg_consumer(u8(key_file), options_));
1221 key_only_consumer_->initialize(format_desc, channel_layout);
1225 int64_t presentation_frame_age_millis() const override
1227 return consumer_ ? static_cast<int64_t>(consumer_->presentation_frame_age_millis()) : 0;
1230 std::future<bool> send(core::const_frame frame) override
1232 bool ready_for_frame = consumer_->ready_for_frame();
1234 if (ready_for_frame && separate_key_)
1235 ready_for_frame = ready_for_frame && key_only_consumer_->ready_for_frame();
1237 if (ready_for_frame)
1239 consumer_->send(frame);
1242 key_only_consumer_->send(frame.key_only());
1246 consumer_->mark_dropped();
1249 key_only_consumer_->mark_dropped();
1252 return make_ready_future(true);
1255 std::wstring print() const override
1257 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";
1260 std::wstring name() const override
1265 boost::property_tree::wptree info() const override
1267 boost::property_tree::wptree info;
1268 info.add(L"type", L"ffmpeg");
1269 info.add(L"path", u16(path_));
1270 info.add(L"separate_key", separate_key_);
1274 bool has_synchronization_clock() const override
1279 int buffer_depth() const override
1284 int index() const override
1286 return compatibility_mode_ ? 200 : 100000 + consumer_index_offset_;
1289 core::monitor::subject& monitor_output() override
1291 return consumer_->monitor_output();
1297 void describe_streaming_consumer(core::help_sink& sink, const core::help_repository& repo)
1299 sink.short_description(L"For streaming/recording the contents of a channel using FFmpeg.");
1300 sink.syntax(L"FILE,STREAM [filename:string],[url:string] {-[ffmpeg_param1:string] [value1:string] {-[ffmpeg_param2:string] [value2:string] {...}}}");
1301 sink.para()->text(L"For recording or streaming the contents of a channel using FFmpeg");
1303 ->item(L"filename", L"The filename under the media folder including the extension (decides which kind of container format that will be used).")
1304 ->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.")
1305 ->item(L"ffmpeg_paramX", L"A parameter supported by FFmpeg. For example vcodec or acodec etc.");
1306 sink.para()->text(L"Examples:");
1307 sink.example(L">> ADD 1 FILE output.mov -vcodec dnxhd");
1308 sink.example(L">> ADD 1 FILE output.mov -vcodec prores");
1309 sink.example(L">> ADD 1 FILE output.mov -vcodec dvvideo");
1310 sink.example(L">> ADD 1 FILE output.mov -vcodec libx264 -preset ultrafast -tune fastdecode -crf 25");
1311 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");
1312 sink.example(L">> ADD 1 STREAM udp://<client_ip_address>:9250 -format mpegts -vcodec libx264 -crf 25 -tune zerolatency -preset ultrafast",
1313 L"for streaming over UDP instead of creating a local file.");
1316 spl::shared_ptr<core::frame_consumer> create_streaming_consumer(
1317 const std::vector<std::wstring>& params, core::interaction_sink*, std::vector<spl::shared_ptr<core::video_channel>> channels)
1319 if (params.size() < 1 || (!boost::iequals(params.at(0), L"STREAM") && !boost::iequals(params.at(0), L"FILE")))
1320 return core::frame_consumer::empty();
1322 auto params2 = params;
1323 auto separate_key_it = std::find_if(params2.begin(), params2.end(), param_comparer(L"SEPARATE_KEY"));
1324 bool separate_key = false;
1326 if (separate_key_it != params2.end())
1328 separate_key = true;
1329 params2.erase(separate_key_it);
1332 auto compatibility_mode = boost::iequals(params.at(0), L"FILE");
1333 auto path = u8(params2.size() > 1 ? params2.at(1) : L"");
1334 auto args = u8(boost::join(params2, L" "));
1336 return spl::make_shared<ffmpeg_consumer_proxy>(path, args, separate_key, compatibility_mode);
1339 spl::shared_ptr<core::frame_consumer> create_preconfigured_streaming_consumer(
1340 const boost::property_tree::wptree& ptree, core::interaction_sink*, std::vector<spl::shared_ptr<core::video_channel>> channels)
1342 return spl::make_shared<ffmpeg_consumer_proxy>(
1343 u8(ptree_get<std::wstring>(ptree, L"path")),
1344 u8(ptree.get<std::wstring>(L"args", L"")),
1345 ptree.get<bool>(L"separate-key", false),