3 #include "ffmpeg_consumer.h"
5 #include "../ffmpeg_error.h"
6 #include "../producer/util/util.h"
8 #include <common/except.h>
9 #include <common/executor.h>
10 #include <common/assert.h>
11 #include <common/utf.h>
12 #include <common/future.h>
13 #include <common/env.h>
14 #include <common/scope_exit.h>
15 #include <common/ptree.h>
17 #include <core/consumer/frame_consumer.h>
18 #include <core/frame/frame.h>
19 #include <core/frame/audio_channel_layout.h>
20 #include <core/video_format.h>
21 #include <core/monitor/monitor.h>
22 #include <core/help/help_repository.h>
23 #include <core/help/help_sink.h>
25 #include <boost/noncopyable.hpp>
26 #include <boost/rational.hpp>
27 #include <boost/format.hpp>
28 #include <boost/algorithm/string/predicate.hpp>
29 #include <boost/property_tree/ptree.hpp>
32 #pragma warning(disable: 4244)
33 #pragma warning(disable: 4245)
34 #include <boost/crc.hpp>
37 #include <tbb/atomic.h>
38 #include <tbb/concurrent_queue.h>
39 #include <tbb/parallel_invoke.h>
40 #include <tbb/parallel_for.h>
45 #pragma warning(disable: 4244)
49 #define __STDC_CONSTANT_MACROS
50 #define __STDC_LIMIT_MACROS
51 #include <libavformat/avformat.h>
52 #include <libavcodec/avcodec.h>
53 #include <libavutil/avutil.h>
54 #include <libavutil/frame.h>
55 #include <libavutil/opt.h>
56 #include <libavutil/imgutils.h>
57 #include <libavutil/parseutils.h>
58 #include <libavfilter/avfilter.h>
59 #include <libavfilter/buffersink.h>
60 #include <libavfilter/buffersrc.h>
65 namespace caspar { namespace ffmpeg {
67 int crc16(const std::string& str)
69 boost::crc_16_type result;
71 result.process_bytes(str.data(), str.length());
73 return result.checksum();
76 class streaming_consumer final : public core::frame_consumer
82 core::monitor::subject subject_;
83 boost::filesystem::path path_;
84 int consumer_index_offset_;
86 std::map<std::string, std::string> options_;
87 bool compatibility_mode_;
89 core::video_format_desc in_video_format_;
90 core::audio_channel_layout in_channel_layout_ = core::audio_channel_layout::invalid();
92 std::shared_ptr<AVFormatContext> oc_;
93 tbb::atomic<bool> abort_request_;
95 std::shared_ptr<AVStream> video_st_;
96 std::shared_ptr<AVStream> audio_st_;
98 std::int64_t video_pts_;
99 std::int64_t audio_pts_;
101 AVFilterContext* audio_graph_in_;
102 AVFilterContext* audio_graph_out_;
103 std::shared_ptr<AVFilterGraph> audio_graph_;
104 std::shared_ptr<AVBitStreamFilterContext> audio_bitstream_filter_;
106 AVFilterContext* video_graph_in_;
107 AVFilterContext* video_graph_out_;
108 std::shared_ptr<AVFilterGraph> video_graph_;
109 std::shared_ptr<AVBitStreamFilterContext> video_bitstream_filter_;
113 executor video_encoder_executor_;
114 executor audio_encoder_executor_;
116 tbb::atomic<int> tokens_;
117 boost::mutex tokens_mutex_;
118 boost::condition_variable tokens_cond_;
119 tbb::atomic<int64_t> current_encoding_delay_;
121 executor write_executor_;
128 bool compatibility_mode)
130 , consumer_index_offset_(crc16(path))
131 , compatibility_mode_(compatibility_mode)
135 , audio_encoder_executor_(print() + L" audio_encoder")
136 , video_encoder_executor_(print() + L" video_encoder")
137 , write_executor_(print() + L" io")
139 abort_request_ = false;
140 current_encoding_delay_ = 0;
143 boost::sregex_iterator(
146 boost::regex("-(?<NAME>[^-\\s]+)(\\s+(?<VALUE>[^\\s]+))?"));
147 it != boost::sregex_iterator();
150 options_[(*it)["NAME"].str()] = (*it)["VALUE"].matched ? (*it)["VALUE"].str() : "";
153 if (options_.find("threads") == options_.end())
154 options_["threads"] = "auto";
161 boost::regex("tokens")).get_value_or(2));
164 ~streaming_consumer()
168 video_encoder_executor_.begin_invoke([&] { encode_video(core::const_frame::empty(), nullptr); });
169 audio_encoder_executor_.begin_invoke([&] { encode_audio(core::const_frame::empty(), nullptr); });
171 video_encoder_executor_.stop();
172 audio_encoder_executor_.stop();
173 video_encoder_executor_.join();
174 audio_encoder_executor_.join();
176 video_graph_.reset();
177 audio_graph_.reset();
181 write_packet(nullptr, nullptr);
183 write_executor_.stop();
184 write_executor_.join();
186 FF(av_write_trailer(oc_.get()));
188 if (!(oc_->oformat->flags & AVFMT_NOFILE) && oc_->pb)
196 const core::video_format_desc& format_desc,
197 const core::audio_channel_layout& channel_layout,
198 int channel_index) override
202 static boost::regex prot_exp("^.+:.*" );
204 const auto overwrite =
205 try_remove_arg<std::string>(
207 boost::regex("y")) != boost::none;
209 if(!boost::regex_match(
213 if(!path_.is_complete())
217 env::media_folder()) +
221 if(boost::filesystem::exists(path_))
223 if(!overwrite && !compatibility_mode_)
224 BOOST_THROW_EXCEPTION(invalid_argument() << msg_info("File exists"));
226 boost::filesystem::remove(path_);
230 const auto oformat_name =
231 try_remove_arg<std::string>(
233 boost::regex("^f|format$"));
237 FF(avformat_alloc_output_context2(
240 oformat_name && !oformat_name->empty() ? oformat_name->c_str() : nullptr,
241 path_.string().c_str()));
245 avformat_free_context);
247 CASPAR_VERIFY(oc_->oformat);
249 oc_->interrupt_callback.callback = streaming_consumer::interrupt_cb;
250 oc_->interrupt_callback.opaque = this;
252 CASPAR_VERIFY(format_desc.format != core::video_format::invalid);
254 in_video_format_ = format_desc;
255 in_channel_layout_ = channel_layout;
257 CASPAR_VERIFY(oc_->oformat);
259 const auto video_codec_name =
260 try_remove_arg<std::string>(
262 boost::regex("^c:v|codec:v|vcodec$"));
264 const auto video_codec =
266 ? avcodec_find_encoder_by_name(video_codec_name->c_str())
267 : avcodec_find_encoder(oc_->oformat->video_codec);
269 const auto audio_codec_name =
270 try_remove_arg<std::string>(
272 boost::regex("^c:a|codec:a|acodec$"));
274 const auto audio_codec =
276 ? avcodec_find_encoder_by_name(audio_codec_name->c_str())
277 : avcodec_find_encoder(oc_->oformat->audio_codec);
280 CASPAR_THROW_EXCEPTION(user_error() << msg_info(
281 "Failed to find video codec " + (video_codec_name
283 : "with id " + boost::lexical_cast<std::string>(
284 oc_->oformat->video_codec))));
286 CASPAR_THROW_EXCEPTION(user_error() << msg_info(
287 "Failed to find audio codec " + (audio_codec_name
289 : "with id " + boost::lexical_cast<std::string>(
290 oc_->oformat->audio_codec))));
295 configure_video_filters(
297 try_remove_arg<std::string>(options_,
298 boost::regex("vf|f:v|filter:v")).get_value_or(""));
300 configure_audio_filters(
302 try_remove_arg<std::string>(options_,
303 boost::regex("af|f:a|filter:a")).get_value_or(""));
308 configue_audio_bistream_filters(options_);
309 configue_video_bistream_filters(options_);
315 auto video_options = options_;
316 auto audio_options = options_;
318 video_st_ = open_encoder(
322 audio_st_ = open_encoder(
326 auto it = options_.begin();
327 while(it != options_.end())
329 if(video_options.find(it->first) == video_options.end() || audio_options.find(it->first) == audio_options.end())
330 it = options_.erase(it);
338 AVDictionary* av_opts = nullptr;
342 std::move(options_));
346 av_dict_free(&av_opts);
349 if (!(oc_->oformat->flags & AVFMT_NOFILE))
353 path_.string().c_str(),
355 &oc_->interrupt_callback,
359 FF(avformat_write_header(
363 options_ = to_map(av_opts);
374 for (const auto& option : options_)
377 << L"Invalid option: -"
380 << u16(option.second);
392 core::monitor::subject& monitor_output() override
397 std::wstring name() const override
402 std::future<bool> send(core::const_frame frame) override
404 CASPAR_VERIFY(in_video_format_.format != core::video_format::invalid);
407 std::shared_ptr<void> token(
412 tokens_cond_.notify_one();
413 current_encoding_delay_ = frame.get_age_millis();
416 return executor_.begin_invoke([=]() -> bool
418 boost::unique_lock<boost::mutex> tokens_lock(tokens_mutex_);
421 tokens_cond_.wait(tokens_lock);
423 video_encoder_executor_.begin_invoke([=]() mutable
430 audio_encoder_executor_.begin_invoke([=]() mutable
441 std::wstring print() const override
443 return L"streaming_consumer[" + u16(path_.string()) + L"]";
446 virtual boost::property_tree::wptree info() const override
448 boost::property_tree::wptree info;
449 info.add(L"type", L"stream");
450 info.add(L"path", path_.wstring());
454 bool has_synchronization_clock() const override
459 int buffer_depth() const override
464 int index() const override
466 return compatibility_mode_ ? 200 : 100000 + consumer_index_offset_;
469 int64_t presentation_frame_age_millis() const override
471 return current_encoding_delay_;
476 static int interrupt_cb(void* ctx)
479 return reinterpret_cast<streaming_consumer*>(ctx)->abort_request_;
482 std::shared_ptr<AVStream> open_encoder(
483 const AVCodec& codec,
484 std::map<std::string,
485 std::string>& options)
493 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("av_new_stream"));
495 auto enc = st->codec;
499 switch(enc->codec_type)
501 case AVMEDIA_TYPE_VIDEO:
503 enc->time_base = video_graph_out_->inputs[0]->time_base;
504 enc->pix_fmt = static_cast<AVPixelFormat>(video_graph_out_->inputs[0]->format);
505 enc->sample_aspect_ratio = st->sample_aspect_ratio = video_graph_out_->inputs[0]->sample_aspect_ratio;
506 enc->width = video_graph_out_->inputs[0]->w;
507 enc->height = video_graph_out_->inputs[0]->h;
508 enc->bit_rate_tolerance = 400 * 1000000;
512 case AVMEDIA_TYPE_AUDIO:
514 enc->time_base = audio_graph_out_->inputs[0]->time_base;
515 enc->sample_fmt = static_cast<AVSampleFormat>(audio_graph_out_->inputs[0]->format);
516 enc->sample_rate = audio_graph_out_->inputs[0]->sample_rate;
517 enc->channel_layout = audio_graph_out_->inputs[0]->channel_layout;
518 enc->channels = audio_graph_out_->inputs[0]->channels;
524 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
525 enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
527 static const std::array<std::string, 4> char_id_map = {{"v", "a", "d", "s"}};
529 const auto char_id = char_id_map.at(enc->codec_type);
531 const auto codec_opts =
534 boost::regex("^(" + char_id + "?[^:]+):" + char_id + "$"));
536 AVDictionary* av_codec_opts = nullptr;
551 av_codec_opts ? &av_codec_opts : nullptr));
560 AV_DICT_IGNORE_SUFFIX);
564 options[t->key + (codec_opts.find(t->key) != codec_opts.end() ? ":" + char_id : "")] = t->value;
570 AV_DICT_IGNORE_SUFFIX);
573 av_dict_free(&av_codec_opts);
576 if(enc->codec_type == AVMEDIA_TYPE_AUDIO && !(codec.capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
578 CASPAR_ASSERT(enc->frame_size > 0);
579 av_buffersink_set_frame_size(audio_graph_out_,
583 return std::shared_ptr<AVStream>(st, [this](AVStream* st)
585 avcodec_close(st->codec);
589 void configue_audio_bistream_filters(
590 std::map<std::string, std::string>& options)
592 const auto audio_bitstream_filter_str =
593 try_remove_arg<std::string>(
595 boost::regex("^bsf:a|absf$"));
597 const auto audio_bitstream_filter =
598 audio_bitstream_filter_str
599 ? av_bitstream_filter_init(audio_bitstream_filter_str->c_str())
602 CASPAR_VERIFY(!audio_bitstream_filter_str || audio_bitstream_filter);
604 if(audio_bitstream_filter)
606 audio_bitstream_filter_.reset(
607 audio_bitstream_filter,
608 av_bitstream_filter_close);
611 if(audio_bitstream_filter_str && !audio_bitstream_filter_)
612 options["bsf:a"] = *audio_bitstream_filter_str;
615 void configue_video_bistream_filters(
616 std::map<std::string, std::string>& options)
618 const auto video_bitstream_filter_str =
619 try_remove_arg<std::string>(
621 boost::regex("^bsf:v|vbsf$"));
623 const auto video_bitstream_filter =
624 video_bitstream_filter_str
625 ? av_bitstream_filter_init(video_bitstream_filter_str->c_str())
628 CASPAR_VERIFY(!video_bitstream_filter_str || video_bitstream_filter);
630 if(video_bitstream_filter)
632 video_bitstream_filter_.reset(
633 video_bitstream_filter,
634 av_bitstream_filter_close);
637 if(video_bitstream_filter_str && !video_bitstream_filter_)
638 options["bsf:v"] = *video_bitstream_filter_str;
641 void configure_video_filters(
642 const AVCodec& codec,
643 const std::string& filtergraph)
646 avfilter_graph_alloc(),
649 avfilter_graph_free(&p);
652 video_graph_->nb_threads = boost::thread::hardware_concurrency()/2;
653 video_graph_->thread_type = AVFILTER_THREAD_SLICE;
655 const auto sample_aspect_ratio =
656 boost::rational<int>(
657 in_video_format_.square_width,
658 in_video_format_.square_height) /
659 boost::rational<int>(
660 in_video_format_.width,
661 in_video_format_.height);
663 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%")
664 % in_video_format_.width % in_video_format_.height
666 % in_video_format_.duration % in_video_format_.time_scale
667 % sample_aspect_ratio.numerator() % sample_aspect_ratio.denominator()
668 % in_video_format_.time_scale % in_video_format_.duration).str();
670 AVFilterContext* filt_vsrc = nullptr;
671 FF(avfilter_graph_create_filter(
673 avfilter_get_by_name("buffer"),
674 "ffmpeg_consumer_buffer",
675 vsrc_options.c_str(),
677 video_graph_.get()));
679 AVFilterContext* filt_vsink = nullptr;
680 FF(avfilter_graph_create_filter(
682 avfilter_get_by_name("buffersink"),
683 "ffmpeg_consumer_buffersink",
686 video_graph_.get()));
688 #pragma warning (push)
689 #pragma warning (disable : 4245)
691 FF(av_opt_set_int_list(
696 AV_OPT_SEARCH_CHILDREN));
698 #pragma warning (pop)
700 configure_filtergraph(
706 video_graph_in_ = filt_vsrc;
707 video_graph_out_ = filt_vsink;
710 << u16(std::string("\n")
711 + avfilter_graph_dump(
716 void configure_audio_filters(
717 const AVCodec& codec,
718 const std::string& filtergraph)
721 avfilter_graph_alloc(),
724 avfilter_graph_free(&p);
727 audio_graph_->nb_threads = boost::thread::hardware_concurrency()/2;
728 audio_graph_->thread_type = AVFILTER_THREAD_SLICE;
730 const auto asrc_options = (boost::format("sample_rate=%1%:sample_fmt=%2%:channels=%3%:time_base=%4%/%5%:channel_layout=%6%")
731 % in_video_format_.audio_sample_rate
732 % av_get_sample_fmt_name(AV_SAMPLE_FMT_S32)
733 % in_channel_layout_.num_channels
734 % 1 % in_video_format_.audio_sample_rate
738 av_get_default_channel_layout(in_channel_layout_.num_channels))).str();
740 AVFilterContext* filt_asrc = nullptr;
741 FF(avfilter_graph_create_filter(
743 avfilter_get_by_name("abuffer"),
744 "ffmpeg_consumer_abuffer",
745 asrc_options.c_str(),
747 audio_graph_.get()));
749 AVFilterContext* filt_asink = nullptr;
750 FF(avfilter_graph_create_filter(
752 avfilter_get_by_name("abuffersink"),
753 "ffmpeg_consumer_abuffersink",
756 audio_graph_.get()));
758 #pragma warning (push)
759 #pragma warning (disable : 4245)
763 "all_channel_counts",
765 AV_OPT_SEARCH_CHILDREN));
767 FF(av_opt_set_int_list(
772 AV_OPT_SEARCH_CHILDREN));
774 FF(av_opt_set_int_list(
777 codec.channel_layouts,
779 AV_OPT_SEARCH_CHILDREN));
781 FF(av_opt_set_int_list(
784 codec.supported_samplerates,
786 AV_OPT_SEARCH_CHILDREN));
788 #pragma warning (pop)
790 configure_filtergraph(
796 audio_graph_in_ = filt_asrc;
797 audio_graph_out_ = filt_asink;
800 << u16(std::string("\n")
801 + avfilter_graph_dump(
806 void configure_filtergraph(
807 AVFilterGraph& graph,
808 const std::string& filtergraph,
809 AVFilterContext& source_ctx,
810 AVFilterContext& sink_ctx)
812 AVFilterInOut* outputs = nullptr;
813 AVFilterInOut* inputs = nullptr;
817 if(!filtergraph.empty())
819 outputs = avfilter_inout_alloc();
820 inputs = avfilter_inout_alloc();
822 CASPAR_VERIFY(outputs && inputs);
824 outputs->name = av_strdup("in");
825 outputs->filter_ctx = &source_ctx;
826 outputs->pad_idx = 0;
827 outputs->next = nullptr;
829 inputs->name = av_strdup("out");
830 inputs->filter_ctx = &sink_ctx;
832 inputs->next = nullptr;
834 FF(avfilter_graph_parse(
850 FF(avfilter_graph_config(
856 avfilter_inout_free(&outputs);
857 avfilter_inout_free(&inputs);
862 void encode_video(core::const_frame frame_ptr, std::shared_ptr<void> token)
867 auto enc = video_st_->codec;
869 if(frame_ptr != core::const_frame::empty())
871 auto src_av_frame = create_frame();
873 const auto sample_aspect_ratio =
874 boost::rational<int>(
875 in_video_format_.square_width,
876 in_video_format_.square_height) /
877 boost::rational<int>(
878 in_video_format_.width,
879 in_video_format_.height);
881 src_av_frame->format = AV_PIX_FMT_BGRA;
882 src_av_frame->width = in_video_format_.width;
883 src_av_frame->height = in_video_format_.height;
884 src_av_frame->sample_aspect_ratio.num = sample_aspect_ratio.numerator();
885 src_av_frame->sample_aspect_ratio.den = sample_aspect_ratio.denominator();
886 src_av_frame->pts = video_pts_;
890 FF(av_image_fill_arrays(
892 src_av_frame->linesize,
893 frame_ptr.image_data().begin(),
894 static_cast<AVPixelFormat>(src_av_frame->format),
895 in_video_format_.width,
896 in_video_format_.height,
899 FF(av_buffersrc_add_frame(
901 src_av_frame.get()));
908 auto filt_frame = create_frame();
910 ret = av_buffersink_get_frame(
914 video_encoder_executor_.begin_invoke([=]
916 if(ret == AVERROR_EOF)
918 if(enc->codec->capabilities & CODEC_CAP_DELAY)
920 while(encode_av_frame(
922 video_bitstream_filter_.get(),
923 avcodec_encode_video2,
926 boost::this_thread::yield(); // TODO:
930 else if(ret != AVERROR(EAGAIN))
932 FF_RET(ret, "av_buffersink_get_frame");
934 if (filt_frame->interlaced_frame)
936 if (enc->codec->id == AV_CODEC_ID_MJPEG)
937 enc->field_order = filt_frame->top_field_first ? AV_FIELD_TT : AV_FIELD_BB;
939 enc->field_order = filt_frame->top_field_first ? AV_FIELD_TB : AV_FIELD_BT;
942 enc->field_order = AV_FIELD_PROGRESSIVE;
944 filt_frame->quality = enc->global_quality;
946 if (!enc->me_threshold)
947 filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
951 video_bitstream_filter_.get(),
952 avcodec_encode_video2,
956 boost::this_thread::yield(); // TODO:
962 void encode_audio(core::const_frame frame_ptr, std::shared_ptr<void> token)
967 auto enc = audio_st_->codec;
969 if(frame_ptr != core::const_frame::empty())
971 auto src_av_frame = create_frame();
973 src_av_frame->channels = in_channel_layout_.num_channels;
974 src_av_frame->channel_layout = av_get_default_channel_layout(in_channel_layout_.num_channels);
975 src_av_frame->sample_rate = in_video_format_.audio_sample_rate;
976 src_av_frame->nb_samples = static_cast<int>(frame_ptr.audio_data().size()) / src_av_frame->channels;
977 src_av_frame->format = AV_SAMPLE_FMT_S32;
978 src_av_frame->pts = audio_pts_;
980 audio_pts_ += src_av_frame->nb_samples;
982 FF(av_samples_fill_arrays(
983 src_av_frame->extended_data,
984 src_av_frame->linesize,
985 reinterpret_cast<const std::uint8_t*>(&*frame_ptr.audio_data().begin()),
986 src_av_frame->channels,
987 src_av_frame->nb_samples,
988 static_cast<AVSampleFormat>(src_av_frame->format),
991 FF(av_buffersrc_add_frame(
993 src_av_frame.get()));
1000 auto filt_frame = create_frame();
1002 ret = av_buffersink_get_frame(
1006 audio_encoder_executor_.begin_invoke([=]
1008 if(ret == AVERROR_EOF)
1010 if(enc->codec->capabilities & CODEC_CAP_DELAY)
1012 while(encode_av_frame(
1014 audio_bitstream_filter_.get(),
1015 avcodec_encode_audio2,
1019 boost::this_thread::yield(); // TODO:
1023 else if(ret != AVERROR(EAGAIN))
1027 "av_buffersink_get_frame");
1031 audio_bitstream_filter_.get(),
1032 avcodec_encode_audio2,
1036 boost::this_thread::yield(); // TODO:
1042 template<typename F>
1043 bool encode_av_frame(
1045 AVBitStreamFilterContext* bsfc,
1047 const std::shared_ptr<AVFrame>& src_av_frame,
1048 std::shared_ptr<void> token)
1051 av_init_packet(&pkt);
1061 if(!got_packet || pkt.size <= 0)
1064 pkt.stream_index = st.index;
1070 auto a = av_bitstream_filter_filter(
1078 pkt.flags & AV_PKT_FLAG_KEY);
1080 if(a == 0 && new_pkt.data != pkt.data && new_pkt.destruct)
1082 auto t = reinterpret_cast<std::uint8_t*>(av_malloc(new_pkt.size + FF_INPUT_BUFFER_PADDING_SIZE));
1094 FF_INPUT_BUFFER_PADDING_SIZE);
1097 new_pkt.buf = nullptr;
1100 a = AVERROR(ENOMEM);
1103 av_free_packet(&pkt);
1107 "av_bitstream_filter_filter");
1113 av_buffer_default_free,
1117 CASPAR_VERIFY(new_pkt.buf);
1122 if (pkt.pts != AV_NOPTS_VALUE)
1127 st.codec->time_base,
1131 if (pkt.dts != AV_NOPTS_VALUE)
1136 st.codec->time_base,
1144 st.codec->time_base, st.time_base));
1147 std::shared_ptr<AVPacket>(
1159 const std::shared_ptr<AVPacket>& pkt_ptr,
1160 std::shared_ptr<void> token)
1162 write_executor_.begin_invoke([this, pkt_ptr, token]() mutable
1164 FF(av_interleaved_write_frame(
1170 template<typename T>
1171 static boost::optional<T> try_remove_arg(
1172 std::map<std::string, std::string>& options,
1173 const boost::regex& expr)
1175 for(auto it = options.begin(); it != options.end(); ++it)
1177 if(boost::regex_search(it->first, expr))
1179 auto arg = it->second;
1181 return boost::lexical_cast<T>(arg);
1185 return boost::optional<T>();
1188 static std::map<std::string, std::string> remove_options(
1189 std::map<std::string, std::string>& options,
1190 const boost::regex& expr)
1192 std::map<std::string, std::string> result;
1194 auto it = options.begin();
1195 while(it != options.end())
1198 if(boost::regex_search(it->first, what, expr))
1201 what.size() > 0 && what[1].matched
1203 : it->first] = it->second;
1204 it = options.erase(it);
1213 static void to_dict(AVDictionary** dest, const std::map<std::string, std::string>& c)
1215 for (const auto& entry : c)
1219 entry.first.c_str(),
1220 entry.second.c_str(), 0);
1224 static std::map<std::string, std::string> to_map(AVDictionary* dict)
1226 std::map<std::string, std::string> result;
1233 AV_DICT_IGNORE_SUFFIX)
1240 AV_DICT_IGNORE_SUFFIX))
1242 result[t->key] = t->value;
1249 void describe_streaming_consumer(core::help_sink& sink, const core::help_repository& repo)
1251 sink.short_description(L"For streaming the contents of a channel using FFmpeg.");
1252 sink.syntax(L"STREAM [url:string] {-[ffmpeg_param1:string] [value1:string] {-[ffmpeg_param2:string] [value2:string] {...}}}");
1253 sink.para()->text(L"For streaming the contents of a channel using FFmpeg");
1255 ->item(L"url", L"The stream URL to create/stream to.")
1256 ->item(L"ffmpeg_paramX", L"A parameter supported by FFmpeg. For example vcodec or acodec etc.");
1257 sink.para()->text(L"Examples:");
1258 sink.example(L">> ADD 1 STREAM udp://<client_ip_address>:9250 -format mpegts -vcodec libx264 -crf 25 -tune zerolatency -preset ultrafast");
1261 spl::shared_ptr<core::frame_consumer> create_streaming_consumer(
1262 const std::vector<std::wstring>& params, core::interaction_sink*, std::vector<spl::shared_ptr<core::video_channel>> channels)
1264 if (params.size() < 1 || (!boost::iequals(params.at(0), L"STREAM") && !boost::iequals(params.at(0), L"FILE")))
1265 return core::frame_consumer::empty();
1267 auto compatibility_mode = boost::iequals(params.at(0), L"FILE");
1268 auto path = u8(params.size() > 1 ? params.at(1) : L"");
1269 auto args = u8(boost::join(params, L" "));
1271 return spl::make_shared<streaming_consumer>(path, args, compatibility_mode);
1274 spl::shared_ptr<core::frame_consumer> create_preconfigured_streaming_consumer(
1275 const boost::property_tree::wptree& ptree, core::interaction_sink*, std::vector<spl::shared_ptr<core::video_channel>> channels)
1277 return spl::make_shared<streaming_consumer>(
1278 u8(ptree_get<std::wstring>(ptree, L"path")),
1279 u8(ptree.get<std::wstring>(L"args", L"")),