2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
4 * This file is part of CasparCG (www.casparcg.com).
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
19 * Author: Robert Nagy, ronag89@gmail.com
22 #include "../StdAfx.h"
24 #include "../ffmpeg_error.h"
26 #include "ffmpeg_consumer.h"
28 #include "../producer/tbb_avcodec.h"
30 #include <core/frame/frame.h>
31 #include <core/mixer/audio/audio_util.h>
32 #include <core/consumer/frame_consumer.h>
33 #include <core/video_format.h>
34 #include <core/help/help_repository.h>
35 #include <core/help/help_sink.h>
37 #include <common/array.h>
38 #include <common/env.h>
39 #include <common/except.h>
40 #include <common/executor.h>
41 #include <common/future.h>
42 #include <common/diagnostics/graph.h>
43 #include <common/lock.h>
44 #include <common/memory.h>
45 #include <common/param.h>
46 #include <common/utf.h>
47 #include <common/assert.h>
48 #include <common/memshfl.h>
49 #include <common/timer.h>
51 #include <boost/algorithm/string.hpp>
52 #include <boost/property_tree/ptree.hpp>
53 #include <boost/filesystem.hpp>
54 #include <boost/range/algorithm.hpp>
55 #include <boost/range/algorithm_ext.hpp>
56 #include <boost/lexical_cast.hpp>
58 #include <tbb/spin_mutex.h>
64 #pragma warning (push)
65 #pragma warning (disable : 4244)
69 #define __STDC_CONSTANT_MACROS
70 #define __STDC_LIMIT_MACROS
71 #include <libavformat/avformat.h>
72 #include <libswscale/swscale.h>
73 #include <libavutil/opt.h>
74 #include <libavutil/pixdesc.h>
75 #include <libavutil/parseutils.h>
76 #include <libavutil/samplefmt.h>
77 #include <libswresample/swresample.h>
83 namespace caspar { namespace ffmpeg {
85 int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
87 AVClass* av_class = *(AVClass**)obj;
89 if((strcmp(name, "pix_fmt") == 0 || strcmp(name, "pixel_format") == 0) && strcmp(av_class->class_name, "AVCodecContext") == 0)
91 AVCodecContext* c = (AVCodecContext*)obj;
92 auto pix_fmt = av_get_pix_fmt(val);
93 if(pix_fmt == PIX_FMT_NONE)
98 //if((strcmp(name, "r") == 0 || strcmp(name, "frame_rate") == 0) && strcmp(av_class->class_name, "AVCodecContext") == 0)
100 // AVCodecContext* c = (AVCodecContext*)obj;
102 // if(c->codec_type != AVMEDIA_TYPE_VIDEO)
106 // int ret = av_parse_video_rate(&rate, val);
110 // c->time_base.num = rate.den;
111 // c->time_base.den = rate.num;
115 return ::av_opt_set(obj, name, val, search_flags);
123 option(std::string name, std::string value)
124 : name(std::move(name))
125 , value(std::move(value))
132 AVOutputFormat* format;
140 output_format(const core::video_format_desc& format_desc, const std::string& filename, std::vector<option>& options)
141 : format(av_guess_format(nullptr, filename.c_str(), nullptr))
142 , width(format_desc.width)
143 , height(format_desc.height)
144 , vcodec(CODEC_ID_NONE)
145 , acodec(CODEC_ID_NONE)
149 if(boost::iequals(boost::filesystem::path(filename).extension().string(), ".dv"))
152 boost::range::remove_erase_if(options, [&](const option& o)
154 return set_opt(o.name, o.value);
157 if(vcodec == CODEC_ID_NONE && format)
158 vcodec = format->video_codec;
160 if(acodec == CODEC_ID_NONE && format)
161 acodec = format->audio_codec;
163 if(vcodec == CODEC_ID_NONE)
164 vcodec = CODEC_ID_H264;
166 if(acodec == CODEC_ID_NONE)
167 acodec = CODEC_ID_PCM_S16LE;
170 bool set_opt(const std::string& name, const std::string& value)
172 //if(name == "target")
174 // enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
176 // if(name.find("pal-") != std::string::npos)
178 // else if(name.find("ntsc-") != std::string::npos)
181 // if(norm == UNKNOWN)
182 // CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("target"));
184 // if (name.find("-dv") != std::string::npos)
186 // set_opt("f", "dv");
189 // set_opt("s", "720x576");
193 // set_opt("s", "720x480");
196 // set_opt("croptop", "2");
197 // set_opt("cropbot", "4");
200 // set_opt("s", norm == PAL ? "720x576" : "720x480");
208 format = av_guess_format(value.c_str(), nullptr, nullptr);
210 if(format == nullptr)
211 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("f"));
215 else if(name == "vcodec" || name == "v:codec")
217 auto c = avcodec_find_encoder_by_name(value.c_str());
219 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("vcodec"));
221 vcodec = avcodec_find_encoder_by_name(value.c_str())->id;
225 else if(name == "acodec" || name == "a:codec")
227 auto c = avcodec_find_encoder_by_name(value.c_str());
229 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("acodec"));
231 acodec = avcodec_find_encoder_by_name(value.c_str())->id;
237 if(av_parse_video_size(&width, &height, value.c_str()) < 0)
238 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("s"));
242 else if(name == "croptop")
244 croptop = boost::lexical_cast<int>(value);
248 else if(name == "cropbot")
250 cropbot = boost::lexical_cast<int>(value);
259 typedef cache_aligned_vector<uint8_t> byte_vector;
261 struct ffmpeg_consumer : boost::noncopyable
263 const spl::shared_ptr<diagnostics::graph> graph_;
264 const std::string filename_;
265 const std::shared_ptr<AVFormatContext> oc_ { avformat_alloc_context(), av_free };
266 const core::video_format_desc format_desc_;
268 core::monitor::subject monitor_subject_;
270 tbb::spin_mutex exception_mutex_;
271 std::exception_ptr exception_;
273 std::shared_ptr<AVStream> audio_st_;
274 std::shared_ptr<AVStream> video_st_;
276 byte_vector picture_buffer_;
277 byte_vector key_picture_buf_;
278 byte_vector audio_buffer_;
279 std::shared_ptr<SwrContext> swr_;
280 std::shared_ptr<SwsContext> sws_;
282 int64_t frame_number_ = 0;
284 output_format output_format_;
286 tbb::atomic<int64_t> current_encoding_delay_;
290 ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, std::vector<option> options, bool key_only)
291 : filename_(filename)
292 , format_desc_(format_desc)
293 , output_format_(format_desc, filename, options)
294 , key_only_(key_only)
297 current_encoding_delay_ = 0;
300 // TODO: Ask stakeholders about case where file already exists.
301 boost::filesystem::remove(boost::filesystem::path(env::media_folder() + u16(filename))); // Delete the file if it exists
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 executor_.set_capacity(8);
310 oc_->oformat = output_format_.format;
312 std::strcpy(oc_->filename, filename_.c_str());
314 // Add the audio and video streams using the default format codecs and initialize the codecs.
315 video_st_ = add_video_stream(options);
318 audio_st_ = add_audio_stream(options);
320 av_dump_format(oc_.get(), 0, filename_.c_str(), 1);
322 // Open the output ffmpeg, if needed.
323 if (!(oc_->oformat->flags & AVFMT_NOFILE))
324 THROW_ON_ERROR2(avio_open(&oc_->pb, filename.c_str(), AVIO_FLAG_WRITE), "[ffmpeg_consumer]");
326 THROW_ON_ERROR2(avformat_write_header(oc_.get(), nullptr), "[ffmpeg_consumer]");
328 if(options.size() > 0)
330 for (auto& option : options)
331 CASPAR_LOG(warning) << L"Invalid option: -" << u16(option.name) << L" " << u16(option.value);
334 CASPAR_LOG(info) << print() << L" Successfully Initialized.";
345 CASPAR_LOG_CURRENT_EXCEPTION();
348 LOG_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");
355 if (!(oc_->oformat->flags & AVFMT_NOFILE))
356 LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]");
358 CASPAR_LOG(info) << print() << L" Successfully Uninitialized.";
363 void send(core::const_frame& frame)
365 auto exception = lock(exception_mutex_, [&]
370 if(exception != nullptr)
371 std::rethrow_exception(exception);
373 executor_.begin_invoke([=]
376 current_encoding_delay_ = frame.get_age_millis();
380 bool ready_for_frame() const
382 return !executor_.is_full();
387 graph_->set_tag("dropped-frame");
390 std::wstring print() const
392 return L"ffmpeg[" + u16(filename_) + L"]";
395 core::monitor::subject& monitor_output()
397 return monitor_subject_;
401 std::shared_ptr<AVStream> add_video_stream(std::vector<option>& options)
403 if(output_format_.vcodec == CODEC_ID_NONE)
406 auto st = av_new_stream(oc_.get(), 0);
408 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("av_new_stream"));
410 auto encoder = avcodec_find_encoder(output_format_.vcodec);
412 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Codec not found."));
416 avcodec_get_context_defaults3(c, encoder);
418 c->codec_id = output_format_.vcodec;
419 c->codec_type = AVMEDIA_TYPE_VIDEO;
420 c->width = output_format_.width;
421 c->height = output_format_.height - output_format_.croptop - output_format_.cropbot;
422 c->time_base.den = format_desc_.time_scale;
423 c->time_base.num = format_desc_.duration;
425 c->flags |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);
426 c->pix_fmt = c->pix_fmt != PIX_FMT_NONE ? c->pix_fmt : PIX_FMT_YUV420P;
428 if(c->codec_id == CODEC_ID_PRORES)
430 c->bit_rate = output_format_.width < 1280 ? 63*1000000 : 220*1000000;
431 c->pix_fmt = PIX_FMT_YUV422P10;
433 else if(c->codec_id == CODEC_ID_DNXHD)
435 if(c->width < 1280 || c->height < 720)
436 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Unsupported video dimensions."));
438 c->bit_rate = 220*1000000;
439 c->pix_fmt = PIX_FMT_YUV422P;
441 else if(c->codec_id == CODEC_ID_DVVIDEO)
443 c->width = c->height == 1280 ? 960 : c->width;
445 if(format_desc_.format == core::video_format::ntsc)
447 c->pix_fmt = PIX_FMT_YUV411P;
448 output_format_.croptop = 2;
449 output_format_.cropbot = 4;
450 c->height = output_format_.height - output_format_.croptop - output_format_.cropbot;
452 else if(format_desc_.format == core::video_format::pal)
453 c->pix_fmt = PIX_FMT_YUV420P;
455 c->pix_fmt = PIX_FMT_YUV422P;
457 if(format_desc_.duration == 1001)
458 c->width = c->height == 1080 ? 1280 : c->width;
460 c->width = c->height == 1080 ? 1440 : c->width;
462 else if(c->codec_id == CODEC_ID_H264)
464 c->pix_fmt = PIX_FMT_YUV420P;
465 av_opt_set(c->priv_data, "preset", "ultrafast", 0);
466 av_opt_set(c->priv_data, "tune", "fastdecode", 0);
467 av_opt_set(c->priv_data, "crf", "5", 0);
469 else if(c->codec_id == CODEC_ID_QTRLE)
471 c->pix_fmt = PIX_FMT_ARGB;
474 boost::range::remove_erase_if(options, [&](const option& o)
476 return o.name.at(0) != 'a' && ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;
479 if(output_format_.format->flags & AVFMT_GLOBALHEADER)
480 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
482 THROW_ON_ERROR2(tbb_avcodec_open(c, encoder), "[ffmpeg_consumer]");
484 return std::shared_ptr<AVStream>(st, [](AVStream* st)
486 LOG_ON_ERROR2(tbb_avcodec_close(st->codec), "[ffmpeg_consumer]");
487 av_freep(&st->codec);
492 std::shared_ptr<AVStream> add_audio_stream(std::vector<option>& options)
494 if(output_format_.acodec == CODEC_ID_NONE)
497 auto st = av_new_stream(oc_.get(), 1);
499 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate audio-stream") << boost::errinfo_api_function("av_new_stream"));
501 auto encoder = avcodec_find_encoder(output_format_.acodec);
503 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
507 avcodec_get_context_defaults3(c, encoder);
509 c->codec_id = output_format_.acodec;
510 c->codec_type = AVMEDIA_TYPE_AUDIO;
511 c->sample_rate = 48000;
513 c->sample_fmt = AV_SAMPLE_FMT_S16;
514 c->time_base.num = 1;
515 c->time_base.den = c->sample_rate;
517 if(output_format_.vcodec == CODEC_ID_FLV1)
518 c->sample_rate = 44100;
520 if(output_format_.format->flags & AVFMT_GLOBALHEADER)
521 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
523 boost::range::remove_erase_if(options, [&](const option& o)
525 return ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;
528 THROW_ON_ERROR2(avcodec_open2(c, encoder, nullptr), "[ffmpeg_consumer]");
530 return std::shared_ptr<AVStream>(st, [](AVStream* st)
532 LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");;
533 av_freep(&st->codec);
538 void encode_video_frame(core::const_frame frame)
543 auto enc = video_st_->codec;
545 auto av_frame = convert_video(frame, enc);
546 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
547 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper;
548 av_frame->pts = frame_number_++;
550 monitor_subject_ << core::monitor::message("/frame")
551 % static_cast<int64_t>(frame_number_)
552 % static_cast<int64_t>(std::numeric_limits<int64_t>::max());
555 av_init_packet(&pkt);
560 THROW_ON_ERROR2(avcodec_encode_video2(enc, &pkt, av_frame.get(), &got_packet), "[ffmpeg_consumer]");
561 std::shared_ptr<AVPacket> guard(&pkt, av_free_packet);
566 if (pkt.pts != AV_NOPTS_VALUE)
567 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, video_st_->time_base);
568 if (pkt.dts != AV_NOPTS_VALUE)
569 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, video_st_->time_base);
571 pkt.stream_index = video_st_->index;
573 THROW_ON_ERROR2(av_interleaved_write_frame(oc_.get(), &pkt), "[ffmpeg_consumer]");
576 uint64_t get_channel_layout(AVCodecContext* dec)
578 auto layout = (dec->channel_layout && dec->channels == av_get_channel_layout_nb_channels(dec->channel_layout)) ? dec->channel_layout : av_get_default_channel_layout(dec->channels);
582 void encode_audio_frame(core::const_frame frame)
587 auto enc = audio_st_->codec;
589 boost::push_back(audio_buffer_, convert_audio(frame, enc));
591 auto frame_size = enc->frame_size != 0 ? enc->frame_size * enc->channels * av_get_bytes_per_sample(enc->sample_fmt) : static_cast<int>(audio_buffer_.size());
593 while(audio_buffer_.size() >= frame_size)
595 std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
596 avcodec_get_frame_defaults(av_frame.get());
597 av_frame->nb_samples = frame_size / (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));
600 av_init_packet(&pkt);
604 THROW_ON_ERROR2(avcodec_fill_audio_frame(av_frame.get(), enc->channels, enc->sample_fmt, audio_buffer_.data(), frame_size, 1), "[ffmpeg_consumer]");
607 THROW_ON_ERROR2(avcodec_encode_audio2(enc, &pkt, av_frame.get(), &got_packet), "[ffmpeg_consumer]");
608 std::shared_ptr<AVPacket> guard(&pkt, av_free_packet);
610 audio_buffer_.erase(audio_buffer_.begin(), audio_buffer_.begin() + frame_size);
615 if (pkt.pts != AV_NOPTS_VALUE)
616 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, audio_st_->time_base);
617 if (pkt.dts != AV_NOPTS_VALUE)
618 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, audio_st_->time_base);
619 if (pkt.duration > 0)
620 pkt.duration = static_cast<int>(av_rescale_q(pkt.duration, enc->time_base, audio_st_->time_base));
622 pkt.stream_index = audio_st_->index;
624 THROW_ON_ERROR2(av_interleaved_write_frame(oc_.get(), &pkt), "[ffmpeg_consumer]");
628 std::shared_ptr<AVFrame> convert_video(core::const_frame frame, AVCodecContext* c)
632 sws_.reset(sws_getContext(format_desc_.width,
633 format_desc_.height - output_format_.croptop - output_format_.cropbot,
638 SWS_BICUBIC, nullptr, nullptr, nullptr),
641 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));
646 std::shared_ptr<AVFrame> in_frame(avcodec_alloc_frame(), av_free);
648 auto in_picture = reinterpret_cast<AVPicture*>(in_frame.get());
652 key_picture_buf_.resize(frame.image_data().size());
653 in_picture->linesize[0] = format_desc_.width * 4;
654 in_picture->data[0] = key_picture_buf_.data();
656 aligned_memshfl(in_picture->data[0], frame.image_data().begin(), frame.image_data().size(), 0x0F0F0F0F, 0x0B0B0B0B, 0x07070707, 0x03030303);
662 const_cast<uint8_t*>(frame.image_data().begin()),
665 format_desc_.height - output_format_.croptop - output_format_.cropbot);
670 for(int n = 0; n < 4; ++n)
671 in_frame->data[n] += in_frame->linesize[n] * output_format_.croptop;
675 std::shared_ptr<AVFrame> out_frame(avcodec_alloc_frame(), av_free);
677 av_image_fill_linesizes(out_frame->linesize, c->pix_fmt, c->width);
678 for(int n = 0; n < 4; ++n)
679 out_frame->linesize[n] += 32 - (out_frame->linesize[n] % 32); // align
681 picture_buffer_.resize(av_image_fill_pointers(out_frame->data, c->pix_fmt, c->height, nullptr, out_frame->linesize));
682 av_image_fill_pointers(out_frame->data, c->pix_fmt, c->height, picture_buffer_.data(), out_frame->linesize);
686 sws_scale(sws_.get(),
690 format_desc_.height - output_format_.cropbot - output_format_.croptop,
692 out_frame->linesize);
697 byte_vector convert_audio(core::const_frame& frame, AVCodecContext* c)
701 swr_ = std::shared_ptr<SwrContext>(swr_alloc_set_opts(nullptr,
702 get_channel_layout(c), c->sample_fmt, c->sample_rate,
703 av_get_default_channel_layout(format_desc_.audio_channels), AV_SAMPLE_FMT_S32, format_desc_.audio_sample_rate,
704 0, nullptr), [](SwrContext* p){swr_free(&p);});
707 CASPAR_THROW_EXCEPTION(bad_alloc());
709 THROW_ON_ERROR2(swr_init(swr_.get()), "[audio_decoder]");
712 byte_vector buffer(48000);
714 const uint8_t* in[] = {reinterpret_cast<const uint8_t*>(frame.audio_data().data())};
715 uint8_t* out[] = {buffer.data()};
717 auto channel_samples = swr_convert(swr_.get(),
718 out, static_cast<int>(buffer.size()) / c->channels / av_get_bytes_per_sample(c->sample_fmt),
719 in, static_cast<int>(frame.audio_data().size()/format_desc_.audio_channels));
721 buffer.resize(channel_samples * c->channels * av_get_bytes_per_sample(c->sample_fmt));
728 auto space = boost::filesystem::space(boost::filesystem::path(filename_).parent_path());
729 if(space.available < 512*1000000)
730 BOOST_THROW_EXCEPTION(file_write_error() << msg_info("out of space"));
733 void encode(const core::const_frame& frame)
737 if(frame_number_ % 25 == 0)
740 caspar::timer frame_timer;
742 encode_video_frame(frame);
743 encode_audio_frame(frame);
745 graph_->set_value("frame-time", frame_timer.elapsed()*format_desc_.fps*0.5);
749 lock(exception_mutex_, [&]
751 exception_ = std::current_exception();
757 struct ffmpeg_consumer_proxy : public core::frame_consumer
759 const std::wstring filename_;
760 const std::vector<option> options_;
761 const bool separate_key_;
763 std::unique_ptr<ffmpeg_consumer> consumer_;
764 std::unique_ptr<ffmpeg_consumer> key_only_consumer_;
768 ffmpeg_consumer_proxy(const std::wstring& filename, const std::vector<option>& options, bool separate_key)
769 : filename_(filename)
771 , separate_key_(separate_key_)
775 void initialize(const core::video_format_desc& format_desc, int) override
778 BOOST_THROW_EXCEPTION(invalid_operation() << msg_info("Cannot reinitialize ffmpeg-consumer."));
780 consumer_.reset(new ffmpeg_consumer(u8(filename_), format_desc, options_, false));
784 boost::filesystem::path fill_file(filename_);
785 auto without_extension = u16(fill_file.stem().string());
786 auto key_file = env::media_folder() + without_extension + L"_A" + u16(fill_file.extension().string());
788 key_only_consumer_.reset(new ffmpeg_consumer(u8(key_file), format_desc, options_, true));
792 int64_t presentation_frame_age_millis() const override
794 return consumer_ ? static_cast<int64_t>(consumer_->current_encoding_delay_) : 0;
797 std::future<bool> send(core::const_frame frame) override
799 bool ready_for_frame = consumer_->ready_for_frame();
801 if (ready_for_frame && separate_key_)
802 ready_for_frame = ready_for_frame && key_only_consumer_->ready_for_frame();
806 consumer_->send(frame);
809 key_only_consumer_->send(frame);
813 consumer_->mark_dropped();
816 key_only_consumer_->mark_dropped();
819 return make_ready_future(true);
822 std::wstring print() const override
824 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";
827 std::wstring name() const override
832 boost::property_tree::wptree info() const override
834 boost::property_tree::wptree info;
835 info.add(L"type", L"file");
836 info.add(L"filename", filename_);
837 info.add(L"separate_key", separate_key_);
841 bool has_synchronization_clock() const override
846 int buffer_depth() const override
851 int index() const override
856 core::monitor::subject& monitor_output()
858 return consumer_->monitor_output();
862 void describe_consumer(core::help_sink& sink, const core::help_repository& repo)
864 sink.short_description(L"Can record a channel to a file supported by FFMpeg.");
865 sink.syntax(L"FILE [filename:string] {-[ffmpeg_param1:string] [value1:string] {-[ffmpeg_param2:string] [value2:string] {...}}} {[separate_key:SEPARATE_KEY]}");
866 sink.para()->text(L"Can record a channel to a file supported by FFMpeg.");
868 ->item(L"filename", L"The filename under the media folder including the extension (decides which kind of container format that will be used).")
869 ->item(L"ffmpeg_paramX", L"A parameter supported by FFMpeg. For example vcodec or acodec etc.")
870 ->item(L"separate_key", L"If defined will create two files simultaneously -- One for fill and one for key (_A will be appended).")
872 sink.para()->text(L"Examples:");
873 sink.example(L">> ADD 1 FILE output.mov -vcodec dnxhd");
874 sink.example(L">> ADD 1 FILE output.mov -vcodec prores");
875 sink.example(L">> ADD 1 FILE output.mov -vcodec dvvideo");
876 sink.example(L">> ADD 1 FILE output.mov - vcodec libx264 -preset ultrafast -tune fastdecode -crf 25");
877 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");
880 spl::shared_ptr<core::frame_consumer> create_consumer(
881 const std::vector<std::wstring>& params, core::interaction_sink*)
883 auto params2 = params;
884 auto separate_key_it = std::find_if(params2.begin(), params2.end(), param_comparer(L"SEPARATE_KEY"));
885 bool separate_key = false;
887 if (separate_key_it != params2.end())
890 params2.erase(separate_key_it);
893 auto str = std::accumulate(params2.begin(), params2.end(), std::wstring(), [](const std::wstring& lhs, const std::wstring& rhs) {return lhs + L" " + rhs;});
895 boost::wregex path_exp(LR"(\s*FILE(\s(?<PATH>.+\.[^\s]+))?.*)", boost::regex::icase);
898 if(!boost::regex_match(str, path, path_exp))
899 return core::frame_consumer::empty();
901 boost::wregex opt_exp(LR"(-((?<NAME>[^\s]+)\s+(?<VALUE>[^\s]+)))");
903 std::vector<option> options;
904 for(boost::wsregex_iterator it(str.begin(), str.end(), opt_exp); it != boost::wsregex_iterator(); ++it)
906 auto name = u8(boost::trim_copy(boost::to_lower_copy((*it)["NAME"].str())));
907 auto value = u8(boost::trim_copy(boost::to_lower_copy((*it)["VALUE"].str())));
911 else if(value == "dvcpro")
914 options.push_back(option(name, value));
917 return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + path["PATH"].str(), options, separate_key);
920 spl::shared_ptr<core::frame_consumer> create_preconfigured_consumer(
921 const boost::property_tree::wptree& ptree, core::interaction_sink*)
923 auto filename = ptree.get<std::wstring>(L"path");
924 auto codec = ptree.get(L"vcodec", L"libx264");
925 auto separate_key = ptree.get(L"separate-key", false);
927 std::vector<option> options;
928 options.push_back(option("vcodec", u8(codec)));
930 return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options, separate_key);