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 std::string filename_;
\r
60 AVStream* audio_st_;
\r
61 std::vector<unsigned char, tbb::cache_aligned_allocator<unsigned char>> audio_outbuf_;
\r
64 AVStream* video_st_;
\r
65 std::vector<uint8_t, tbb::cache_aligned_allocator<unsigned char>> picture_buf_;
\r
67 std::vector<unsigned char, tbb::cache_aligned_allocator<unsigned char>> video_outbuf_;
\r
68 SwsContext* img_convert_ctx_;
\r
70 AVOutputFormat* fmt_;
\r
71 std::shared_ptr<AVFormatContext> oc_;
\r
72 core::video_format_desc format_desc_;
\r
74 std::vector<short, tbb::cache_aligned_allocator<short>> audio_input_buffer_;
\r
76 boost::unique_future<void> active_;
\r
80 ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc)
\r
81 : filename_(filename)
\r
82 , audio_st_(nullptr)
\r
83 , video_st_(nullptr)
\r
85 , img_convert_ctx_(nullptr)
\r
86 , video_outbuf_(1920*1080*4)
\r
87 , audio_outbuf_(48000)
\r
88 , format_desc_(format_desc)
\r
89 , executor_(L"ffmpeg_consumer")
\r
91 active_ = executor_.begin_invoke([]{});
\r
93 fmt_ = av_guess_format(nullptr, filename_.c_str(), nullptr);
\r
96 CASPAR_LOG(info) << "Could not deduce output format from ffmpeg extension: using MPEG.";
\r
97 fmt_ = av_guess_format("mpeg", nullptr, nullptr);
\r
98 filename_ = filename_ + ".avi";
\r
101 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format"));
\r
103 oc_.reset(avformat_alloc_context(), av_free);
\r
105 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Memory error"));
\r
106 std::copy_n(filename_.c_str(), filename_.size(), oc_->filename);
\r
108 oc_->oformat = fmt_;
\r
109 // To avoid mpeg buffer underflow (http://www.mail-archive.com/libav-user@mplayerhq.hu/msg00194.html)
\r
110 oc_->preload = static_cast<int>(0.5*AV_TIME_BASE);
\r
111 oc_->max_delay = static_cast<int>(0.7*AV_TIME_BASE);
\r
113 // Add the audio and video streams using the default format codecs and initialize the codecs .
\r
114 if (fmt_->video_codec != CODEC_ID_NONE)
\r
115 video_st_ = add_video_stream(fmt_->video_codec);
\r
117 if (fmt_->audio_codec != CODEC_ID_NONE)
\r
118 audio_st_ = add_audio_stream(fmt_->audio_codec);
\r
120 // Set the output parameters (must be done even if no parameters).
\r
122 if ((errn = -av_set_parameters(oc_.get(), nullptr)) > 0)
\r
123 BOOST_THROW_EXCEPTION(
\r
124 file_read_error() <<
\r
125 msg_info("Invalid output format parameters") <<
\r
126 boost::errinfo_api_function("avcodec_open") <<
\r
127 boost::errinfo_errno(errn) <<
\r
128 boost::errinfo_file_name(filename_));
\r
130 dump_format(oc_.get(), 0, filename_.c_str(), 1);
\r
132 // Now that all the parameters are set, we can open the audio and
\r
133 // video codecs and allocate the necessary encode buffers.
\r
135 open_video(video_st_);
\r
140 open_audio(audio_st_);
\r
144 CASPAR_LOG_CURRENT_EXCEPTION();
\r
145 audio_st_ = nullptr;
\r
148 // Open the output ffmpeg, if needed.
\r
149 if (!(fmt_->flags & AVFMT_NOFILE))
\r
152 if ((errn = -url_fopen(&oc_->pb, filename_.c_str(), URL_WRONLY)) > 0)
\r
153 BOOST_THROW_EXCEPTION(
\r
154 file_not_found() <<
\r
155 msg_info("Could not open file") <<
\r
156 boost::errinfo_api_function("url_fopen") <<
\r
157 boost::errinfo_errno(errn) <<
\r
158 boost::errinfo_file_name(filename_));
\r
161 av_write_header(oc_.get()); // write the stream header, if any
\r
163 CASPAR_LOG(info) << print() << L" Successfully initialized.";
\r
168 executor_.invoke([]{});
\r
171 av_write_trailer(oc_.get());
\r
173 // Close each codec.
\r
175 avcodec_close(video_st_->codec);
\r
178 avcodec_close(audio_st_->codec);
\r
180 // Free the streams.
\r
181 for(size_t i = 0; i < oc_->nb_streams; ++i)
\r
183 av_freep(&oc_->streams[i]->codec);
\r
184 av_freep(&oc_->streams[i]);
\r
187 if (!(fmt_->flags & AVFMT_NOFILE))
\r
188 url_fclose(oc_->pb); // Close the output ffmpeg.
\r
191 const core::video_format_desc& get_video_format_desc() const
\r
193 return format_desc_;
\r
196 std::wstring print() const
\r
198 return L"ffmpeg[" + widen(filename_) + L"]";
\r
201 AVStream* add_video_stream(enum CodecID codec_id)
\r
203 auto st = av_new_stream(oc_.get(), 0);
\r
205 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not alloc stream"));
\r
207 auto c = st->codec;
\r
208 c->codec_id = codec_id;
\r
209 c->codec_type = AVMEDIA_TYPE_VIDEO;
\r
211 // Put sample parameters.
\r
212 c->bit_rate = static_cast<int>(static_cast<double>(format_desc_.size)*format_desc_.fps*0.1326);
\r
213 c->width = format_desc_.width;
\r
214 c->height = format_desc_.height;
\r
215 c->time_base.den = static_cast<int>(format_desc_.fps);
\r
216 c->time_base.num = 1;
\r
217 c->pix_fmt = c->pix_fmt == -1 ? PIX_FMT_YUV420P : c->pix_fmt;
\r
219 // Some formats want stream headers to be separate.
\r
220 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
\r
221 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
\r
226 void open_video(AVStream* st)
\r
228 auto c = st->codec;
\r
230 auto codec = avcodec_find_encoder(c->codec_id);
\r
232 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
235 if ((errn = -avcodec_open(c, codec)) > 0)
\r
236 BOOST_THROW_EXCEPTION(
\r
237 file_read_error() <<
\r
238 msg_info("Could not open video codec.") <<
\r
239 boost::errinfo_api_function("avcodec_open") <<
\r
240 boost::errinfo_errno(errn) <<
\r
241 boost::errinfo_file_name(filename_));
\r
244 void encode_video_frame(const safe_ptr<const core::read_frame>& frame)
\r
249 AVCodecContext* c = video_st_->codec;
\r
251 if (img_convert_ctx_ == nullptr)
\r
253 img_convert_ctx_ = sws_getContext(format_desc_.width, format_desc_.height, PIX_FMT_BGRA, c->width, c->height, c->pix_fmt, SWS_BICUBIC, nullptr, nullptr, nullptr);
\r
254 if (img_convert_ctx_ == nullptr)
\r
255 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));
\r
258 std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
\r
259 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
261 std::shared_ptr<AVFrame> local_av_frame(avcodec_alloc_frame(), av_free);
\r
262 picture_buf_.resize(avpicture_get_size(c->pix_fmt, format_desc_.width, format_desc_.height));
\r
263 avpicture_fill(reinterpret_cast<AVPicture*>(local_av_frame.get()), picture_buf_.data(), c->pix_fmt, format_desc_.width, format_desc_.height);
\r
265 sws_scale(img_convert_ctx_, av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);
\r
267 int ret = avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), local_av_frame.get());
\r
271 BOOST_THROW_EXCEPTION(
\r
272 invalid_operation() <<
\r
273 msg_info("Could not encode video frame.") <<
\r
274 boost::errinfo_api_function("avcodec_encode_video") <<
\r
275 boost::errinfo_errno(errn) <<
\r
276 boost::errinfo_file_name(filename_));
\r
278 auto out_size = ret;
\r
280 av_init_packet(&pkt);
\r
281 pkt.size = out_size;
\r
283 // If zero size, it means the image was buffered.
\r
286 if (c->coded_frame->pts != AV_NOPTS_VALUE)
\r
287 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);
\r
288 if(c->coded_frame->key_frame)
\r
289 pkt.flags |= AV_PKT_FLAG_KEY;
\r
291 pkt.stream_index = video_st_->index;
\r
292 pkt.data = video_outbuf_.data();
\r
294 if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)
\r
295 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing video frame"));
\r
299 AVStream* add_audio_stream(enum CodecID codec_id)
\r
301 audio_st_ = av_new_stream(oc_.get(), 1);
\r
303 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not alloc stream"));
\r
305 auto c = audio_st_->codec;
\r
306 c->codec_id = codec_id;
\r
307 c->codec_type = AVMEDIA_TYPE_AUDIO;
\r
309 // Put sample parameters.
\r
310 c->bit_rate = 192000;
\r
311 c->sample_rate = 48000;
\r
314 // Some formats want stream headers to be separate.
\r
315 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
\r
316 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
\r
321 void open_audio(AVStream* st)
\r
323 auto c = st->codec;
\r
325 // Find the audio encoder.
\r
326 auto codec = avcodec_find_encoder(c->codec_id);
\r
328 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
332 if ((errn = -avcodec_open(c, codec)) > 0)
\r
333 BOOST_THROW_EXCEPTION(
\r
334 file_read_error() <<
\r
335 msg_info("Could not open audio codec") <<
\r
336 boost::errinfo_api_function("avcodec_open") <<
\r
337 boost::errinfo_errno(errn) <<
\r
338 boost::errinfo_file_name(filename_));
\r
341 void encode_audio_frame(const safe_ptr<const core::read_frame>& frame)
\r
343 if(!frame->audio_data().empty())
\r
344 audio_input_buffer_.insert(audio_input_buffer_.end(), frame->audio_data().begin(), frame->audio_data().end());
\r
346 audio_input_buffer_.insert(audio_input_buffer_.end(), 3840, 0);
\r
348 while(encode_audio_packet()){}
\r
351 bool encode_audio_packet()
\r
356 auto c = audio_st_->codec;
\r
358 auto frame_bytes = c->frame_size * 2 * 2; // samples per frame * 2 channels * 2 bytes per sample
\r
359 if(static_cast<int>(audio_input_buffer_.size()) < frame_bytes/2)
\r
363 av_init_packet(&pkt);
\r
365 int ret = avcodec_encode_audio(c, audio_outbuf_.data(), audio_outbuf_.size(), audio_input_buffer_.data());
\r
369 BOOST_THROW_EXCEPTION(
\r
370 invalid_operation() <<
\r
371 msg_info("Could not encode audio samples.") <<
\r
372 boost::errinfo_api_function("avcodec_encode_audio") <<
\r
373 boost::errinfo_errno(errn) <<
\r
374 boost::errinfo_file_name(filename_));
\r
377 audio_input_buffer_ = std::vector<short, tbb::cache_aligned_allocator<short>>(audio_input_buffer_.begin() + frame_bytes/2, audio_input_buffer_.end());
\r
379 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
\r
380 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);
\r
381 pkt.flags |= AV_PKT_FLAG_KEY;
\r
382 pkt.stream_index = audio_st_->index;
\r
383 pkt.data = audio_outbuf_.data();
\r
385 if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)
\r
386 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing audio frame"));
\r
391 void send(const safe_ptr<const core::read_frame>& frame)
\r
394 active_ = executor_.begin_invoke([=]
\r
396 auto my_frame = frame;
\r
397 encode_video_frame(my_frame);
\r
398 encode_audio_frame(my_frame);
\r
402 size_t buffer_depth() const { return 1; }
\r
405 struct ffmpeg_consumer_proxy : public core::frame_consumer
\r
407 const std::wstring filename_;
\r
408 const bool key_only_;
\r
410 std::unique_ptr<ffmpeg_consumer> consumer_;
\r
414 ffmpeg_consumer_proxy(const std::wstring& filename, bool key_only)
\r
415 : filename_(filename)
\r
416 , key_only_(key_only){}
\r
418 virtual void initialize(const core::video_format_desc& format_desc)
\r
420 consumer_.reset(new ffmpeg_consumer(narrow(filename_), format_desc));
\r
423 virtual void send(const safe_ptr<const core::read_frame>& frame)
\r
425 consumer_->send(frame);
\r
428 virtual std::wstring print() const
\r
430 return consumer_->print();
\r
433 virtual bool key_only() const
\r
438 virtual const core::video_format_desc& get_video_format_desc() const
\r
440 return consumer_->get_video_format_desc();
\r
444 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const std::vector<std::wstring>& params)
\r
446 if(params.size() < 2 || params[0] != L"FILE")
\r
447 return core::frame_consumer::empty();
\r
449 // TODO: Ask stakeholders about case where file already exists.
\r
450 boost::filesystem::remove(boost::filesystem::wpath(env::media_folder() + params[1])); // Delete the file if it exists
\r
451 bool key_only = std::find(params.begin(), params.end(), L"KEY_ONLY") != params.end();
\r
453 return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + params[1], key_only);
\r
456 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const boost::property_tree::ptree& ptree)
\r
458 std::string filename = ptree.get<std::string>("filename");
\r
459 bool key_only = ptree.get("key-only", false);
\r
461 return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + widen(filename), key_only);
\r