3 #include "ffmpeg_consumer.h"
5 #include "../ffmpeg_error.h"
7 #include <common/except.h>
8 #include <common/executor.h>
9 #include <common/assert.h>
10 #include <common/utf.h>
11 #include <common/future.h>
12 #include <common/env.h>
13 #include <common/scope_exit.h>
15 #include <core/consumer/frame_consumer.h>
16 #include <core/frame/frame.h>
17 #include <core/frame/audio_channel_layout.h>
18 #include <core/video_format.h>
19 #include <core/monitor/monitor.h>
20 #include <core/help/help_repository.h>
21 #include <core/help/help_sink.h>
23 #include <boost/noncopyable.hpp>
24 #include <boost/rational.hpp>
25 #include <boost/format.hpp>
26 #include <boost/algorithm/string/predicate.hpp>
27 #include <boost/property_tree/ptree.hpp>
30 #pragma warning(disable: 4244)
31 #pragma warning(disable: 4245)
32 #include <boost/crc.hpp>
35 #include <tbb/atomic.h>
36 #include <tbb/concurrent_queue.h>
37 #include <tbb/parallel_invoke.h>
38 #include <tbb/parallel_for.h>
43 #pragma warning(disable: 4244)
47 #define __STDC_CONSTANT_MACROS
48 #define __STDC_LIMIT_MACROS
49 #include <libavformat/avformat.h>
50 #include <libavcodec/avcodec.h>
51 #include <libavutil/avutil.h>
52 #include <libavutil/frame.h>
53 #include <libavutil/opt.h>
54 #include <libavutil/imgutils.h>
55 #include <libavutil/parseutils.h>
56 #include <libavfilter/avfilter.h>
57 #include <libavfilter/buffersink.h>
58 #include <libavfilter/buffersrc.h>
63 namespace caspar { namespace ffmpeg {
65 int crc16(const std::string& str)
67 boost::crc_16_type result;
69 result.process_bytes(str.data(), str.length());
71 return result.checksum();
74 class streaming_consumer final : public core::frame_consumer
80 core::monitor::subject subject_;
81 boost::filesystem::path path_;
82 int consumer_index_offset_;
84 std::map<std::string, std::string> options_;
85 bool compatibility_mode_;
87 core::video_format_desc in_video_format_;
88 core::audio_channel_layout in_channel_layout_ = core::audio_channel_layout::invalid();
90 std::shared_ptr<AVFormatContext> oc_;
91 tbb::atomic<bool> abort_request_;
93 std::shared_ptr<AVStream> video_st_;
94 std::shared_ptr<AVStream> audio_st_;
96 std::int64_t video_pts_;
97 std::int64_t audio_pts_;
99 AVFilterContext* audio_graph_in_;
100 AVFilterContext* audio_graph_out_;
101 std::shared_ptr<AVFilterGraph> audio_graph_;
102 std::shared_ptr<AVBitStreamFilterContext> audio_bitstream_filter_;
104 AVFilterContext* video_graph_in_;
105 AVFilterContext* video_graph_out_;
106 std::shared_ptr<AVFilterGraph> video_graph_;
107 std::shared_ptr<AVBitStreamFilterContext> video_bitstream_filter_;
111 executor video_encoder_executor_;
112 executor audio_encoder_executor_;
114 tbb::atomic<int> tokens_;
115 boost::mutex tokens_mutex_;
116 boost::condition_variable tokens_cond_;
117 tbb::atomic<int64_t> current_encoding_delay_;
119 executor write_executor_;
126 bool compatibility_mode)
128 , consumer_index_offset_(crc16(path))
129 , compatibility_mode_(compatibility_mode)
133 , audio_encoder_executor_(print() + L" audio_encoder")
134 , video_encoder_executor_(print() + L" video_encoder")
135 , write_executor_(print() + L" io")
137 abort_request_ = false;
138 current_encoding_delay_ = 0;
141 boost::sregex_iterator(
144 boost::regex("-(?<NAME>[^-\\s]+)(\\s+(?<VALUE>[^\\s]+))?"));
145 it != boost::sregex_iterator();
148 options_[(*it)["NAME"].str()] = (*it)["VALUE"].matched ? (*it)["VALUE"].str() : "";
151 if (options_.find("threads") == options_.end())
152 options_["threads"] = "auto";
159 boost::regex("tokens")).get_value_or(2));
162 ~streaming_consumer()
166 video_encoder_executor_.begin_invoke([&] { encode_video(core::const_frame::empty(), nullptr); });
167 audio_encoder_executor_.begin_invoke([&] { encode_audio(core::const_frame::empty(), nullptr); });
169 video_encoder_executor_.stop();
170 audio_encoder_executor_.stop();
171 video_encoder_executor_.join();
172 audio_encoder_executor_.join();
174 video_graph_.reset();
175 audio_graph_.reset();
179 write_packet(nullptr, nullptr);
181 write_executor_.stop();
182 write_executor_.join();
184 FF(av_write_trailer(oc_.get()));
186 if (!(oc_->oformat->flags & AVFMT_NOFILE) && oc_->pb)
194 const core::video_format_desc& format_desc,
195 const core::audio_channel_layout& channel_layout,
196 int channel_index) override
200 static boost::regex prot_exp("^.+:.*" );
202 const auto overwrite =
203 try_remove_arg<std::string>(
205 boost::regex("y")) != boost::none;
207 if(!boost::regex_match(
211 if(!path_.is_complete())
215 env::media_folder()) +
219 if(boost::filesystem::exists(path_))
221 if(!overwrite && !compatibility_mode_)
222 BOOST_THROW_EXCEPTION(invalid_argument() << msg_info("File exists"));
224 boost::filesystem::remove(path_);
228 const auto oformat_name =
229 try_remove_arg<std::string>(
231 boost::regex("^f|format$"));
235 FF(avformat_alloc_output_context2(
238 oformat_name && !oformat_name->empty() ? oformat_name->c_str() : nullptr,
239 path_.string().c_str()));
243 avformat_free_context);
245 CASPAR_VERIFY(oc_->oformat);
247 oc_->interrupt_callback.callback = streaming_consumer::interrupt_cb;
248 oc_->interrupt_callback.opaque = this;
250 CASPAR_VERIFY(format_desc.format != core::video_format::invalid);
252 in_video_format_ = format_desc;
253 in_channel_layout_ = channel_layout;
255 CASPAR_VERIFY(oc_->oformat);
257 const auto video_codec_name =
258 try_remove_arg<std::string>(
260 boost::regex("^c:v|codec:v|vcodec$"));
262 const auto video_codec =
264 ? avcodec_find_encoder_by_name(video_codec_name->c_str())
265 : avcodec_find_encoder(oc_->oformat->video_codec);
267 const auto audio_codec_name =
268 try_remove_arg<std::string>(
270 boost::regex("^c:a|codec:a|acodec$"));
272 const auto audio_codec =
274 ? avcodec_find_encoder_by_name(audio_codec_name->c_str())
275 : avcodec_find_encoder(oc_->oformat->audio_codec);
278 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(
279 "Failed to find video codec " + (video_codec_name
281 : "with id " + boost::lexical_cast<std::string>(
282 oc_->oformat->video_codec))));
284 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info(
285 "Failed to find audio codec " + (audio_codec_name
287 : "with id " + boost::lexical_cast<std::string>(
288 oc_->oformat->audio_codec))));
293 configure_video_filters(
295 try_remove_arg<std::string>(options_,
296 boost::regex("vf|f:v|filter:v")).get_value_or(""));
298 configure_audio_filters(
300 try_remove_arg<std::string>(options_,
301 boost::regex("af|f:a|filter:a")).get_value_or(""));
306 configue_audio_bistream_filters(options_);
307 configue_video_bistream_filters(options_);
313 auto video_options = options_;
314 auto audio_options = options_;
316 video_st_ = open_encoder(
320 audio_st_ = open_encoder(
324 auto it = options_.begin();
325 while(it != options_.end())
327 if(video_options.find(it->first) == video_options.end() || audio_options.find(it->first) == audio_options.end())
328 it = options_.erase(it);
336 AVDictionary* av_opts = nullptr;
340 std::move(options_));
344 av_dict_free(&av_opts);
347 if (!(oc_->oformat->flags & AVFMT_NOFILE))
351 path_.string().c_str(),
353 &oc_->interrupt_callback,
357 FF(avformat_write_header(
361 options_ = to_map(av_opts);
372 for (const auto& option : options_)
375 << L"Invalid option: -"
378 << u16(option.second);
390 core::monitor::subject& monitor_output() override
395 std::wstring name() const override
400 std::future<bool> send(core::const_frame frame) override
402 CASPAR_VERIFY(in_video_format_.format != core::video_format::invalid);
405 std::shared_ptr<void> token(
410 tokens_cond_.notify_one();
411 current_encoding_delay_ = frame.get_age_millis();
414 return executor_.begin_invoke([=]() -> bool
416 boost::unique_lock<boost::mutex> tokens_lock(tokens_mutex_);
419 tokens_cond_.wait(tokens_lock);
421 video_encoder_executor_.begin_invoke([=]() mutable
428 audio_encoder_executor_.begin_invoke([=]() mutable
439 std::wstring print() const override
441 return L"streaming_consumer[" + u16(path_.string()) + L"]";
444 virtual boost::property_tree::wptree info() const override
446 boost::property_tree::wptree info;
447 info.add(L"type", L"stream");
448 info.add(L"path", path_.wstring());
452 bool has_synchronization_clock() const override
457 int buffer_depth() const override
462 int index() const override
464 return compatibility_mode_ ? 200 : 100000 + consumer_index_offset_;
467 int64_t presentation_frame_age_millis() const override
469 return current_encoding_delay_;
474 static int interrupt_cb(void* ctx)
477 return reinterpret_cast<streaming_consumer*>(ctx)->abort_request_;
480 std::shared_ptr<AVStream> open_encoder(
481 const AVCodec& codec,
482 std::map<std::string,
483 std::string>& options)
491 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("av_new_stream"));
493 auto enc = st->codec;
497 switch(enc->codec_type)
499 case AVMEDIA_TYPE_VIDEO:
501 enc->time_base = video_graph_out_->inputs[0]->time_base;
502 enc->pix_fmt = static_cast<AVPixelFormat>(video_graph_out_->inputs[0]->format);
503 enc->sample_aspect_ratio = st->sample_aspect_ratio = video_graph_out_->inputs[0]->sample_aspect_ratio;
504 enc->width = video_graph_out_->inputs[0]->w;
505 enc->height = video_graph_out_->inputs[0]->h;
506 enc->bit_rate_tolerance = 400 * 1000000;
510 case AVMEDIA_TYPE_AUDIO:
512 enc->time_base = audio_graph_out_->inputs[0]->time_base;
513 enc->sample_fmt = static_cast<AVSampleFormat>(audio_graph_out_->inputs[0]->format);
514 enc->sample_rate = audio_graph_out_->inputs[0]->sample_rate;
515 enc->channel_layout = audio_graph_out_->inputs[0]->channel_layout;
516 enc->channels = audio_graph_out_->inputs[0]->channels;
522 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
523 enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
525 static const std::array<std::string, 4> char_id_map = {{"v", "a", "d", "s"}};
527 const auto char_id = char_id_map.at(enc->codec_type);
529 const auto codec_opts =
532 boost::regex("^(" + char_id + "?[^:]+):" + char_id + "$"));
534 AVDictionary* av_codec_opts = nullptr;
549 av_codec_opts ? &av_codec_opts : nullptr));
558 AV_DICT_IGNORE_SUFFIX);
562 options[t->key + (codec_opts.find(t->key) != codec_opts.end() ? ":" + char_id : "")] = t->value;
568 AV_DICT_IGNORE_SUFFIX);
571 av_dict_free(&av_codec_opts);
574 if(enc->codec_type == AVMEDIA_TYPE_AUDIO && !(codec.capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
576 CASPAR_ASSERT(enc->frame_size > 0);
577 av_buffersink_set_frame_size(audio_graph_out_,
581 return std::shared_ptr<AVStream>(st, [this](AVStream* st)
583 avcodec_close(st->codec);
587 void configue_audio_bistream_filters(
588 std::map<std::string, std::string>& options)
590 const auto audio_bitstream_filter_str =
591 try_remove_arg<std::string>(
593 boost::regex("^bsf:a|absf$"));
595 const auto audio_bitstream_filter =
596 audio_bitstream_filter_str
597 ? av_bitstream_filter_init(audio_bitstream_filter_str->c_str())
600 CASPAR_VERIFY(!audio_bitstream_filter_str || audio_bitstream_filter);
602 if(audio_bitstream_filter)
604 audio_bitstream_filter_.reset(
605 audio_bitstream_filter,
606 av_bitstream_filter_close);
609 if(audio_bitstream_filter_str && !audio_bitstream_filter_)
610 options["bsf:a"] = *audio_bitstream_filter_str;
613 void configue_video_bistream_filters(
614 std::map<std::string, std::string>& options)
616 const auto video_bitstream_filter_str =
617 try_remove_arg<std::string>(
619 boost::regex("^bsf:v|vbsf$"));
621 const auto video_bitstream_filter =
622 video_bitstream_filter_str
623 ? av_bitstream_filter_init(video_bitstream_filter_str->c_str())
626 CASPAR_VERIFY(!video_bitstream_filter_str || video_bitstream_filter);
628 if(video_bitstream_filter)
630 video_bitstream_filter_.reset(
631 video_bitstream_filter,
632 av_bitstream_filter_close);
635 if(video_bitstream_filter_str && !video_bitstream_filter_)
636 options["bsf:v"] = *video_bitstream_filter_str;
639 void configure_video_filters(
640 const AVCodec& codec,
641 const std::string& filtergraph)
644 avfilter_graph_alloc(),
647 avfilter_graph_free(&p);
650 video_graph_->nb_threads = boost::thread::hardware_concurrency()/2;
651 video_graph_->thread_type = AVFILTER_THREAD_SLICE;
653 const auto sample_aspect_ratio =
654 boost::rational<int>(
655 in_video_format_.square_width,
656 in_video_format_.square_height) /
657 boost::rational<int>(
658 in_video_format_.width,
659 in_video_format_.height);
661 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%")
662 % in_video_format_.width % in_video_format_.height
664 % in_video_format_.duration % in_video_format_.time_scale
665 % sample_aspect_ratio.numerator() % sample_aspect_ratio.denominator()
666 % in_video_format_.time_scale % in_video_format_.duration).str();
668 AVFilterContext* filt_vsrc = nullptr;
669 FF(avfilter_graph_create_filter(
671 avfilter_get_by_name("buffer"),
672 "ffmpeg_consumer_buffer",
673 vsrc_options.c_str(),
675 video_graph_.get()));
677 AVFilterContext* filt_vsink = nullptr;
678 FF(avfilter_graph_create_filter(
680 avfilter_get_by_name("buffersink"),
681 "ffmpeg_consumer_buffersink",
684 video_graph_.get()));
686 #pragma warning (push)
687 #pragma warning (disable : 4245)
689 FF(av_opt_set_int_list(
694 AV_OPT_SEARCH_CHILDREN));
696 #pragma warning (pop)
698 configure_filtergraph(
704 video_graph_in_ = filt_vsrc;
705 video_graph_out_ = filt_vsink;
708 << u16(std::string("\n")
709 + avfilter_graph_dump(
714 void configure_audio_filters(
715 const AVCodec& codec,
716 const std::string& filtergraph)
719 avfilter_graph_alloc(),
722 avfilter_graph_free(&p);
725 audio_graph_->nb_threads = boost::thread::hardware_concurrency()/2;
726 audio_graph_->thread_type = AVFILTER_THREAD_SLICE;
728 const auto asrc_options = (boost::format("sample_rate=%1%:sample_fmt=%2%:channels=%3%:time_base=%4%/%5%:channel_layout=%6%")
729 % in_video_format_.audio_sample_rate
730 % av_get_sample_fmt_name(AV_SAMPLE_FMT_S32)
731 % in_channel_layout_.num_channels
732 % 1 % in_video_format_.audio_sample_rate
736 av_get_default_channel_layout(in_channel_layout_.num_channels))).str();
738 AVFilterContext* filt_asrc = nullptr;
739 FF(avfilter_graph_create_filter(
741 avfilter_get_by_name("abuffer"),
742 "ffmpeg_consumer_abuffer",
743 asrc_options.c_str(),
745 audio_graph_.get()));
747 AVFilterContext* filt_asink = nullptr;
748 FF(avfilter_graph_create_filter(
750 avfilter_get_by_name("abuffersink"),
751 "ffmpeg_consumer_abuffersink",
754 audio_graph_.get()));
756 #pragma warning (push)
757 #pragma warning (disable : 4245)
761 "all_channel_counts",
763 AV_OPT_SEARCH_CHILDREN));
765 FF(av_opt_set_int_list(
770 AV_OPT_SEARCH_CHILDREN));
772 FF(av_opt_set_int_list(
775 codec.channel_layouts,
777 AV_OPT_SEARCH_CHILDREN));
779 FF(av_opt_set_int_list(
782 codec.supported_samplerates,
784 AV_OPT_SEARCH_CHILDREN));
786 #pragma warning (pop)
788 configure_filtergraph(
794 audio_graph_in_ = filt_asrc;
795 audio_graph_out_ = filt_asink;
798 << u16(std::string("\n")
799 + avfilter_graph_dump(
804 void configure_filtergraph(
805 AVFilterGraph& graph,
806 const std::string& filtergraph,
807 AVFilterContext& source_ctx,
808 AVFilterContext& sink_ctx)
810 AVFilterInOut* outputs = nullptr;
811 AVFilterInOut* inputs = nullptr;
815 if(!filtergraph.empty())
817 outputs = avfilter_inout_alloc();
818 inputs = avfilter_inout_alloc();
820 CASPAR_VERIFY(outputs && inputs);
822 outputs->name = av_strdup("in");
823 outputs->filter_ctx = &source_ctx;
824 outputs->pad_idx = 0;
825 outputs->next = nullptr;
827 inputs->name = av_strdup("out");
828 inputs->filter_ctx = &sink_ctx;
830 inputs->next = nullptr;
832 FF(avfilter_graph_parse(
848 FF(avfilter_graph_config(
854 avfilter_inout_free(&outputs);
855 avfilter_inout_free(&inputs);
860 void encode_video(core::const_frame frame_ptr, std::shared_ptr<void> token)
865 auto enc = video_st_->codec;
867 std::shared_ptr<AVFrame> src_av_frame;
869 if(frame_ptr != core::const_frame::empty())
873 [frame_ptr](AVFrame* frame)
875 av_frame_free(&frame);
878 avcodec_get_frame_defaults(src_av_frame.get());
880 const auto sample_aspect_ratio =
881 boost::rational<int>(
882 in_video_format_.square_width,
883 in_video_format_.square_height) /
884 boost::rational<int>(
885 in_video_format_.width,
886 in_video_format_.height);
888 src_av_frame->format = AV_PIX_FMT_BGRA;
889 src_av_frame->width = in_video_format_.width;
890 src_av_frame->height = in_video_format_.height;
891 src_av_frame->sample_aspect_ratio.num = sample_aspect_ratio.numerator();
892 src_av_frame->sample_aspect_ratio.den = sample_aspect_ratio.denominator();
893 src_av_frame->pts = video_pts_;
897 FF(av_image_fill_arrays(
899 src_av_frame->linesize,
900 frame_ptr.image_data().begin(),
901 static_cast<AVPixelFormat>(src_av_frame->format),
902 in_video_format_.width,
903 in_video_format_.height,
906 FF(av_buffersrc_add_frame(
908 src_av_frame.get()));
915 std::shared_ptr<AVFrame> filt_frame(
922 ret = av_buffersink_get_frame(
926 video_encoder_executor_.begin_invoke([=]
928 if(ret == AVERROR_EOF)
930 if(enc->codec->capabilities & CODEC_CAP_DELAY)
932 while(encode_av_frame(
934 video_bitstream_filter_.get(),
935 avcodec_encode_video2,
938 boost::this_thread::yield(); // TODO:
942 else if(ret != AVERROR(EAGAIN))
944 FF_RET(ret, "av_buffersink_get_frame");
946 if (filt_frame->interlaced_frame)
948 if (enc->codec->id == AV_CODEC_ID_MJPEG)
949 enc->field_order = filt_frame->top_field_first ? AV_FIELD_TT : AV_FIELD_BB;
951 enc->field_order = filt_frame->top_field_first ? AV_FIELD_TB : AV_FIELD_BT;
954 enc->field_order = AV_FIELD_PROGRESSIVE;
956 filt_frame->quality = enc->global_quality;
958 if (!enc->me_threshold)
959 filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
963 video_bitstream_filter_.get(),
964 avcodec_encode_video2,
968 boost::this_thread::yield(); // TODO:
974 void encode_audio(core::const_frame frame_ptr, std::shared_ptr<void> token)
979 auto enc = audio_st_->codec;
981 std::shared_ptr<AVFrame> src_av_frame;
983 if(frame_ptr != core::const_frame::empty())
992 src_av_frame->channels = in_channel_layout_.num_channels;
993 src_av_frame->channel_layout = av_get_default_channel_layout(in_channel_layout_.num_channels);
994 src_av_frame->sample_rate = in_video_format_.audio_sample_rate;
995 src_av_frame->nb_samples = static_cast<int>(frame_ptr.audio_data().size()) / src_av_frame->channels;
996 src_av_frame->format = AV_SAMPLE_FMT_S32;
997 src_av_frame->pts = audio_pts_;
999 audio_pts_ += src_av_frame->nb_samples;
1001 FF(av_samples_fill_arrays(
1002 src_av_frame->extended_data,
1003 src_av_frame->linesize,
1004 reinterpret_cast<const std::uint8_t*>(&*frame_ptr.audio_data().begin()),
1005 src_av_frame->channels,
1006 src_av_frame->nb_samples,
1007 static_cast<AVSampleFormat>(src_av_frame->format),
1010 FF(av_buffersrc_add_frame(
1012 src_av_frame.get()));
1019 std::shared_ptr<AVFrame> filt_frame(
1026 ret = av_buffersink_get_frame(
1030 audio_encoder_executor_.begin_invoke([=]
1032 if(ret == AVERROR_EOF)
1034 if(enc->codec->capabilities & CODEC_CAP_DELAY)
1036 while(encode_av_frame(
1038 audio_bitstream_filter_.get(),
1039 avcodec_encode_audio2,
1043 boost::this_thread::yield(); // TODO:
1047 else if(ret != AVERROR(EAGAIN))
1051 "av_buffersink_get_frame");
1055 audio_bitstream_filter_.get(),
1056 avcodec_encode_audio2,
1060 boost::this_thread::yield(); // TODO:
1066 template<typename F>
1067 bool encode_av_frame(
1069 AVBitStreamFilterContext* bsfc,
1071 const std::shared_ptr<AVFrame>& src_av_frame,
1072 std::shared_ptr<void> token)
1075 av_init_packet(&pkt);
1085 if(!got_packet || pkt.size <= 0)
1088 pkt.stream_index = st.index;
1094 auto a = av_bitstream_filter_filter(
1102 pkt.flags & AV_PKT_FLAG_KEY);
1104 if(a == 0 && new_pkt.data != pkt.data && new_pkt.destruct)
1106 auto t = reinterpret_cast<std::uint8_t*>(av_malloc(new_pkt.size + FF_INPUT_BUFFER_PADDING_SIZE));
1118 FF_INPUT_BUFFER_PADDING_SIZE);
1121 new_pkt.buf = nullptr;
1124 a = AVERROR(ENOMEM);
1127 av_free_packet(&pkt);
1131 "av_bitstream_filter_filter");
1137 av_buffer_default_free,
1141 CASPAR_VERIFY(new_pkt.buf);
1146 if (pkt.pts != AV_NOPTS_VALUE)
1151 st.codec->time_base,
1155 if (pkt.dts != AV_NOPTS_VALUE)
1160 st.codec->time_base,
1168 st.codec->time_base, st.time_base));
1171 std::shared_ptr<AVPacket>(
1183 const std::shared_ptr<AVPacket>& pkt_ptr,
1184 std::shared_ptr<void> token)
1186 write_executor_.begin_invoke([this, pkt_ptr, token]() mutable
1188 FF(av_interleaved_write_frame(
1194 template<typename T>
1195 static boost::optional<T> try_remove_arg(
1196 std::map<std::string, std::string>& options,
1197 const boost::regex& expr)
1199 for(auto it = options.begin(); it != options.end(); ++it)
1201 if(boost::regex_search(it->first, expr))
1203 auto arg = it->second;
1205 return boost::lexical_cast<T>(arg);
1209 return boost::optional<T>();
1212 static std::map<std::string, std::string> remove_options(
1213 std::map<std::string, std::string>& options,
1214 const boost::regex& expr)
1216 std::map<std::string, std::string> result;
1218 auto it = options.begin();
1219 while(it != options.end())
1222 if(boost::regex_search(it->first, what, expr))
1225 what.size() > 0 && what[1].matched
1227 : it->first] = it->second;
1228 it = options.erase(it);
1237 static void to_dict(AVDictionary** dest, const std::map<std::string, std::string>& c)
1239 for (const auto& entry : c)
1243 entry.first.c_str(),
1244 entry.second.c_str(), 0);
1248 static std::map<std::string, std::string> to_map(AVDictionary* dict)
1250 std::map<std::string, std::string> result;
1257 AV_DICT_IGNORE_SUFFIX)
1264 AV_DICT_IGNORE_SUFFIX))
1266 result[t->key] = t->value;
1273 void describe_streaming_consumer(core::help_sink& sink, const core::help_repository& repo)
1275 sink.short_description(L"For streaming the contents of a channel using FFMpeg.");
1276 sink.syntax(L"STREAM [url:string] {-[ffmpeg_param1:string] [value1:string] {-[ffmpeg_param2:string] [value2:string] {...}}}");
1277 sink.para()->text(L"For streaming the contents of a channel using FFMpeg");
1279 ->item(L"url", L"The stream URL to create/stream to.")
1280 ->item(L"ffmpeg_paramX", L"A parameter supported by FFMpeg. For example vcodec or acodec etc.");
1281 sink.para()->text(L"Examples:");
1282 sink.example(L">> ADD 1 STREAM udp://<client_ip_address>:9250 -format mpegts -vcodec libx264 -crf 25 -tune zerolatency -preset ultrafast");
1285 spl::shared_ptr<core::frame_consumer> create_streaming_consumer(
1286 const std::vector<std::wstring>& params, core::interaction_sink*)
1288 if (params.size() < 1 || (!boost::iequals(params.at(0), L"STREAM") && !boost::iequals(params.at(0), L"FILE")))
1289 return core::frame_consumer::empty();
1291 auto compatibility_mode = boost::iequals(params.at(0), L"FILE");
1292 auto path = u8(params.size() > 1 ? params.at(1) : L"");
1293 auto args = u8(boost::join(params, L" "));
1295 return spl::make_shared<streaming_consumer>(path, args, compatibility_mode);
1298 spl::shared_ptr<core::frame_consumer> create_preconfigured_streaming_consumer(
1299 const boost::property_tree::wptree& ptree, core::interaction_sink*)
1301 return spl::make_shared<streaming_consumer>(
1302 u8(ptree.get<std::wstring>(L"path")),
1303 u8(ptree.get<std::wstring>(L"args", L"")),