]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/consumer/ffmpeg_consumer.cpp
2.0.0.2: Use boost::timer instead of handwritten timer.
[casparcg] / modules / ffmpeg / consumer / ffmpeg_consumer.cpp
1 /*\r
2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 *  This ffmpeg is part of CasparCG.\r
5 *\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
10 *\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
15 \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
18 *\r
19 */\r
20  \r
21 #include "../StdAfx.h"\r
22 \r
23 #include "ffmpeg_consumer.h"\r
24 \r
25 #include <core/consumer/frame/read_frame.h>\r
26 \r
27 #include <common/concurrency/executor.h>\r
28 #include <common/utility/string.h>\r
29 #include <common/env.h>\r
30 \r
31 #include <boost/thread/once.hpp>\r
32 \r
33 #include <tbb/cache_aligned_allocator.h>\r
34 #include <tbb/parallel_invoke.h>\r
35 \r
36 #include <cstdio>\r
37 \r
38 #if defined(_MSC_VER)\r
39 #pragma warning (push)\r
40 #pragma warning (disable : 4244)\r
41 #endif\r
42 extern "C" \r
43 {\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
48 }\r
49 #if defined(_MSC_VER)\r
50 #pragma warning (pop)\r
51 #endif\r
52 \r
53 namespace caspar { \r
54         \r
55 struct ffmpeg_consumer::implementation : boost::noncopyable\r
56 {               \r
57         std::string filename_;\r
58 \r
59         // Audio\r
60         AVStream* audio_st_;\r
61         std::vector<unsigned char, tbb::cache_aligned_allocator<unsigned char>> audio_outbuf_;\r
62 \r
63         // Video\r
64         AVStream* video_st_;\r
65         std::vector<uint8_t, tbb::cache_aligned_allocator<unsigned char>> picture_buf_;\r
66 \r
67         std::vector<unsigned char, tbb::cache_aligned_allocator<unsigned char>> video_outbuf_;\r
68         SwsContext* img_convert_ctx_;\r
69         \r
70         AVOutputFormat* fmt_;\r
71         std::shared_ptr<AVFormatContext> oc_;\r
72         core::video_format_desc format_desc_;\r
73 \r
74         std::vector<short, tbb::cache_aligned_allocator<short>> audio_input_buffer_;\r
75 \r
76         boost::unique_future<void> active_;\r
77 \r
78         executor executor_;\r
79 public:\r
80         implementation(const std::string& filename)\r
81                 : filename_(filename)\r
82                 , audio_st_(nullptr)\r
83                 , video_st_(nullptr)\r
84                 , fmt_(nullptr)\r
85                 , img_convert_ctx_(nullptr)\r
86                 , video_outbuf_(1920*1080*4)\r
87                 , audio_outbuf_(48000)\r
88                 , executor_(L"ffmpeg_consumer")\r
89         {}\r
90 \r
91         ~implementation()\r
92         {    \r
93                 executor_.invoke([]{});\r
94                 executor_.stop();\r
95 \r
96                 av_write_trailer(oc_.get());\r
97 \r
98                 // Close each codec.\r
99                 if (video_st_)          \r
100                         avcodec_close(video_st_->codec);\r
101                 \r
102                 if (audio_st_)\r
103                         avcodec_close(audio_st_->codec);\r
104                                 \r
105                 // Free the streams.\r
106                 for(size_t i = 0; i < oc_->nb_streams; ++i) \r
107                 {\r
108                         av_freep(&oc_->streams[i]->codec);\r
109                         av_freep(&oc_->streams[i]);\r
110                 }\r
111 \r
112                 if (!(fmt_->flags & AVFMT_NOFILE)) \r
113                         url_fclose(oc_->pb); // Close the output ffmpeg.\r
114         }\r
115 \r
116         void initialize(const core::video_format_desc& format_desc)\r
117         {\r
118                 format_desc_ = format_desc;\r
119                 executor_.start();\r
120                 active_ = executor_.begin_invoke([]{});\r
121 \r
122                 fmt_ = av_guess_format(nullptr, filename_.c_str(), nullptr);\r
123                 if (!fmt_) \r
124                 {\r
125                         CASPAR_LOG(warning) << "Could not deduce output format from ffmpeg extension: using MPEG.";\r
126                         fmt_ = av_guess_format("mpeg", nullptr, nullptr);\r
127                         filename_ = filename_ + ".avi"; \r
128                 }\r
129                 if (!fmt_)\r
130                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format"));\r
131                 \r
132                 oc_.reset(avformat_alloc_context(), av_free);\r
133                 if (!oc_)\r
134                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Memory error"));\r
135                 std::copy_n(filename_.c_str(), filename_.size(), oc_->filename);\r
136 \r
137                 oc_->oformat = fmt_;\r
138                 // To avoid mpeg buffer underflow (http://www.mail-archive.com/libav-user@mplayerhq.hu/msg00194.html)\r
139                 oc_->preload = static_cast<int>(0.5*AV_TIME_BASE);\r
140                 oc_->max_delay = static_cast<int>(0.7*AV_TIME_BASE);\r
141                         \r
142                 //  Add the audio and video streams using the default format codecs     and initialize the codecs .\r
143                 if (fmt_->video_codec != CODEC_ID_NONE)         \r
144                         video_st_ = add_video_stream(fmt_->video_codec);\r
145                 \r
146                 if (fmt_->audio_codec != CODEC_ID_NONE) \r
147                         audio_st_ = add_audio_stream(fmt_->audio_codec);        \r
148 \r
149                 // Set the output parameters (must be done even if no parameters).              \r
150                 int errn = 0;\r
151                 if ((errn = -av_set_parameters(oc_.get(), nullptr)) > 0)\r
152                         BOOST_THROW_EXCEPTION(\r
153                                 file_read_error() << \r
154                                 msg_info("Invalid output format parameters") <<\r
155                                 boost::errinfo_api_function("avcodec_open") <<\r
156                                 boost::errinfo_errno(errn) <<\r
157                                 boost::errinfo_file_name(filename_));\r
158                 \r
159                 dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
160 \r
161                 // Now that all the parameters are set, we can open the audio and\r
162                 // video codecs and allocate the necessary encode buffers.\r
163                 if (video_st_)\r
164                         open_video(video_st_);\r
165                 \r
166                 try\r
167                 {\r
168                         if (audio_st_)\r
169                                 open_audio(audio_st_);\r
170                 }\r
171                 catch(...)\r
172                 {\r
173                         CASPAR_LOG_CURRENT_EXCEPTION();\r
174                         audio_st_ = nullptr;\r
175                 }\r
176  \r
177                 // Open the output ffmpeg, if needed.\r
178                 if (!(fmt_->flags & AVFMT_NOFILE)) \r
179                 {\r
180                         int errn = 0;\r
181                         if ((errn = -url_fopen(&oc_->pb, filename_.c_str(), URL_WRONLY)) > 0) \r
182                                 BOOST_THROW_EXCEPTION(\r
183                                         file_not_found() << \r
184                                         msg_info("Could not open file") <<\r
185                                         boost::errinfo_api_function("url_fopen") <<\r
186                                         boost::errinfo_errno(errn) <<\r
187                                         boost::errinfo_file_name(filename_));\r
188                 }\r
189                 \r
190                 av_write_header(oc_.get()); // write the stream header, if any \r
191 \r
192                 CASPAR_LOG(info) << print() << L" Successfully initialized.";\r
193         }\r
194         \r
195         std::wstring print() const\r
196         {\r
197                 return L"ffmpeg[" + widen(filename_) + L"]";\r
198         }\r
199 \r
200         AVStream* add_video_stream(enum CodecID codec_id)\r
201         { \r
202                 auto st = av_new_stream(oc_.get(), 0);\r
203                 if (!st) \r
204                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not alloc stream"));\r
205  \r
206                 auto c = st->codec;\r
207                 c->codec_id = codec_id;\r
208                 c->codec_type = AVMEDIA_TYPE_VIDEO;\r
209  \r
210                 // Put sample parameters.\r
211                 c->bit_rate = static_cast<int>(static_cast<double>(format_desc_.size)*format_desc_.fps*0.1326);\r
212                 c->width = format_desc_.width;\r
213                 c->height = format_desc_.height;\r
214                 c->time_base.den = static_cast<int>(format_desc_.fps);\r
215                 c->time_base.num = 1;\r
216                 c->pix_fmt = c->pix_fmt == -1 ? PIX_FMT_YUV420P : c->pix_fmt;\r
217 \r
218                 // Some formats want stream headers to be separate.\r
219                 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)\r
220                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
221  \r
222                 return st;\r
223         }\r
224          \r
225         void open_video(AVStream* st)\r
226         { \r
227                 auto c = st->codec;\r
228  \r
229                 auto codec = avcodec_find_encoder(c->codec_id);\r
230                 if (!codec)\r
231                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
232                 \r
233                 int errn = 0;\r
234                 if ((errn = -avcodec_open(c, codec)) > 0)\r
235                         BOOST_THROW_EXCEPTION(\r
236                                 file_read_error() << \r
237                                 msg_info("Could not open video codec.") <<\r
238                                 boost::errinfo_api_function("avcodec_open") <<\r
239                                 boost::errinfo_errno(errn) <<\r
240                                 boost::errinfo_file_name(filename_));            \r
241         }\r
242   \r
243         void encode_video_frame(const safe_ptr<const core::read_frame>& frame)\r
244         { \r
245                 AVCodecContext* c = video_st_->codec;\r
246  \r
247                 if (img_convert_ctx_ == nullptr) \r
248                 {\r
249                         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
250                         if (img_convert_ctx_ == nullptr) \r
251                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));\r
252                 }\r
253 \r
254                 std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);\r
255                 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
256                                 \r
257                 std::shared_ptr<AVFrame> local_av_frame(avcodec_alloc_frame(), av_free);\r
258                 picture_buf_.resize(avpicture_get_size(c->pix_fmt, format_desc_.width, format_desc_.height));\r
259                 avpicture_fill(reinterpret_cast<AVPicture*>(local_av_frame.get()), picture_buf_.data(), c->pix_fmt, format_desc_.width, format_desc_.height);\r
260 \r
261                 sws_scale(img_convert_ctx_, av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);\r
262                                 \r
263                 int ret = avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), local_av_frame.get());\r
264                                 \r
265                 int errn = -ret;\r
266                 if (errn > 0) \r
267                         BOOST_THROW_EXCEPTION(\r
268                                 invalid_operation() << \r
269                                 msg_info("Could not encode video frame.") <<\r
270                                 boost::errinfo_api_function("avcodec_encode_video") <<\r
271                                 boost::errinfo_errno(errn) <<\r
272                                 boost::errinfo_file_name(filename_));\r
273 \r
274                 auto out_size = ret;\r
275                 AVPacket pkt;\r
276                 av_init_packet(&pkt);\r
277                 pkt.size = out_size;\r
278 \r
279                 // If zero size, it means the image was buffered.\r
280                 if (out_size > 0) \r
281                 { \r
282                         if (c->coded_frame->pts != AV_NOPTS_VALUE)\r
283                                 pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);\r
284                         if(c->coded_frame->key_frame)\r
285                                 pkt.flags |= AV_PKT_FLAG_KEY;\r
286 \r
287                         pkt.stream_index = video_st_->index;\r
288                         pkt.data = video_outbuf_.data();\r
289 \r
290                         if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)\r
291                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing video frame"));\r
292                 }               \r
293         }\r
294 \r
295         AVStream* add_audio_stream(enum CodecID codec_id)\r
296         {\r
297                 audio_st_ = av_new_stream(oc_.get(), 1);\r
298                 if (!audio_st_)\r
299                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not alloc stream"));\r
300 \r
301                 auto c = audio_st_->codec;\r
302                 c->codec_id = codec_id;\r
303                 c->codec_type = AVMEDIA_TYPE_AUDIO;\r
304 \r
305                 // Put sample parameters.\r
306                 c->bit_rate = 192000;\r
307                 c->sample_rate = 48000;\r
308                 c->channels = 2;\r
309 \r
310                 // Some formats want stream headers to be separate.\r
311                 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)\r
312                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
313 \r
314                 return audio_st_;\r
315         }\r
316 \r
317         void open_audio(AVStream* st)\r
318         {\r
319                 auto c = st->codec;\r
320 \r
321                 // Find the audio encoder.\r
322                 auto codec = avcodec_find_encoder(c->codec_id);\r
323                 if (!codec) \r
324                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
325                 \r
326                 // Open it.\r
327                 int errn = 0;\r
328                 if ((errn = -avcodec_open(c, codec)) > 0)\r
329                         BOOST_THROW_EXCEPTION(\r
330                                 file_read_error() << \r
331                                 msg_info("Could not open audio codec") <<\r
332                                 boost::errinfo_api_function("avcodec_open") <<\r
333                                 boost::errinfo_errno(errn) <<\r
334                                 boost::errinfo_file_name(filename_));\r
335         }\r
336         \r
337         void encode_audio_frame(const safe_ptr<const core::read_frame>& frame)\r
338         {       \r
339                 if(!frame->audio_data().empty())\r
340                         audio_input_buffer_.insert(audio_input_buffer_.end(), frame->audio_data().begin(), frame->audio_data().end());\r
341                 else\r
342                         audio_input_buffer_.insert(audio_input_buffer_.end(), 3840, 0);\r
343 \r
344                 while(encode_audio_packet()){}\r
345         }\r
346 \r
347         bool encode_audio_packet()\r
348         {                               \r
349                 auto c = audio_st_->codec;\r
350 \r
351                 auto frame_bytes = c->frame_size * 2 * 2; // samples per frame * 2 channels * 2 bytes per sample\r
352                 if(static_cast<int>(audio_input_buffer_.size()) < frame_bytes/2)\r
353                         return false;\r
354 \r
355                 AVPacket pkt;\r
356                 av_init_packet(&pkt);\r
357                 \r
358                 int ret = avcodec_encode_audio(c, audio_outbuf_.data(), audio_outbuf_.size(), audio_input_buffer_.data());\r
359                 \r
360                 int errn = -ret;\r
361                 if (errn > 0) \r
362                         BOOST_THROW_EXCEPTION(\r
363                                 invalid_operation() << \r
364                                 msg_info("Could not encode audio samples.") <<\r
365                                 boost::errinfo_api_function("avcodec_encode_audio") <<\r
366                                 boost::errinfo_errno(errn) <<\r
367                                 boost::errinfo_file_name(filename_));\r
368 \r
369                 pkt.size = ret;\r
370                 audio_input_buffer_ = std::vector<short, tbb::cache_aligned_allocator<short>>(audio_input_buffer_.begin() + frame_bytes/2, audio_input_buffer_.end());\r
371 \r
372                 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)\r
373                         pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);\r
374                 pkt.flags |= AV_PKT_FLAG_KEY;\r
375                 pkt.stream_index = audio_st_->index;\r
376                 pkt.data = audio_outbuf_.data();\r
377                 \r
378                 if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)\r
379                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing audio frame"));\r
380 \r
381                 return true;\r
382         }\r
383          \r
384         void send(const safe_ptr<const core::read_frame>& frame)\r
385         {\r
386                 active_.get();\r
387                 active_ = executor_.begin_invoke([=]\r
388                 {                               \r
389                         auto my_frame = frame;\r
390                         encode_video_frame(my_frame);\r
391                         encode_audio_frame(my_frame);\r
392                 });\r
393         }\r
394 \r
395         size_t buffer_depth() const { return 1; }\r
396 };\r
397 \r
398 ffmpeg_consumer::ffmpeg_consumer(const std::wstring& filename) : impl_(new implementation(narrow(filename))){}\r
399 ffmpeg_consumer::ffmpeg_consumer(ffmpeg_consumer&& other) : impl_(std::move(other.impl_)){}\r
400 void ffmpeg_consumer::send(const safe_ptr<const core::read_frame>& frame){impl_->send(frame);}\r
401 size_t ffmpeg_consumer::buffer_depth() const{return impl_->buffer_depth();}\r
402 void ffmpeg_consumer::initialize(const core::video_format_desc& format_desc)\r
403 {\r
404         // TODO: Ugly\r
405         impl_.reset(new implementation(impl_->filename_));\r
406         impl_->initialize(format_desc);\r
407 }\r
408 std::wstring ffmpeg_consumer::print() const {return impl_->print();}\r
409 \r
410 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const std::vector<std::wstring>& params)\r
411 {\r
412         if(params.size() < 2 || params[0] != L"FILE")\r
413                 return core::frame_consumer::empty();\r
414         \r
415         // TODO: Ask stakeholders about case where file already exists.\r
416         boost::filesystem::remove(boost::filesystem::wpath(env::media_folder() + params[1])); // Delete the file if it exists\r
417         return make_safe<ffmpeg_consumer>(env::media_folder() + params[1]);\r
418 }\r
419 \r
420 }\r