2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>
\r
4 * This ffmpeg is part of CasparCG.
\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
21 #include "../StdAfx.h"
\r
23 #include "ffmpeg_consumer.h"
\r
25 #include <core/mixer/read_frame.h>
\r
26 #include <core/consumer/frame_consumer.h>
\r
27 #include <core/video_format.h>
\r
29 #include <common/concurrency/executor.h>
\r
30 #include <common/utility/string.h>
\r
31 #include <common/env.h>
\r
33 #include <boost/thread/once.hpp>
\r
35 #include <tbb/cache_aligned_allocator.h>
\r
36 #include <tbb/parallel_invoke.h>
\r
40 #if defined(_MSC_VER)
\r
41 #pragma warning (push)
\r
42 #pragma warning (disable : 4244)
\r
46 #define __STDC_CONSTANT_MACROS
\r
47 #define __STDC_LIMIT_MACROS
\r
48 #include <libavformat/avformat.h>
\r
49 #include <libswscale/swscale.h>
\r
51 #if defined(_MSC_VER)
\r
52 #pragma warning (pop)
\r
57 struct ffmpeg_consumer : boost::noncopyable
\r
59 const std::string filename_;
\r
60 const size_t bitrate_;
\r
62 const std::shared_ptr<AVFormatContext> oc_;
\r
63 const core::video_format_desc format_desc_;
\r
68 std::shared_ptr<AVStream> audio_st_;
\r
69 std::vector<uint8_t> audio_outbuf_;
\r
71 std::vector<int16_t> audio_input_buffer_;
\r
74 std::shared_ptr<AVStream> video_st_;
\r
75 std::vector<uint8_t> video_outbuf_;
\r
77 std::vector<uint8_t> picture_buf_;
\r
78 std::shared_ptr<SwsContext> img_convert_ctx_;
\r
81 ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, size_t bitrate)
\r
82 : filename_(filename)
\r
84 , video_outbuf_(1920*1080*4)
\r
85 , audio_outbuf_(48000)
\r
86 , oc_(avformat_alloc_context(), av_free)
\r
87 , format_desc_(format_desc)
\r
88 , executor_(print())
\r
92 BOOST_THROW_EXCEPTION(caspar_exception()
\r
93 << msg_info("Could not alloc format-context")
\r
94 << boost::errinfo_api_function("avformat_alloc_context"));
\r
97 executor_.set_capacity(core::consumer_buffer_depth());
\r
99 oc_->oformat = av_guess_format(nullptr, filename_.c_str(), nullptr);
\r
101 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format."));
\r
103 std::copy_n(filename_.c_str(), filename_.size(), oc_->filename);
\r
105 // Add the audio and video streams using the default format codecs and initialize the codecs .
\r
106 if (oc_->oformat->video_codec != CODEC_ID_NONE)
\r
107 video_st_ = add_video_stream(oc_->oformat->video_codec);
\r
109 //if (oc_->oformat->audio_codec != CODEC_ID_NONE)
\r
110 // audio_st_ = add_audio_stream(oc_->oformat->audio_codec);
\r
112 // Set the output parameters (must be done even if no parameters).
\r
113 int errn = av_set_parameters(oc_.get(), nullptr);
\r
116 BOOST_THROW_EXCEPTION(
\r
117 file_read_error() <<
\r
118 msg_info("Invalid output format parameters") <<
\r
119 boost::errinfo_api_function("avcodec_open") <<
\r
120 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
121 boost::errinfo_file_name(filename_));
\r
124 dump_format(oc_.get(), 0, filename_.c_str(), 1);
\r
126 // Now that all the parameters are set, we can open the audio and
\r
127 // video codecs and allocate the necessary encode buffers.
\r
129 open_video(video_st_);
\r
134 open_audio(audio_st_);
\r
138 CASPAR_LOG_CURRENT_EXCEPTION();
\r
139 audio_st_ = nullptr;
\r
142 // Open the output ffmpeg, if needed.
\r
143 if (!(oc_->oformat->flags & AVFMT_NOFILE))
\r
145 int errn = url_fopen(&oc_->pb, filename_.c_str(), URL_WRONLY);
\r
148 BOOST_THROW_EXCEPTION(
\r
149 file_not_found() <<
\r
150 msg_info("Could not open file") <<
\r
151 boost::errinfo_api_function("url_fopen") <<
\r
152 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
153 boost::errinfo_file_name(filename_));
\r
157 av_write_header(oc_.get()); // write the stream header, if any
\r
159 CASPAR_LOG(info) << print() << L" Successfully initialized.";
\r
170 av_write_trailer(oc_.get());
\r
172 if (!(oc_->oformat->flags & AVFMT_NOFILE))
\r
173 url_fclose(oc_->pb); // Close the output ffmpeg.
\r
176 const core::video_format_desc& get_video_format_desc() const
\r
178 return format_desc_;
\r
181 std::wstring print() const
\r
183 return L"ffmpeg[" + widen(filename_) + L"]";
\r
186 std::shared_ptr<AVStream> add_video_stream(enum CodecID codec_id)
\r
188 auto st = av_new_stream(oc_.get(), 0);
\r
191 BOOST_THROW_EXCEPTION(caspar_exception()
\r
192 << msg_info("Could not alloc video-stream")
\r
193 << boost::errinfo_api_function("av_new_stream"));
\r
196 st->codec->codec_id = codec_id;
\r
197 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
\r
198 st->codec->bit_rate = bitrate_;
\r
199 st->codec->width = format_desc_.width;
\r
200 st->codec->height = format_desc_.height;
\r
201 st->codec->time_base.den = format_desc_.time_scale;
\r
202 st->codec->time_base.num = format_desc_.duration;
\r
203 st->codec->pix_fmt = st->codec->pix_fmt == -1 ? PIX_FMT_YUV420P : st->codec->pix_fmt;
\r
205 return std::shared_ptr<AVStream>(st, [](AVStream* st)
\r
207 avcodec_close(st->codec);
\r
212 std::shared_ptr<AVStream> add_audio_stream(enum CodecID codec_id)
\r
214 auto st = av_new_stream(oc_.get(), 1);
\r
217 BOOST_THROW_EXCEPTION(caspar_exception()
\r
218 << msg_info("Could not alloc audio-stream")
\r
219 << boost::errinfo_api_function("av_new_stream"));
\r
222 st->codec->codec_id = codec_id;
\r
223 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
\r
224 st->codec->sample_rate = 48000;
\r
225 st->codec->channels = 2;
\r
226 st->codec->sample_fmt = SAMPLE_FMT_S16;
\r
228 return std::shared_ptr<AVStream>(st, [](AVStream* st)
\r
230 avcodec_close(st->codec);
\r
235 void open_video(std::shared_ptr<AVStream>& st)
\r
237 auto codec = avcodec_find_encoder(st->codec->codec_id);
\r
239 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
241 int errn = avcodec_open(st->codec, codec);
\r
244 BOOST_THROW_EXCEPTION(
\r
245 file_read_error() <<
\r
246 msg_info("Could not open video codec.") <<
\r
247 boost::errinfo_api_function("avcodec_open") <<
\r
248 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
249 boost::errinfo_file_name(filename_));
\r
253 void open_audio(std::shared_ptr<AVStream>& st)
\r
255 auto codec = avcodec_find_encoder(st->codec->codec_id);
\r
257 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
259 int errn = avcodec_open(st->codec, codec);
\r
262 BOOST_THROW_EXCEPTION(
\r
263 file_read_error() <<
\r
264 msg_info("Could not open audio codec") <<
\r
265 boost::errinfo_api_function("avcodec_open") <<
\r
266 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
267 boost::errinfo_file_name(filename_));
\r
271 void encode_video_frame(const safe_ptr<core::read_frame>& frame)
\r
276 AVCodecContext* c = video_st_->codec;
\r
278 if(!img_convert_ctx_)
\r
280 img_convert_ctx_.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
281 if (img_convert_ctx_ == nullptr)
\r
282 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));
\r
285 std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
\r
286 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
288 std::shared_ptr<AVFrame> local_av_frame(avcodec_alloc_frame(), av_free);
\r
289 picture_buf_.resize(avpicture_get_size(c->pix_fmt, format_desc_.width, format_desc_.height));
\r
290 avpicture_fill(reinterpret_cast<AVPicture*>(local_av_frame.get()), picture_buf_.data(), c->pix_fmt, format_desc_.width, format_desc_.height);
\r
292 sws_scale(img_convert_ctx_.get(), av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);
\r
294 int errn = avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), local_av_frame.get());
\r
297 BOOST_THROW_EXCEPTION(
\r
298 invalid_operation() <<
\r
299 msg_info("Could not encode video frame.") <<
\r
300 boost::errinfo_api_function("avcodec_encode_video") <<
\r
301 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
302 boost::errinfo_file_name(filename_));
\r
306 av_init_packet(&pkt);
\r
309 // If zero size, it means the image was buffered.
\r
312 if (c->coded_frame->pts != AV_NOPTS_VALUE)
\r
313 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);
\r
315 if(c->coded_frame->key_frame)
\r
316 pkt.flags |= AV_PKT_FLAG_KEY;
\r
318 pkt.stream_index = video_st_->index;
\r
319 pkt.data = video_outbuf_.data();
\r
321 if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)
\r
322 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing video frame"));
\r
326 void encode_audio_frame(const safe_ptr<core::read_frame>& frame)
\r
331 if(!frame->audio_data().empty())
\r
332 audio_input_buffer_.insert(audio_input_buffer_.end(), frame->audio_data().begin(), frame->audio_data().end());
\r
334 audio_input_buffer_.insert(audio_input_buffer_.end(), 3840, 0);
\r
336 while(encode_audio_packet()){}
\r
339 bool encode_audio_packet()
\r
341 auto c = audio_st_->codec;
\r
343 auto frame_bytes = c->frame_size * 2 * 2; // samples per frame * 2 channels * 2 bytes per sample
\r
344 if(static_cast<int>(audio_input_buffer_.size()) < frame_bytes/2)
\r
348 av_init_packet(&pkt);
\r
350 int errn = avcodec_encode_audio(c, audio_outbuf_.data(), audio_outbuf_.size(), audio_input_buffer_.data());
\r
353 BOOST_THROW_EXCEPTION(
\r
354 invalid_operation() <<
\r
355 msg_info("Could not encode audio samples.") <<
\r
356 boost::errinfo_api_function("avcodec_encode_audio") <<
\r
357 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
358 boost::errinfo_file_name(filename_));
\r
362 audio_input_buffer_ = std::vector<int16_t>(audio_input_buffer_.begin() + frame_bytes/2, audio_input_buffer_.end());
\r
364 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
\r
365 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);
\r
367 pkt.flags |= AV_PKT_FLAG_KEY;
\r
368 pkt.stream_index = audio_st_->index;
\r
369 pkt.data = audio_outbuf_.data();
\r
371 if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)
\r
372 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing audio frame"));
\r
377 void send(const safe_ptr<core::read_frame>& frame)
\r
379 executor_.begin_invoke([=]
\r
381 encode_video_frame(frame);
\r
382 encode_audio_frame(frame);
\r
386 size_t buffer_depth() const { return 1; }
\r
389 struct ffmpeg_consumer_proxy : public core::frame_consumer
\r
391 const std::wstring filename_;
\r
392 const bool key_only_;
\r
393 const size_t bitrate_;
\r
395 std::unique_ptr<ffmpeg_consumer> consumer_;
\r
399 ffmpeg_consumer_proxy(const std::wstring& filename, bool key_only, size_t bitrate)
\r
400 : filename_(filename)
\r
401 , key_only_(key_only)
\r
402 , bitrate_(bitrate){}
\r
404 virtual void initialize(const core::video_format_desc& format_desc)
\r
406 consumer_.reset(new ffmpeg_consumer(narrow(filename_), format_desc, bitrate_));
\r
409 virtual void send(const safe_ptr<core::read_frame>& frame)
\r
411 consumer_->send(frame);
\r
414 virtual std::wstring print() const
\r
416 return consumer_->print();
\r
419 virtual bool key_only() const
\r
424 virtual bool has_synchronization_clock() const
\r
429 virtual const core::video_format_desc& get_video_format_desc() const
\r
431 return consumer_->get_video_format_desc();
\r
435 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const std::vector<std::wstring>& params)
\r
437 if(params.size() < 2 || params[0] != L"FILE")
\r
438 return core::frame_consumer::empty();
\r
440 // TODO: Ask stakeholders about case where file already exists.
\r
441 boost::filesystem::remove(boost::filesystem::wpath(env::media_folder() + params[1])); // Delete the file if it exists
\r
442 bool key_only = std::find(params.begin(), params.end(), L"KEY_ONLY") != params.end();
\r
444 return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + params[1], key_only, 100000000);
\r
447 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const boost::property_tree::ptree& ptree)
\r
449 std::string filename = ptree.get<std::string>("path");
\r
450 bool key_only = ptree.get("key-only", false);
\r
451 size_t bitrate = ptree.get("bitrate", 100000000);
\r
453 return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + widen(filename), key_only, bitrate);
\r