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/data_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/concurrency/executor.h>
\r
35 #include <common/diagnostics/graph.h>
\r
36 #include <common/spl/memory.h>
\r
37 #include <common/utf.h>
\r
38 #include <common/param.h>
\r
40 #include <boost/algorithm/string.hpp>
\r
41 #include <boost/timer.hpp>
\r
42 #include <boost/property_tree/ptree.hpp>
\r
43 #include <boost/filesystem.hpp>
\r
45 #if defined(_MSC_VER)
\r
46 #pragma warning (push)
\r
47 #pragma warning (disable : 4244)
\r
51 #define __STDC_CONSTANT_MACROS
\r
52 #define __STDC_LIMIT_MACROS
\r
53 #include <libavformat/avformat.h>
\r
54 #include <libswscale/swscale.h>
\r
55 #include <libavutil/opt.h>
\r
57 #if defined(_MSC_VER)
\r
58 #pragma warning (pop)
\r
61 namespace caspar { namespace ffmpeg {
\r
63 struct ffmpeg_consumer : boost::noncopyable
\r
65 const std::wstring filename_;
\r
67 const std::shared_ptr<AVFormatContext> oc_;
\r
68 const core::video_format_desc format_desc_;
\r
70 const spl::shared_ptr<diagnostics::graph> graph_;
\r
71 boost::timer frame_timer_;
\r
72 boost::timer write_timer_;
\r
75 executor file_write_executor_;
\r
78 std::shared_ptr<AVStream> audio_st_;
\r
81 std::shared_ptr<AVStream> video_st_;
\r
83 std::vector<uint8_t> video_outbuf_;
\r
84 std::vector<uint8_t> picture_buf_;
\r
85 std::shared_ptr<SwsContext> sws_;
\r
87 int64_t frame_number_;
\r
90 ffmpeg_consumer(const std::wstring& filename, const core::video_format_desc& format_desc, const std::wstring& codec, const std::vector<std::wstring>& options)
\r
91 : filename_(filename)
\r
92 , video_outbuf_(1920*1080*8)
\r
93 , oc_(avformat_alloc_context(), av_free)
\r
94 , format_desc_(format_desc)
\r
95 , executor_(print())
\r
96 , file_write_executor_(print() + L"/output")
\r
99 // TODO: Ask stakeholders about case where file already exists.
\r
100 boost::filesystem::remove(boost::filesystem::path(env::media_folder() + filename)); // Delete the file if it exists
\r
102 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
\r
103 graph_->set_color("write-time", diagnostics::color(0.5f, 0.5f, 0.1f));
\r
104 graph_->set_text(print());
\r
105 diagnostics::register_graph(graph_);
\r
107 executor_.set_capacity(8);
\r
108 file_write_executor_.set_capacity(8);
\r
110 oc_->oformat = av_guess_format(nullptr, u8(filename_).c_str(), nullptr);
\r
112 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format."));
\r
114 THROW_ON_ERROR2(av_set_parameters(oc_.get(), nullptr), "[ffmpeg_consumer]");
\r
116 strcpy_s(oc_->filename, u8(filename_).c_str());
\r
118 auto video_codec = avcodec_find_encoder_by_name(u8(codec).c_str());
\r
119 if(video_codec == nullptr)
\r
120 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info(codec));
\r
122 // Add the audio and video streams using the default format codecs and initialize the codecs .
\r
123 video_st_ = add_video_stream(video_codec->id, options);
\r
124 audio_st_ = add_audio_stream();
\r
126 dump_format(oc_.get(), 0, u8(filename_).c_str(), 1);
\r
128 // Open the output ffmpeg, if needed.
\r
129 if (!(oc_->oformat->flags & AVFMT_NOFILE))
\r
130 THROW_ON_ERROR2(avio_open(&oc_->pb, u8(filename_).c_str(), URL_WRONLY), "[ffmpeg_consumer]");
\r
132 THROW_ON_ERROR2(av_write_header(oc_.get()), "[ffmpeg_consumer]");
\r
141 file_write_executor_.wait();
\r
142 file_write_executor_.stop();
\r
143 file_write_executor_.join();
\r
145 LOG_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");
\r
150 if (!(oc_->oformat->flags & AVFMT_NOFILE))
\r
151 LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]"); // Close the output ffmpeg.
\r
154 std::wstring print() const
\r
156 return L"ffmpeg[" + filename_ + L"]";
\r
159 std::shared_ptr<AVStream> add_video_stream(enum CodecID codec_id, const std::vector<std::wstring>& options)
\r
161 auto st = av_new_stream(oc_.get(), 0);
\r
163 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream") << boost::errinfo_api_function("av_new_stream"));
\r
165 auto encoder = avcodec_find_encoder(codec_id);
\r
167 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
169 auto c = st->codec;
\r
171 avcodec_get_context_defaults3(c, encoder);
\r
173 c->codec_id = codec_id;
\r
174 c->codec_type = AVMEDIA_TYPE_VIDEO;
\r
175 c->width = format_desc_.width;
\r
176 c->height = format_desc_.height;
\r
177 c->time_base.den = format_desc_.time_scale;
\r
178 c->time_base.num = format_desc_.duration;
\r
180 c->flags |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);
\r
182 if(c->codec_id == CODEC_ID_PRORES)
\r
184 c->bit_rate = format_desc_.width < 1280 ? 63*1000000 : 220*1000000;
\r
185 c->pix_fmt = PIX_FMT_YUV422P10;
\r
187 else if(c->codec_id == CODEC_ID_DNXHD)
\r
189 if(format_desc_.width < 1280 || format_desc_.height < 720)
\r
190 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("unsupported dimension"));
\r
192 c->bit_rate = 220*1000000;
\r
193 c->pix_fmt = PIX_FMT_YUV422P;
\r
195 else if(c->codec_id == CODEC_ID_DVVIDEO)
\r
197 c->bit_rate = format_desc_.width < 1280 ? 50*1000000 : 100*1000000;
\r
198 c->pix_fmt = PIX_FMT_YUV422P;
\r
200 c->width = format_desc_.height == 1280 ? 960 : c->width;
\r
202 if(format_desc_.duration == 1001)
\r
203 c->width = format_desc_.height == 1080 ? 1280 : c->width;
\r
205 c->width = format_desc_.height == 1080 ? 1440 : c->width;
\r
207 else if(c->codec_id == CODEC_ID_H264)
\r
209 c->pix_fmt = PIX_FMT_YUV420P;
\r
210 if(options.empty())
\r
212 av_opt_set(c->priv_data, "preset", "ultrafast", 0);
\r
213 av_opt_set(c->priv_data, "tune", "fastdecode", 0);
\r
214 av_opt_set(c->priv_data, "crf", "5", 0);
\r
217 else if(c->codec_id == CODEC_ID_QTRLE)
\r
219 c->pix_fmt = PIX_FMT_ARGB;
\r
223 BOOST_THROW_EXCEPTION(invalid_argument() << msg_info("Unsupported output parameters."));
\r
226 c->max_b_frames = 0; // b-frames not supported.
\r
228 for(size_t n = 0; n < options.size()/2; ++n)
\r
229 THROW_ON_ERROR2(av_opt_set(c, u8(options[n*2+0]).c_str(), u8(options[n*2+1]).c_str(), AV_OPT_SEARCH_CHILDREN), "[ffmpeg_consumer]");
\r
231 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
\r
232 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
\r
234 c->thread_count = boost::thread::hardware_concurrency();
\r
235 THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");
\r
237 return std::shared_ptr<AVStream>(st, [](AVStream* st)
\r
239 LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");
\r
240 av_freep(&st->codec);
\r
245 std::shared_ptr<AVStream> add_audio_stream()
\r
247 auto st = av_new_stream(oc_.get(), 1);
\r
249 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate audio-stream") << boost::errinfo_api_function("av_new_stream"));
\r
251 st->codec->codec_id = CODEC_ID_PCM_S16LE;
\r
252 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
\r
253 st->codec->sample_rate = 48000;
\r
254 st->codec->channels = 2;
\r
255 st->codec->sample_fmt = SAMPLE_FMT_S16;
\r
257 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
\r
258 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
\r
260 auto codec = avcodec_find_encoder(st->codec->codec_id);
\r
262 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
264 THROW_ON_ERROR2(avcodec_open(st->codec, codec), "[ffmpeg_consumer]");
\r
266 return std::shared_ptr<AVStream>(st, [](AVStream* st)
\r
268 LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");;
\r
269 av_freep(&st->codec);
\r
274 std::shared_ptr<AVFrame> convert_video_frame(const spl::shared_ptr<const core::data_frame>& frame, AVCodecContext* c)
\r
278 sws_.reset(sws_getContext(format_desc_.width, format_desc_.height, PIX_FMT_BGRA, c->width, c->height, c->pix_fmt, SWS_BICUBIC, nullptr, nullptr, nullptr), sws_freeContext);
\r
279 if (sws_ == nullptr)
\r
280 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));
\r
283 std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
\r
284 avpicture_fill(reinterpret_cast<AVPicture*>(av_frame.get()), const_cast<uint8_t*>(frame->image_data().begin()), PIX_FMT_BGRA, format_desc_.width, format_desc_.height);
\r
286 std::shared_ptr<AVFrame> local_av_frame(avcodec_alloc_frame(), av_free);
\r
287 picture_buf_.resize(avpicture_get_size(c->pix_fmt, format_desc_.width, format_desc_.height));
\r
288 avpicture_fill(reinterpret_cast<AVPicture*>(local_av_frame.get()), picture_buf_.data(), c->pix_fmt, format_desc_.width, format_desc_.height);
\r
290 sws_scale(sws_.get(), av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);
\r
292 return local_av_frame;
\r
295 std::shared_ptr<AVPacket> encode_video_frame(const spl::shared_ptr<const core::data_frame>& frame)
\r
297 auto c = video_st_->codec;
\r
299 auto av_frame = convert_video_frame(frame, c);
\r
300 av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;
\r
301 av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper;
\r
302 av_frame->pts = frame_number_++;
\r
304 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
307 spl::shared_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)
\r
312 av_init_packet(pkt.get());
\r
314 if (c->coded_frame->pts != AV_NOPTS_VALUE)
\r
315 pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);
\r
317 if(c->coded_frame->key_frame)
\r
318 pkt->flags |= AV_PKT_FLAG_KEY;
\r
320 pkt->stream_index = video_st_->index;
\r
321 pkt->data = video_outbuf_.data();
\r
322 pkt->size = out_size;
\r
324 av_dup_packet(pkt.get());
\r
330 std::shared_ptr<AVPacket> encode_audio_frame(const spl::shared_ptr<const core::data_frame>& frame)
\r
332 auto c = audio_st_->codec;
\r
334 auto audio_data = core::audio_32_to_16(frame->audio_data());
\r
336 spl::shared_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)
\r
341 av_init_packet(pkt.get());
\r
343 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
\r
344 pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);
\r
346 pkt->flags |= AV_PKT_FLAG_KEY;
\r
347 pkt->stream_index = audio_st_->index;
\r
348 pkt->size = static_cast<int>(audio_data.size()*2);
\r
349 pkt->data = reinterpret_cast<uint8_t*>(audio_data.data());
\r
351 av_dup_packet(pkt.get());
\r
355 void send(const spl::shared_ptr<const core::data_frame>& frame)
\r
357 executor_.begin_invoke([=]
\r
359 frame_timer_.restart();
\r
361 auto video = encode_video_frame(frame);
\r
362 auto audio = encode_audio_frame(frame);
\r
364 graph_->set_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);
\r
366 file_write_executor_.begin_invoke([=]
\r
368 write_timer_.restart();
\r
371 av_write_frame(oc_.get(), video.get());
\r
373 av_write_frame(oc_.get(), audio.get());
\r
375 graph_->set_value("write-time", write_timer_.elapsed()*format_desc_.fps*0.5);
\r
381 struct ffmpeg_consumer_proxy : public core::frame_consumer
\r
383 const std::wstring filename_;
\r
384 const bool key_only_;
\r
385 const std::wstring codec_;
\r
386 const std::vector<std::wstring> options_;
\r
388 std::unique_ptr<ffmpeg_consumer> consumer_;
\r
392 ffmpeg_consumer_proxy(const std::wstring& filename, bool key_only, const std::wstring& codec, const std::vector<std::wstring>& options)
\r
393 : filename_(filename)
\r
394 , key_only_(key_only)
\r
395 , codec_(std::move(codec))
\r
396 , options_(options)
\r
400 virtual void initialize(const core::video_format_desc& format_desc, int)
\r
403 consumer_.reset(new ffmpeg_consumer(filename_, format_desc, codec_, options_));
\r
406 virtual bool send(const spl::shared_ptr<const core::data_frame>& frame) override
\r
408 consumer_->send(frame);
\r
412 virtual std::wstring print() const override
\r
414 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";
\r
417 virtual boost::property_tree::wptree info() const override
\r
419 boost::property_tree::wptree info;
\r
420 info.add(L"type", L"ffmpeg-consumer");
\r
421 info.add(L"key-only", key_only_);
\r
422 info.add(L"filename", filename_);
\r
423 info.add(L"vcodec", codec_);
\r
427 virtual bool has_synchronization_clock() const override
\r
432 virtual int buffer_depth() const override
\r
437 virtual int index() const override
\r
443 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)
\r
445 if(params.size() < 1 || params[0] != L"FILE")
\r
446 return core::frame_consumer::empty();
\r
448 auto filename = (params.size() > 1 ? params[1] : L"");
\r
449 bool key_only = get_param(L"KEY_ONLY", params, false);
\r
450 auto codec = get_param(L"-VCODEC", params, get_param(L"CODEC", params, L"libx264"));
\r
452 std::vector<std::wstring> options;
\r
453 auto opt_it = std::find(params.begin(), params.end(), L"-VCODEC");
\r
455 if(std::distance(opt_it, params.end()) > 2)
\r
457 std::advance(opt_it, 2);
\r
458 while(opt_it != params.end())
\r
460 auto str = *opt_it++;
\r
461 if(str.size() > 0 && str.at(0) == L'-')
\r
462 str = str.substr(1);
\r
463 options.push_back(boost::to_lower_copy(str));
\r
467 if(codec == L"H264")
\r
468 codec = L"libx264";
\r
470 if(codec == L"DVCPRO")
\r
471 codec = L"dvvideo";
\r
473 codec = boost::to_lower_copy(codec);
\r
475 return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, key_only, codec, options);
\r
478 spl::shared_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree)
\r
480 auto filename = ptree.get<std::wstring>(L"path");
\r
481 auto key_only = ptree.get(L"key-only", false);
\r
482 auto codec = ptree.get(L"vcodec", L"libx264");
\r
484 return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, key_only, codec, std::vector<std::wstring>());
\r