2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
\r
4 * This file is part of CasparCG (www.casparcg.com).
\r
6 * CasparCG is free software: you can redistribute it and/or modify
\r
7 * it under the terms of the GNU General Public License as published by
\r
8 * the Free Software Foundation, either version 3 of the License, or
\r
9 * (at your option) any later version.
\r
11 * CasparCG is distributed in the hope that it will be useful,
\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
14 * GNU General Public License for more details.
\r
16 * You should have received a copy of the GNU General Public License
\r
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
\r
19 * Author: Robert Nagy, ronag89@gmail.com
\r
22 #include "../StdAfx.h"
\r
24 #include "../ffmpeg_error.h"
\r
26 #include "ffmpeg_consumer.h"
\r
28 #include <core/frame/frame.h>
\r
29 #include <core/mixer/audio/audio_util.h>
\r
30 #include <core/consumer/frame_consumer.h>
\r
31 #include <core/video_format.h>
\r
33 #include <common/env.h>
\r
34 #include <common/utf.h>
\r
35 #include <common/param.h>
\r
36 #include <common/concurrency/executor.h>
\r
37 #include <common/diagnostics/graph.h>
\r
38 #include <common/memory/array.h>
\r
39 #include <common/spl/memory.h>
\r
41 #include <boost/algorithm/string.hpp>
\r
42 #include <boost/timer.hpp>
\r
43 #include <boost/property_tree/ptree.hpp>
\r
44 #include <boost/filesystem.hpp>
\r
46 #if defined(_MSC_VER)
\r
47 #pragma warning (push)
\r
48 #pragma warning (disable : 4244)
\r
52 #define __STDC_CONSTANT_MACROS
\r
53 #define __STDC_LIMIT_MACROS
\r
54 #include <libavformat/avformat.h>
\r
55 #include <libswscale/swscale.h>
\r
56 #include <libavutil/opt.h>
\r
58 #if defined(_MSC_VER)
\r
59 #pragma warning (pop)
\r
62 namespace caspar { namespace ffmpeg {
\r
69 option(std::string name, std::string value)
\r
70 : name(std::move(name))
\r
71 , value(std::move(value))
\r
76 void set_format(AVOutputFormat*& format, const std::string& value)
\r
78 format = av_guess_format(value.c_str(), nullptr, nullptr);
\r
80 if(format == nullptr)
\r
81 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("f"));
\r
84 bool parse_format(AVOutputFormat*& format, std::vector<option>& options)
\r
86 auto format_it = std::find_if(options.begin(), options.end(), [](const option& o)
\r
88 return o.name == "f" || o.name == "format";
\r
91 if(format_it == options.end())
\r
94 set_format(format, format_it->value);
\r
96 options.erase(format_it);
\r
101 void set_vcodec(CodecID& vcodec, const std::string& value)
\r
103 vcodec = avcodec_find_encoder_by_name(value.c_str())->id;
\r
104 if(vcodec == CODEC_ID_NONE)
\r
105 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("vcodec"));
\r
108 bool parse_vcodec(CodecID& vcodec, std::vector<option>& options)
\r
110 auto vcodec_it = std::find_if(options.begin(), options.end(), [](const option& o)
\r
112 return o.name == "vcodec";
\r
115 if(vcodec_it == options.end())
\r
118 set_vcodec(vcodec, vcodec_it->value);
\r
120 options.erase(vcodec_it);
\r
125 void set_pix_fmt(AVCodecContext* vcodec, const std::string& value)
\r
127 auto pix_fmt = av_get_pix_fmt(value.c_str());
\r
128 if(pix_fmt == PIX_FMT_NONE)
\r
129 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("pix_fmt"));
\r
131 vcodec->pix_fmt = pix_fmt;
\r
134 bool parse_pix_fmt(AVCodecContext* vcodec, std::vector<option>& options)
\r
136 auto pix_fmt_it = std::find_if(options.begin(), options.end(), [](const option& o)
\r
138 return o.name == "pix_fmt" || o.name == "pixel_format";
\r
141 if(pix_fmt_it == options.end())
\r
144 set_pix_fmt(vcodec, pix_fmt_it->value);
\r
146 options.erase(pix_fmt_it);
\r
151 struct ffmpeg_consumer : boost::noncopyable
\r
153 const std::string filename_;
\r
155 const std::shared_ptr<AVFormatContext> oc_;
\r
156 const core::video_format_desc format_desc_;
\r
158 const spl::shared_ptr<diagnostics::graph> graph_;
\r
159 boost::timer frame_timer_;
\r
160 boost::timer write_timer_;
\r
162 executor executor_;
\r
163 executor file_write_executor_;
\r
166 std::shared_ptr<AVStream> audio_st_;
\r
169 std::shared_ptr<AVStream> video_st_;
\r
171 std::vector<uint8_t> video_outbuf_;
\r
172 std::vector<uint8_t> picture_buf_;
\r
173 std::shared_ptr<SwsContext> sws_;
\r
175 int64_t frame_number_;
\r
178 ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, std::vector<option> options)
\r
179 : filename_(filename)
\r
180 , video_outbuf_(1920*1080*8)
\r
181 , oc_(avformat_alloc_context(), av_free)
\r
182 , format_desc_(format_desc)
\r
183 , executor_(print())
\r
184 , file_write_executor_(print() + L"/output")
\r
187 // TODO: Ask stakeholders about case where file already exists.
\r
188 boost::filesystem::remove(boost::filesystem::path(env::media_folder() + u16(filename))); // Delete the file if it exists
\r
190 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
\r
191 graph_->set_color("write-time", diagnostics::color(0.5f, 0.5f, 0.1f));
\r
192 graph_->set_text(print());
\r
193 diagnostics::register_graph(graph_);
\r
195 executor_.set_capacity(8);
\r
196 file_write_executor_.set_capacity(8);
\r
198 oc_->oformat = av_guess_format(nullptr, filename_.c_str(), nullptr);
\r
200 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format."));
\r
202 parse_format(oc_->oformat, options);
\r
204 auto vcodec = oc_->oformat->video_codec;
\r
205 parse_vcodec(vcodec, options);
\r
207 THROW_ON_ERROR2(av_set_parameters(oc_.get(), nullptr), "[ffmpeg_consumer]");
\r
209 strcpy_s(oc_->filename, filename_.c_str());
\r
211 // Add the audio and video streams using the default format codecs and initialize the codecs .
\r
212 video_st_ = add_video_stream(vcodec, options);
\r
213 audio_st_ = add_audio_stream();
\r
215 dump_format(oc_.get(), 0, filename_.c_str(), 1);
\r
217 // Open the output ffmpeg, if needed.
\r
218 if (!(oc_->oformat->flags & AVFMT_NOFILE))
\r
219 THROW_ON_ERROR2(avio_open(&oc_->pb, filename_.c_str(), URL_WRONLY), "[ffmpeg_consumer]");
\r
221 THROW_ON_ERROR2(av_write_header(oc_.get()), "[ffmpeg_consumer]");
\r
223 CASPAR_LOG(info) << print() << L" Successfully Initialized.";
\r
229 file_write_executor_.wait();
\r
231 LOG_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");
\r
236 if (!(oc_->oformat->flags & AVFMT_NOFILE))
\r
237 LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]"); // Close the output ffmpeg.
\r
239 CASPAR_LOG(info) << print() << L" Successfully Uninitialized.";
\r
242 std::wstring print() const
\r
244 return L"ffmpeg[" + u16(filename_) + L"]";
\r
247 std::shared_ptr<AVStream> add_video_stream(CodecID vcodec, std::vector<option>& options)
\r
249 auto st = av_new_stream(oc_.get(), 0);
\r
251 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream") << boost::errinfo_api_function("av_new_stream"));
\r
253 auto encoder = avcodec_find_encoder(vcodec);
\r
255 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
257 auto c = st->codec;
\r
259 avcodec_get_context_defaults3(c, encoder);
\r
261 c->codec_id = vcodec;
\r
262 c->codec_type = AVMEDIA_TYPE_VIDEO;
\r
263 c->width = format_desc_.width;
\r
264 c->height = format_desc_.height;
\r
265 c->time_base.den = format_desc_.time_scale;
\r
266 c->time_base.num = format_desc_.duration;
\r
268 c->flags |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);
\r
270 if(c->codec_id == CODEC_ID_PRORES)
\r
272 c->bit_rate = format_desc_.width < 1280 ? 63*1000000 : 220*1000000;
\r
273 c->pix_fmt = PIX_FMT_YUV422P10;
\r
275 else if(c->codec_id == CODEC_ID_DNXHD)
\r
277 if(format_desc_.width < 1280 || format_desc_.height < 720)
\r
278 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("unsupported dimension"));
\r
280 c->bit_rate = 220*1000000;
\r
281 c->pix_fmt = PIX_FMT_YUV422P;
\r
283 else if(c->codec_id == CODEC_ID_DVVIDEO)
\r
285 c->bit_rate = format_desc_.width < 1280 ? 50*1000000 : 100*1000000;
\r
286 c->width = format_desc_.height == 1280 ? 960 : c->width;
\r
288 if(format_desc_.format == core::video_format::ntsc)
\r
289 c->pix_fmt = PIX_FMT_YUV411P;
\r
290 else if(format_desc_.format == core::video_format::pal)
\r
291 c->pix_fmt = PIX_FMT_YUV420P;
\r
293 if(c->bit_rate >= 50*1000000) // dv50
\r
294 c->pix_fmt = PIX_FMT_YUV422P;
\r
296 if(format_desc_.duration == 1001)
\r
297 c->width = format_desc_.height == 1080 ? 1280 : c->width;
\r
299 c->width = format_desc_.height == 1080 ? 1440 : c->width;
\r
301 else if(c->codec_id == CODEC_ID_H264)
\r
303 c->pix_fmt = PIX_FMT_YUV420P;
\r
304 if(options.empty())
\r
306 av_opt_set(c->priv_data, "preset", "ultrafast", 0);
\r
307 av_opt_set(c->priv_data, "tune", "fastdecode", 0);
\r
308 av_opt_set(c->priv_data, "crf", "5", 0);
\r
311 else if(c->codec_id == CODEC_ID_QTRLE)
\r
313 c->pix_fmt = PIX_FMT_ARGB;
\r
317 BOOST_THROW_EXCEPTION(invalid_argument() << msg_info("Unsupported output parameters."));
\r
320 parse_pix_fmt(c, options);
\r
322 c->max_b_frames = 0; // b-frames not supported.
\r
324 BOOST_FOREACH(auto& option, options)
\r
325 THROW_ON_ERROR2(av_opt_set(c, option.name.c_str(), option.value.c_str(), AV_OPT_SEARCH_CHILDREN), "[ffmpeg_consumer]");
\r
327 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
\r
328 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
\r
330 c->thread_count = boost::thread::hardware_concurrency();
\r
331 THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");
\r
333 return std::shared_ptr<AVStream>(st, [](AVStream* st)
\r
335 LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");
\r
336 av_freep(&st->codec);
\r
341 std::shared_ptr<AVStream> add_audio_stream()
\r
343 auto st = av_new_stream(oc_.get(), 1);
\r
345 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate audio-stream") << boost::errinfo_api_function("av_new_stream"));
\r
347 st->codec->codec_id = CODEC_ID_PCM_S16LE;
\r
348 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
\r
349 st->codec->sample_rate = 48000;
\r
350 st->codec->channels = 2;
\r
351 st->codec->sample_fmt = SAMPLE_FMT_S16;
\r
353 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
\r
354 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
\r
356 auto codec = avcodec_find_encoder(st->codec->codec_id);
\r
358 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
360 THROW_ON_ERROR2(avcodec_open(st->codec, codec), "[ffmpeg_consumer]");
\r
362 return std::shared_ptr<AVStream>(st, [](AVStream* st)
\r
364 LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");;
\r
365 av_freep(&st->codec);
\r
370 std::shared_ptr<AVFrame> convert_video_frame(core::const_frame frame, AVCodecContext* c)
\r
374 sws_.reset(sws_getContext(static_cast<int>(format_desc_.width), static_cast<int>(format_desc_.height), PIX_FMT_BGRA, c->width, c->height, c->pix_fmt, SWS_BICUBIC, nullptr, nullptr, nullptr), sws_freeContext);
\r
375 if (sws_ == nullptr)
\r
376 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));
\r
379 std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
\r
380 avpicture_fill(reinterpret_cast<AVPicture*>(av_frame.get()), const_cast<uint8_t*>(frame.image_data().begin()), PIX_FMT_BGRA, static_cast<int>(format_desc_.width), static_cast<int>(format_desc_.height));
\r
382 std::shared_ptr<AVFrame> local_av_frame(avcodec_alloc_frame(), av_free);
\r
383 picture_buf_.resize(avpicture_get_size(c->pix_fmt, static_cast<int>(format_desc_.width), static_cast<int>(format_desc_.height)));
\r
384 avpicture_fill(reinterpret_cast<AVPicture*>(local_av_frame.get()), picture_buf_.data(), c->pix_fmt, static_cast<int>(format_desc_.width), static_cast<int>(format_desc_.height));
\r
386 sws_scale(sws_.get(), av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);
\r
388 return local_av_frame;
\r
391 std::shared_ptr<AVPacket> encode_video_frame(core::const_frame frame)
\r
393 auto c = video_st_->codec;
\r
395 auto av_frame = convert_video_frame(frame, c);
\r
396 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
\r
397 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper;
\r
398 av_frame->pts = frame_number_++;
\r
400 int out_size = THROW_ON_ERROR2(avcodec_encode_video(c, video_outbuf_.data(), static_cast<int>(video_outbuf_.size()), av_frame.get()), "[ffmpeg_consumer]");
\r
403 spl::shared_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)
\r
408 av_init_packet(pkt.get());
\r
410 if (c->coded_frame->pts != AV_NOPTS_VALUE)
\r
411 pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);
\r
413 if(c->coded_frame->key_frame)
\r
414 pkt->flags |= AV_PKT_FLAG_KEY;
\r
416 pkt->stream_index = video_st_->index;
\r
417 pkt->data = video_outbuf_.data();
\r
418 pkt->size = out_size;
\r
420 av_dup_packet(pkt.get());
\r
426 std::shared_ptr<AVPacket> encode_audio_frame(core::const_frame frame)
\r
428 auto c = audio_st_->codec;
\r
430 auto audio_data = core::audio_32_to_16(frame.audio_data());
\r
432 spl::shared_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)
\r
437 av_init_packet(pkt.get());
\r
439 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
\r
440 pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);
\r
442 pkt->flags |= AV_PKT_FLAG_KEY;
\r
443 pkt->stream_index = audio_st_->index;
\r
444 pkt->size = static_cast<int>(audio_data.size()*2);
\r
445 pkt->data = reinterpret_cast<uint8_t*>(audio_data.data());
\r
447 av_dup_packet(pkt.get());
\r
451 void send(core::const_frame& frame)
\r
453 executor_.begin_invoke([=]
\r
455 frame_timer_.restart();
\r
457 auto video = encode_video_frame(frame);
\r
458 auto audio = encode_audio_frame(frame);
\r
460 graph_->set_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);
\r
462 file_write_executor_.begin_invoke([=]
\r
464 write_timer_.restart();
\r
467 av_write_frame(oc_.get(), video.get());
\r
469 av_write_frame(oc_.get(), audio.get());
\r
471 graph_->set_value("write-time", write_timer_.elapsed()*format_desc_.fps*0.5);
\r
477 struct ffmpeg_consumer_proxy : public core::frame_consumer
\r
479 const std::wstring filename_;
\r
480 const std::vector<option> options_;
\r
482 std::unique_ptr<ffmpeg_consumer> consumer_;
\r
486 ffmpeg_consumer_proxy(const std::wstring& filename, const std::vector<option>& options)
\r
487 : filename_(filename)
\r
488 , options_(options)
\r
492 virtual void initialize(const core::video_format_desc& format_desc, int)
\r
495 consumer_.reset(new ffmpeg_consumer(u8(filename_), format_desc, options_));
\r
498 virtual bool send(core::const_frame frame) override
\r
500 consumer_->send(frame);
\r
504 virtual std::wstring print() const override
\r
506 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";
\r
509 virtual std::wstring name() const override
\r
514 virtual boost::property_tree::wptree info() const override
\r
516 boost::property_tree::wptree info;
\r
517 info.add(L"type", L"file");
\r
518 info.add(L"filename", filename_);
\r
522 virtual bool has_synchronization_clock() const override
\r
527 virtual int buffer_depth() const override
\r
532 virtual int index() const override
\r
538 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)
\r
540 if(params.size() < 1 || params[0] != L"FILE")
\r
541 return core::frame_consumer::empty();
\r
543 auto filename = (params.size() > 1 ? params[1] : L"");
\r
545 std::vector<option> options;
\r
547 if(params.size() >= 3)
\r
549 for(auto opt_it = params.begin()+2; opt_it != params.end();)
\r
551 auto name = u8(boost::trim_copy(boost::to_lower_copy(*opt_it++))).substr(1);
\r
552 auto value = u8(boost::trim_copy(boost::to_lower_copy(*opt_it++)));
\r
554 if(value == "h264")
\r
556 else if(value == "dvcpro")
\r
559 options.push_back(option(name, value));
\r
563 return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);
\r
566 spl::shared_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree)
\r
568 auto filename = ptree.get<std::wstring>(L"path");
\r
569 auto codec = ptree.get(L"vcodec", L"libx264");
\r
571 std::vector<option> options;
\r
572 options.push_back(option("vcodec", u8(codec)));
\r
574 return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);
\r