]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/consumer/ffmpeg_consumer.cpp
2.0. ffmpeg: Header file optimization and fixes.
[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/mixer/read_frame.h>\r
26 #include <core/consumer/frame_consumer.h>\r
27 #include <core/video_format.h>\r
28 \r
29 #include <common/concurrency/executor.h>\r
30 #include <common/utility/string.h>\r
31 #include <common/env.h>\r
32 \r
33 #include <boost/thread/once.hpp>\r
34 \r
35 #include <tbb/cache_aligned_allocator.h>\r
36 #include <tbb/parallel_invoke.h>\r
37 \r
38 #include <cstdio>\r
39 \r
40 #if defined(_MSC_VER)\r
41 #pragma warning (push)\r
42 #pragma warning (disable : 4244)\r
43 #endif\r
44 extern "C" \r
45 {\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
50 }\r
51 #if defined(_MSC_VER)\r
52 #pragma warning (pop)\r
53 #endif\r
54 \r
55 namespace caspar { \r
56         \r
57 struct ffmpeg_consumer : boost::noncopyable\r
58 {               \r
59         const std::string                                               filename_;\r
60         const size_t                                                    bitrate_;\r
61                 \r
62         const std::shared_ptr<AVFormatContext>  oc_;\r
63         const core::video_format_desc                   format_desc_;\r
64         \r
65         executor                                                                executor_;\r
66 \r
67         // Audio\r
68         std::shared_ptr<AVStream>                               audio_st_;\r
69         std::vector<uint8_t>                                    audio_outbuf_;\r
70 \r
71         std::vector<int16_t>                                    audio_input_buffer_;\r
72 \r
73         // Video\r
74         std::shared_ptr<AVStream>                               video_st_;\r
75         std::vector<uint8_t>                                    video_outbuf_;\r
76 \r
77         std::vector<uint8_t>                                    picture_buf_;\r
78         std::shared_ptr<SwsContext>                             img_convert_ctx_;\r
79         \r
80 public:\r
81         ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, size_t bitrate)\r
82                 : filename_(filename)\r
83                 , bitrate_(bitrate)\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
89         {\r
90                 if (!oc_)\r
91                 {\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
95                 }\r
96 \r
97                 executor_.set_capacity(core::consumer_buffer_depth());\r
98 \r
99                 oc_->oformat = av_guess_format(nullptr, filename_.c_str(), nullptr);\r
100                 if (!oc_->oformat)\r
101                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format."));\r
102                 \r
103                 std::copy_n(filename_.c_str(), filename_.size(), oc_->filename);\r
104                                         \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
108                 \r
109                 //if (oc_->oformat->audio_codec != CODEC_ID_NONE) \r
110                 //      audio_st_ = add_audio_stream(oc_->oformat->audio_codec);        \r
111 \r
112                 // Set the output parameters (must be done even if no parameters).              \r
113                 int errn = av_set_parameters(oc_.get(), nullptr);\r
114                 if (errn < 0)\r
115                 {\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
122                 }\r
123                 \r
124                 dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
125 \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
128                 if (video_st_)\r
129                         open_video(video_st_);\r
130                 \r
131                 try\r
132                 {\r
133                         if (audio_st_)\r
134                                 open_audio(audio_st_);\r
135                 }\r
136                 catch(...)\r
137                 {\r
138                         CASPAR_LOG_CURRENT_EXCEPTION();\r
139                         audio_st_ = nullptr;\r
140                 }\r
141  \r
142                 // Open the output ffmpeg, if needed.\r
143                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
144                 {\r
145                         int errn = url_fopen(&oc_->pb, filename_.c_str(), URL_WRONLY);\r
146                         if (errn < 0) \r
147                         {\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
154                         }\r
155                 }\r
156                 \r
157                 av_write_header(oc_.get()); // write the stream header, if any \r
158 \r
159                 CASPAR_LOG(info) << print() << L" Successfully initialized.";   \r
160         }\r
161 \r
162         ~ffmpeg_consumer()\r
163         {    \r
164                 executor_.stop();\r
165                 executor_.join();\r
166 \r
167                 audio_st_.reset();\r
168                 video_st_.reset();\r
169 \r
170                 av_write_trailer(oc_.get());\r
171                 \r
172                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
173                         url_fclose(oc_->pb); // Close the output ffmpeg.\r
174         }\r
175 \r
176         const core::video_format_desc& get_video_format_desc() const\r
177         {\r
178                 return format_desc_;\r
179         }\r
180                 \r
181         std::wstring print() const\r
182         {\r
183                 return L"ffmpeg[" + widen(filename_) + L"]";\r
184         }\r
185 \r
186         std::shared_ptr<AVStream> add_video_stream(enum CodecID codec_id)\r
187         { \r
188                 auto st = av_new_stream(oc_.get(), 0);\r
189                 if (!st) \r
190                 {\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
194                 }\r
195 \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
204  \r
205                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
206                 {\r
207                         avcodec_close(st->codec);\r
208                         //av_freep(st);\r
209                 });\r
210         }\r
211         \r
212         std::shared_ptr<AVStream> add_audio_stream(enum CodecID codec_id)\r
213         {\r
214                 auto st = av_new_stream(oc_.get(), 1);\r
215                 if (!st) \r
216                 {\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
220                 }\r
221 \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
227                 \r
228                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
229                 {\r
230                         avcodec_close(st->codec);\r
231                         //av_freep(st);\r
232                 });\r
233         }\r
234          \r
235         void open_video(std::shared_ptr<AVStream>& st)\r
236         {  \r
237                 auto codec = avcodec_find_encoder(st->codec->codec_id);\r
238                 if (!codec)\r
239                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
240                 \r
241                 int errn = avcodec_open(st->codec, codec);\r
242                 if (errn < 0)\r
243                 {\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
250                 }\r
251         }\r
252 \r
253         void open_audio(std::shared_ptr<AVStream>& st)\r
254         {\r
255                 auto codec = avcodec_find_encoder(st->codec->codec_id);\r
256                 if (!codec) \r
257                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
258                 \r
259                 int errn = avcodec_open(st->codec, codec);\r
260                 if (errn < 0)\r
261                 {\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
268                 }\r
269         }\r
270   \r
271         void encode_video_frame(const safe_ptr<core::read_frame>& frame)\r
272         { \r
273                 if(!video_st_)\r
274                         return;\r
275 \r
276                 AVCodecContext* c = video_st_->codec;\r
277  \r
278                 if(!img_convert_ctx_) \r
279                 {\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
283                 }\r
284 \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
287                                 \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
291 \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
293                                 \r
294                 int errn = avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), local_av_frame.get());\r
295                 if (errn < 0) \r
296                 {\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
303                 }\r
304 \r
305                 AVPacket pkt;\r
306                 av_init_packet(&pkt);\r
307                 pkt.size = errn;\r
308 \r
309                 // If zero size, it means the image was buffered.\r
310                 if (errn > 0) \r
311                 { \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
314                         \r
315                         if(c->coded_frame->key_frame)\r
316                                 pkt.flags |= AV_PKT_FLAG_KEY;\r
317 \r
318                         pkt.stream_index = video_st_->index;\r
319                         pkt.data             = video_outbuf_.data();\r
320 \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
323                 }               \r
324         }\r
325                 \r
326         void encode_audio_frame(const safe_ptr<core::read_frame>& frame)\r
327         {       \r
328                 if(!audio_st_)\r
329                         return;\r
330 \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
333                 else\r
334                         audio_input_buffer_.insert(audio_input_buffer_.end(), 3840, 0);\r
335 \r
336                 while(encode_audio_packet()){}\r
337         }\r
338 \r
339         bool encode_audio_packet()\r
340         {               \r
341                 auto c = audio_st_->codec;\r
342 \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
345                         return false;\r
346 \r
347                 AVPacket pkt;\r
348                 av_init_packet(&pkt);\r
349                 \r
350                 int errn = avcodec_encode_audio(c, audio_outbuf_.data(), audio_outbuf_.size(), audio_input_buffer_.data());\r
351                 if (errn < 0) \r
352                 {\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
359                 }\r
360 \r
361                 pkt.size = errn;\r
362                 audio_input_buffer_ = std::vector<int16_t>(audio_input_buffer_.begin() + frame_bytes/2, audio_input_buffer_.end());\r
363 \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
366 \r
367                 pkt.flags                |= AV_PKT_FLAG_KEY;\r
368                 pkt.stream_index = audio_st_->index;\r
369                 pkt.data                 = audio_outbuf_.data();\r
370                 \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
373 \r
374                 return true;\r
375         }\r
376          \r
377         void send(const safe_ptr<core::read_frame>& frame)\r
378         {\r
379                 executor_.begin_invoke([=]\r
380                 {                               \r
381                         encode_video_frame(frame);\r
382                         encode_audio_frame(frame);\r
383                 });\r
384         }\r
385 \r
386         size_t buffer_depth() const { return 1; }\r
387 };\r
388 \r
389 struct ffmpeg_consumer_proxy : public core::frame_consumer\r
390 {\r
391         const std::wstring filename_;\r
392         const bool key_only_;\r
393         const size_t bitrate_;\r
394 \r
395         std::unique_ptr<ffmpeg_consumer> consumer_;\r
396 \r
397 public:\r
398 \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
403         \r
404         virtual void initialize(const core::video_format_desc& format_desc)\r
405         {\r
406                 consumer_.reset(new ffmpeg_consumer(narrow(filename_), format_desc, bitrate_));\r
407         }\r
408         \r
409         virtual void send(const safe_ptr<core::read_frame>& frame)\r
410         {\r
411                 consumer_->send(frame);\r
412         }\r
413         \r
414         virtual std::wstring print() const\r
415         {\r
416                 return consumer_->print();\r
417         }\r
418 \r
419         virtual bool key_only() const\r
420         {\r
421                 return key_only_;\r
422         }\r
423         \r
424         virtual bool has_synchronization_clock() const \r
425         {\r
426                 return false;\r
427         }\r
428 \r
429         virtual const core::video_format_desc& get_video_format_desc() const\r
430         {\r
431                 return consumer_->get_video_format_desc();\r
432         }\r
433 };      \r
434 \r
435 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const std::vector<std::wstring>& params)\r
436 {\r
437         if(params.size() < 2 || params[0] != L"FILE")\r
438                 return core::frame_consumer::empty();\r
439         \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
443 \r
444         return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + params[1], key_only, 100000000);\r
445 }\r
446 \r
447 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const boost::property_tree::ptree& ptree)\r
448 {\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
452         \r
453         return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + widen(filename), key_only, bitrate);\r
454 }\r
455 \r
456 }\r