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
27 #include <common/concurrency/executor.h>
\r
28 #include <common/utility/string.h>
\r
29 #include <common/env.h>
\r
31 #include <boost/thread/once.hpp>
\r
33 #include <tbb/cache_aligned_allocator.h>
\r
34 #include <tbb/parallel_invoke.h>
\r
38 #if defined(_MSC_VER)
\r
39 #pragma warning (push)
\r
40 #pragma warning (disable : 4244)
\r
44 #define __STDC_CONSTANT_MACROS
\r
45 #define __STDC_LIMIT_MACROS
\r
46 #include <libavformat/avformat.h>
\r
47 #include <libswscale/swscale.h>
\r
49 #if defined(_MSC_VER)
\r
50 #pragma warning (pop)
\r
55 struct ffmpeg_consumer : boost::noncopyable
\r
57 const std::string filename_;
\r
58 const size_t bitrate_;
\r
60 const std::shared_ptr<AVFormatContext> oc_;
\r
61 const core::video_format_desc format_desc_;
\r
66 std::shared_ptr<AVStream> audio_st_;
\r
67 std::vector<uint8_t> audio_outbuf_;
\r
69 std::vector<int16_t> audio_input_buffer_;
\r
72 std::shared_ptr<AVStream> video_st_;
\r
73 std::vector<uint8_t> video_outbuf_;
\r
75 std::vector<uint8_t> picture_buf_;
\r
76 std::shared_ptr<SwsContext> img_convert_ctx_;
\r
79 ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, size_t bitrate)
\r
80 : filename_(filename)
\r
82 , video_outbuf_(1920*1080*4)
\r
83 , audio_outbuf_(48000)
\r
84 , oc_(avformat_alloc_context(), av_free)
\r
85 , format_desc_(format_desc)
\r
86 , executor_(print())
\r
90 BOOST_THROW_EXCEPTION(caspar_exception()
\r
91 << msg_info("Could not alloc format-context")
\r
92 << boost::errinfo_api_function("avformat_alloc_context"));
\r
95 executor_.set_capacity(CONSUMER_BUFFER_DEPTH);
\r
97 oc_->oformat = av_guess_format(nullptr, filename_.c_str(), nullptr);
\r
99 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format."));
\r
101 std::copy_n(filename_.c_str(), filename_.size(), oc_->filename);
\r
103 // Add the audio and video streams using the default format codecs and initialize the codecs .
\r
104 if (oc_->oformat->video_codec != CODEC_ID_NONE)
\r
105 video_st_ = add_video_stream(oc_->oformat->video_codec);
\r
107 //if (oc_->oformat->audio_codec != CODEC_ID_NONE)
\r
108 // audio_st_ = add_audio_stream(oc_->oformat->audio_codec);
\r
110 // Set the output parameters (must be done even if no parameters).
\r
111 int errn = av_set_parameters(oc_.get(), nullptr);
\r
114 BOOST_THROW_EXCEPTION(
\r
115 file_read_error() <<
\r
116 msg_info("Invalid output format parameters") <<
\r
117 boost::errinfo_api_function("avcodec_open") <<
\r
118 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
119 boost::errinfo_file_name(filename_));
\r
122 dump_format(oc_.get(), 0, filename_.c_str(), 1);
\r
124 // Now that all the parameters are set, we can open the audio and
\r
125 // video codecs and allocate the necessary encode buffers.
\r
127 open_video(video_st_);
\r
132 open_audio(audio_st_);
\r
136 CASPAR_LOG_CURRENT_EXCEPTION();
\r
137 audio_st_ = nullptr;
\r
140 // Open the output ffmpeg, if needed.
\r
141 if (!(oc_->oformat->flags & AVFMT_NOFILE))
\r
143 int errn = url_fopen(&oc_->pb, filename_.c_str(), URL_WRONLY);
\r
146 BOOST_THROW_EXCEPTION(
\r
147 file_not_found() <<
\r
148 msg_info("Could not open file") <<
\r
149 boost::errinfo_api_function("url_fopen") <<
\r
150 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
151 boost::errinfo_file_name(filename_));
\r
155 av_write_header(oc_.get()); // write the stream header, if any
\r
157 CASPAR_LOG(info) << print() << L" Successfully initialized.";
\r
168 av_write_trailer(oc_.get());
\r
170 if (!(oc_->oformat->flags & AVFMT_NOFILE))
\r
171 url_fclose(oc_->pb); // Close the output ffmpeg.
\r
174 const core::video_format_desc& get_video_format_desc() const
\r
176 return format_desc_;
\r
179 std::wstring print() const
\r
181 return L"ffmpeg[" + widen(filename_) + L"]";
\r
184 std::shared_ptr<AVStream> add_video_stream(enum CodecID codec_id)
\r
186 auto st = av_new_stream(oc_.get(), 0);
\r
189 BOOST_THROW_EXCEPTION(caspar_exception()
\r
190 << msg_info("Could not alloc video-stream")
\r
191 << boost::errinfo_api_function("av_new_stream"));
\r
194 st->codec->codec_id = codec_id;
\r
195 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
\r
196 st->codec->bit_rate = bitrate_;
\r
197 st->codec->width = format_desc_.width;
\r
198 st->codec->height = format_desc_.height;
\r
199 st->codec->time_base.den = format_desc_.time_scale;
\r
200 st->codec->time_base.num = format_desc_.duration;
\r
201 st->codec->pix_fmt = st->codec->pix_fmt == -1 ? PIX_FMT_YUV420P : st->codec->pix_fmt;
\r
203 return std::shared_ptr<AVStream>(st, [](AVStream* st)
\r
205 avcodec_close(st->codec);
\r
210 std::shared_ptr<AVStream> add_audio_stream(enum CodecID codec_id)
\r
212 auto st = av_new_stream(oc_.get(), 1);
\r
215 BOOST_THROW_EXCEPTION(caspar_exception()
\r
216 << msg_info("Could not alloc audio-stream")
\r
217 << boost::errinfo_api_function("av_new_stream"));
\r
220 st->codec->codec_id = codec_id;
\r
221 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
\r
222 st->codec->sample_rate = 48000;
\r
223 st->codec->channels = 2;
\r
224 st->codec->sample_fmt = SAMPLE_FMT_S16;
\r
226 return std::shared_ptr<AVStream>(st, [](AVStream* st)
\r
228 avcodec_close(st->codec);
\r
233 void open_video(std::shared_ptr<AVStream>& st)
\r
235 auto codec = avcodec_find_encoder(st->codec->codec_id);
\r
237 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
239 int errn = avcodec_open(st->codec, codec);
\r
242 BOOST_THROW_EXCEPTION(
\r
243 file_read_error() <<
\r
244 msg_info("Could not open video codec.") <<
\r
245 boost::errinfo_api_function("avcodec_open") <<
\r
246 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
247 boost::errinfo_file_name(filename_));
\r
251 void open_audio(std::shared_ptr<AVStream>& st)
\r
253 auto codec = avcodec_find_encoder(st->codec->codec_id);
\r
255 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
257 int errn = avcodec_open(st->codec, codec);
\r
260 BOOST_THROW_EXCEPTION(
\r
261 file_read_error() <<
\r
262 msg_info("Could not open audio codec") <<
\r
263 boost::errinfo_api_function("avcodec_open") <<
\r
264 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
265 boost::errinfo_file_name(filename_));
\r
269 void encode_video_frame(const safe_ptr<const core::read_frame>& frame)
\r
274 AVCodecContext* c = video_st_->codec;
\r
276 if(!img_convert_ctx_)
\r
278 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
279 if (img_convert_ctx_ == 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(img_convert_ctx_.get(), av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);
\r
292 int errn = avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), local_av_frame.get());
\r
295 BOOST_THROW_EXCEPTION(
\r
296 invalid_operation() <<
\r
297 msg_info("Could not encode video frame.") <<
\r
298 boost::errinfo_api_function("avcodec_encode_video") <<
\r
299 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
300 boost::errinfo_file_name(filename_));
\r
304 av_init_packet(&pkt);
\r
307 // If zero size, it means the image was buffered.
\r
310 if (c->coded_frame->pts != AV_NOPTS_VALUE)
\r
311 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);
\r
313 if(c->coded_frame->key_frame)
\r
314 pkt.flags |= AV_PKT_FLAG_KEY;
\r
316 pkt.stream_index = video_st_->index;
\r
317 pkt.data = video_outbuf_.data();
\r
319 if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)
\r
320 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing video frame"));
\r
324 void encode_audio_frame(const safe_ptr<const core::read_frame>& frame)
\r
329 if(!frame->audio_data().empty())
\r
330 audio_input_buffer_.insert(audio_input_buffer_.end(), frame->audio_data().begin(), frame->audio_data().end());
\r
332 audio_input_buffer_.insert(audio_input_buffer_.end(), 3840, 0);
\r
334 while(encode_audio_packet()){}
\r
337 bool encode_audio_packet()
\r
339 auto c = audio_st_->codec;
\r
341 auto frame_bytes = c->frame_size * 2 * 2; // samples per frame * 2 channels * 2 bytes per sample
\r
342 if(static_cast<int>(audio_input_buffer_.size()) < frame_bytes/2)
\r
346 av_init_packet(&pkt);
\r
348 int errn = avcodec_encode_audio(c, audio_outbuf_.data(), audio_outbuf_.size(), audio_input_buffer_.data());
\r
351 BOOST_THROW_EXCEPTION(
\r
352 invalid_operation() <<
\r
353 msg_info("Could not encode audio samples.") <<
\r
354 boost::errinfo_api_function("avcodec_encode_audio") <<
\r
355 boost::errinfo_errno(AVUNERROR(errn)) <<
\r
356 boost::errinfo_file_name(filename_));
\r
360 audio_input_buffer_ = std::vector<int16_t>(audio_input_buffer_.begin() + frame_bytes/2, audio_input_buffer_.end());
\r
362 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
\r
363 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);
\r
365 pkt.flags |= AV_PKT_FLAG_KEY;
\r
366 pkt.stream_index = audio_st_->index;
\r
367 pkt.data = audio_outbuf_.data();
\r
369 if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)
\r
370 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing audio frame"));
\r
375 void send(const safe_ptr<const core::read_frame>& frame)
\r
377 executor_.begin_invoke([=]
\r
379 encode_video_frame(frame);
\r
380 encode_audio_frame(frame);
\r
384 size_t buffer_depth() const { return 1; }
\r
387 struct ffmpeg_consumer_proxy : public core::frame_consumer
\r
389 const std::wstring filename_;
\r
390 const bool key_only_;
\r
391 const size_t bitrate_;
\r
393 std::unique_ptr<ffmpeg_consumer> consumer_;
\r
397 ffmpeg_consumer_proxy(const std::wstring& filename, bool key_only, size_t bitrate)
\r
398 : filename_(filename)
\r
399 , key_only_(key_only)
\r
400 , bitrate_(bitrate){}
\r
402 virtual void initialize(const core::video_format_desc& format_desc)
\r
404 consumer_.reset(new ffmpeg_consumer(narrow(filename_), format_desc, bitrate_));
\r
407 virtual void send(const safe_ptr<const core::read_frame>& frame)
\r
409 consumer_->send(frame);
\r
412 virtual std::wstring print() const
\r
414 return consumer_->print();
\r
417 virtual bool key_only() const
\r
422 virtual bool has_synchronization_clock() const
\r
427 virtual const core::video_format_desc& get_video_format_desc() const
\r
429 return consumer_->get_video_format_desc();
\r
433 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const std::vector<std::wstring>& params)
\r
435 if(params.size() < 2 || params[0] != L"FILE")
\r
436 return core::frame_consumer::empty();
\r
438 // TODO: Ask stakeholders about case where file already exists.
\r
439 boost::filesystem::remove(boost::filesystem::wpath(env::media_folder() + params[1])); // Delete the file if it exists
\r
440 bool key_only = std::find(params.begin(), params.end(), L"KEY_ONLY") != params.end();
\r
442 return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + params[1], key_only, 100000000);
\r
445 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const boost::property_tree::ptree& ptree)
\r
447 std::string filename = ptree.get<std::string>("path");
\r
448 bool key_only = ptree.get("key-only", false);
\r
449 size_t bitrate = ptree.get("bitrate", 100000000);
\r
451 return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + widen(filename), key_only, bitrate);
\r