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/consumer/frame/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::implementation : boost::noncopyable
\r
57 printer parent_printer_;
\r
58 std::string filename_;
\r
61 AVStream* audio_st_;
\r
62 std::vector<unsigned char, tbb::cache_aligned_allocator<unsigned char>> audio_outbuf_;
\r
65 AVStream* video_st_;
\r
66 std::vector<uint8_t, tbb::cache_aligned_allocator<unsigned char>> picture_buf_;
\r
68 std::vector<unsigned char, tbb::cache_aligned_allocator<unsigned char>> video_outbuf_;
\r
69 SwsContext* img_convert_ctx_;
\r
71 AVOutputFormat* fmt_;
\r
72 std::shared_ptr<AVFormatContext> oc_;
\r
73 core::video_format_desc format_desc_;
\r
75 std::vector<short, tbb::cache_aligned_allocator<short>> audio_input_buffer_;
\r
77 boost::unique_future<void> active_;
\r
81 implementation(const std::string& filename)
\r
82 : filename_(filename)
\r
83 , audio_st_(nullptr)
\r
84 , video_st_(nullptr)
\r
86 , img_convert_ctx_(nullptr)
\r
87 , video_outbuf_(1920*1080*4)
\r
88 , audio_outbuf_(48000)
\r
89 , executor_(L"ffmpeg_consumer")
\r
94 executor_.invoke([]{});
\r
97 av_write_trailer(oc_.get());
\r
99 // Close each codec.
\r
101 avcodec_close(video_st_->codec);
\r
104 avcodec_close(audio_st_->codec);
\r
106 // Free the streams.
\r
107 for(size_t i = 0; i < oc_->nb_streams; ++i)
\r
109 av_freep(&oc_->streams[i]->codec);
\r
110 av_freep(&oc_->streams[i]);
\r
113 if (!(fmt_->flags & AVFMT_NOFILE))
\r
114 url_fclose(oc_->pb); // Close the output ffmpeg.
\r
117 void initialize(const core::video_format_desc& format_desc, const printer& parent_printer)
\r
119 format_desc_ = format_desc;
\r
120 parent_printer_ = parent_printer;
\r
122 active_ = executor_.begin_invoke([]{});
\r
124 fmt_ = av_guess_format(nullptr, filename_.c_str(), nullptr);
\r
127 CASPAR_LOG(warning) << "Could not deduce output format from ffmpeg extension: using MPEG.";
\r
128 fmt_ = av_guess_format("mpeg", nullptr, nullptr);
\r
129 filename_ = filename_ + ".avi";
\r
132 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format"));
\r
134 oc_.reset(avformat_alloc_context(), av_free);
\r
136 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Memory error"));
\r
137 std::copy_n(filename_.c_str(), filename_.size(), oc_->filename);
\r
139 oc_->oformat = fmt_;
\r
140 // To avoid mpeg buffer underflow (http://www.mail-archive.com/libav-user@mplayerhq.hu/msg00194.html)
\r
141 oc_->preload = static_cast<int>(0.5*AV_TIME_BASE);
\r
142 oc_->max_delay = static_cast<int>(0.7*AV_TIME_BASE);
\r
144 // Add the audio and video streams using the default format codecs and initialize the codecs .
\r
145 if (fmt_->video_codec != CODEC_ID_NONE)
\r
146 video_st_ = add_video_stream(fmt_->video_codec);
\r
148 if (fmt_->audio_codec != CODEC_ID_NONE)
\r
149 audio_st_ = add_audio_stream(fmt_->audio_codec);
\r
151 // Set the output parameters (must be done even if no parameters).
\r
153 if ((errn = -av_set_parameters(oc_.get(), nullptr)) > 0)
\r
154 BOOST_THROW_EXCEPTION(
\r
155 file_read_error() <<
\r
156 msg_info("Invalid output format parameters") <<
\r
157 boost::errinfo_api_function("avcodec_open") <<
\r
158 boost::errinfo_errno(errn) <<
\r
159 boost::errinfo_file_name(filename_));
\r
161 dump_format(oc_.get(), 0, filename_.c_str(), 1);
\r
163 // Now that all the parameters are set, we can open the audio and
\r
164 // video codecs and allocate the necessary encode buffers.
\r
166 open_video(video_st_);
\r
171 open_audio(audio_st_);
\r
175 CASPAR_LOG_CURRENT_EXCEPTION();
\r
176 audio_st_ = nullptr;
\r
179 // Open the output ffmpeg, if needed.
\r
180 if (!(fmt_->flags & AVFMT_NOFILE))
\r
183 if ((errn = -url_fopen(&oc_->pb, filename_.c_str(), URL_WRONLY)) > 0)
\r
184 BOOST_THROW_EXCEPTION(
\r
185 file_not_found() <<
\r
186 msg_info("Could not open file") <<
\r
187 boost::errinfo_api_function("url_fopen") <<
\r
188 boost::errinfo_errno(errn) <<
\r
189 boost::errinfo_file_name(filename_));
\r
192 av_write_header(oc_.get()); // write the stream header, if any
\r
194 CASPAR_LOG(info) << print() << L" Successfully initialized.";
\r
197 std::wstring print() const
\r
199 return (parent_printer_ ? parent_printer_() + L"/" : L"") + L"ffmpeg[" + widen(filename_) + L"]";
\r
202 AVStream* add_video_stream(enum CodecID codec_id)
\r
204 auto st = av_new_stream(oc_.get(), 0);
\r
206 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not alloc stream"));
\r
208 auto c = st->codec;
\r
209 c->codec_id = codec_id;
\r
210 c->codec_type = AVMEDIA_TYPE_VIDEO;
\r
212 // Put sample parameters.
\r
213 c->bit_rate = static_cast<int>(static_cast<double>(format_desc_.size)*format_desc_.fps*0.1326);
\r
214 c->width = format_desc_.width;
\r
215 c->height = format_desc_.height;
\r
216 c->time_base.den = static_cast<int>(format_desc_.fps);
\r
217 c->time_base.num = 1;
\r
218 c->pix_fmt = c->pix_fmt == -1 ? PIX_FMT_YUV420P : c->pix_fmt;
\r
220 // Some formats want stream headers to be separate.
\r
221 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
\r
222 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
\r
227 void open_video(AVStream* st)
\r
229 auto c = st->codec;
\r
231 auto codec = avcodec_find_encoder(c->codec_id);
\r
233 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
236 if ((errn = -avcodec_open(c, codec)) > 0)
\r
237 BOOST_THROW_EXCEPTION(
\r
238 file_read_error() <<
\r
239 msg_info("Could not open video codec.") <<
\r
240 boost::errinfo_api_function("avcodec_open") <<
\r
241 boost::errinfo_errno(errn) <<
\r
242 boost::errinfo_file_name(filename_));
\r
245 void encode_video_frame(const safe_ptr<const core::read_frame>& frame)
\r
247 AVCodecContext* c = video_st_->codec;
\r
249 if (img_convert_ctx_ == nullptr)
\r
251 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
252 if (img_convert_ctx_ == nullptr)
\r
253 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));
\r
256 std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
\r
257 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
259 std::shared_ptr<AVFrame> local_av_frame(avcodec_alloc_frame(), av_free);
\r
260 picture_buf_.resize(avpicture_get_size(c->pix_fmt, format_desc_.width, format_desc_.height));
\r
261 avpicture_fill(reinterpret_cast<AVPicture*>(local_av_frame.get()), picture_buf_.data(), c->pix_fmt, format_desc_.width, format_desc_.height);
\r
263 sws_scale(img_convert_ctx_, av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);
\r
265 int ret = avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), local_av_frame.get());
\r
269 BOOST_THROW_EXCEPTION(
\r
270 invalid_operation() <<
\r
271 msg_info("Could not encode video frame.") <<
\r
272 boost::errinfo_api_function("avcodec_encode_video") <<
\r
273 boost::errinfo_errno(errn) <<
\r
274 boost::errinfo_file_name(filename_));
\r
276 auto out_size = ret;
\r
278 av_init_packet(&pkt);
\r
279 pkt.size = out_size;
\r
281 // If zero size, it means the image was buffered.
\r
284 if (c->coded_frame->pts != AV_NOPTS_VALUE)
\r
285 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);
\r
286 if(c->coded_frame->key_frame)
\r
287 pkt.flags |= AV_PKT_FLAG_KEY;
\r
289 pkt.stream_index = video_st_->index;
\r
290 pkt.data = video_outbuf_.data();
\r
292 if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)
\r
293 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing video frame"));
\r
297 AVStream* add_audio_stream(enum CodecID codec_id)
\r
299 audio_st_ = av_new_stream(oc_.get(), 1);
\r
301 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not alloc stream"));
\r
303 auto c = audio_st_->codec;
\r
304 c->codec_id = codec_id;
\r
305 c->codec_type = AVMEDIA_TYPE_AUDIO;
\r
307 // Put sample parameters.
\r
308 c->bit_rate = 192000;
\r
309 c->sample_rate = 48000;
\r
312 // Some formats want stream headers to be separate.
\r
313 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
\r
314 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
\r
319 void open_audio(AVStream* st)
\r
321 auto c = st->codec;
\r
323 // Find the audio encoder.
\r
324 auto codec = avcodec_find_encoder(c->codec_id);
\r
326 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));
\r
330 if ((errn = -avcodec_open(c, codec)) > 0)
\r
331 BOOST_THROW_EXCEPTION(
\r
332 file_read_error() <<
\r
333 msg_info("Could not open audio codec") <<
\r
334 boost::errinfo_api_function("avcodec_open") <<
\r
335 boost::errinfo_errno(errn) <<
\r
336 boost::errinfo_file_name(filename_));
\r
339 void encode_audio_frame(const safe_ptr<const core::read_frame>& frame)
\r
341 if(!frame->audio_data().empty())
\r
342 audio_input_buffer_.insert(audio_input_buffer_.end(), frame->audio_data().begin(), frame->audio_data().end());
\r
344 audio_input_buffer_.insert(audio_input_buffer_.end(), 3840, 0);
\r
346 while(encode_audio_packet()){}
\r
349 bool encode_audio_packet()
\r
351 auto c = audio_st_->codec;
\r
353 auto frame_bytes = c->frame_size * 2 * 2; // samples per frame * 2 channels * 2 bytes per sample
\r
354 if(static_cast<int>(audio_input_buffer_.size()) < frame_bytes/2)
\r
358 av_init_packet(&pkt);
\r
360 int ret = avcodec_encode_audio(c, audio_outbuf_.data(), audio_outbuf_.size(), audio_input_buffer_.data());
\r
364 BOOST_THROW_EXCEPTION(
\r
365 invalid_operation() <<
\r
366 msg_info("Could not encode audio samples.") <<
\r
367 boost::errinfo_api_function("avcodec_encode_audio") <<
\r
368 boost::errinfo_errno(errn) <<
\r
369 boost::errinfo_file_name(filename_));
\r
372 audio_input_buffer_ = std::vector<short, tbb::cache_aligned_allocator<short>>(audio_input_buffer_.begin() + frame_bytes/2, audio_input_buffer_.end());
\r
374 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
\r
375 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);
\r
376 pkt.flags |= AV_PKT_FLAG_KEY;
\r
377 pkt.stream_index = audio_st_->index;
\r
378 pkt.data = audio_outbuf_.data();
\r
380 if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)
\r
381 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing audio frame"));
\r
386 void send(const safe_ptr<const core::read_frame>& frame)
\r
389 active_ = executor_.begin_invoke([=]
\r
391 auto my_frame = frame;
\r
392 encode_video_frame(my_frame);
\r
393 encode_audio_frame(my_frame);
\r
397 size_t buffer_depth() const { return 1; }
\r
400 ffmpeg_consumer::ffmpeg_consumer(const std::wstring& filename) : impl_(new implementation(narrow(filename))){}
\r
401 ffmpeg_consumer::ffmpeg_consumer(ffmpeg_consumer&& other) : impl_(std::move(other.impl_)){}
\r
402 void ffmpeg_consumer::send(const safe_ptr<const core::read_frame>& frame){impl_->send(frame);}
\r
403 size_t ffmpeg_consumer::buffer_depth() const{return impl_->buffer_depth();}
\r
404 void ffmpeg_consumer::initialize(const core::video_format_desc& format_desc, const printer& parent_printer)
\r
406 impl_.reset(new implementation(impl_->filename_));
\r
407 impl_->initialize(format_desc, parent_printer);
\r
409 std::wstring ffmpeg_consumer::print() const {return impl_->print();}
\r
411 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const std::vector<std::wstring>& params)
\r
413 if(params.size() < 2 || params[0] != L"FILE")
\r
414 return core::frame_consumer::empty();
\r
416 // TODO: Ask stakeholders about case where file already exists.
\r
417 boost::filesystem::remove(boost::filesystem::wpath(env::media_folder() + params[1])); // Delete the file if it exists
\r
418 return make_safe<ffmpeg_consumer>(env::media_folder() + params[1]);
\r