]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/consumer/ffmpeg_consumer.cpp
2.0.0.2: ffmpeg_consumer: Misc work.
[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 \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 : boost::noncopyable\r
56 {               \r
57         const std::string                                               filename_;\r
58         const size_t                                                    bitrate_;\r
59                 \r
60         const std::shared_ptr<AVFormatContext>  oc_;\r
61         const core::video_format_desc                   format_desc_;\r
62         \r
63         executor                                                                executor_;\r
64 \r
65         // Audio\r
66         std::shared_ptr<AVStream>                               audio_st_;\r
67         std::vector<uint8_t>                                    audio_outbuf_;\r
68 \r
69         std::vector<int16_t>                                    audio_input_buffer_;\r
70 \r
71         // Video\r
72         std::shared_ptr<AVStream>                               video_st_;\r
73         std::vector<uint8_t>                                    video_outbuf_;\r
74 \r
75         std::vector<uint8_t>                                    picture_buf_;\r
76         std::shared_ptr<SwsContext>                             img_convert_ctx_;\r
77         \r
78 public:\r
79         ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, size_t bitrate)\r
80                 : filename_(filename)\r
81                 , bitrate_(bitrate)\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
87         {\r
88                 if (!oc_)\r
89                 {\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
93                 }\r
94 \r
95                 executor_.set_capacity(CONSUMER_BUFFER_DEPTH);\r
96 \r
97                 oc_->oformat = av_guess_format(nullptr, filename_.c_str(), nullptr);\r
98                 if (!oc_->oformat)\r
99                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format."));\r
100                 \r
101                 std::copy_n(filename_.c_str(), filename_.size(), oc_->filename);\r
102                                         \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
106                 \r
107                 //if (oc_->oformat->audio_codec != CODEC_ID_NONE) \r
108                 //      audio_st_ = add_audio_stream(oc_->oformat->audio_codec);        \r
109 \r
110                 // Set the output parameters (must be done even if no parameters).              \r
111                 int errn = av_set_parameters(oc_.get(), nullptr);\r
112                 if (errn < 0)\r
113                 {\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
120                 }\r
121                 \r
122                 dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
123 \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
126                 if (video_st_)\r
127                         open_video(video_st_);\r
128                 \r
129                 try\r
130                 {\r
131                         if (audio_st_)\r
132                                 open_audio(audio_st_);\r
133                 }\r
134                 catch(...)\r
135                 {\r
136                         CASPAR_LOG_CURRENT_EXCEPTION();\r
137                         audio_st_ = nullptr;\r
138                 }\r
139  \r
140                 // Open the output ffmpeg, if needed.\r
141                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
142                 {\r
143                         int errn = url_fopen(&oc_->pb, filename_.c_str(), URL_WRONLY);\r
144                         if (errn < 0) \r
145                         {\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
152                         }\r
153                 }\r
154                 \r
155                 av_write_header(oc_.get()); // write the stream header, if any \r
156 \r
157                 CASPAR_LOG(info) << print() << L" Successfully initialized.";   \r
158         }\r
159 \r
160         ~ffmpeg_consumer()\r
161         {    \r
162                 executor_.stop();\r
163                 executor_.join();\r
164 \r
165                 audio_st_.reset();\r
166                 video_st_.reset();\r
167 \r
168                 av_write_trailer(oc_.get());\r
169                 \r
170                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
171                         url_fclose(oc_->pb); // Close the output ffmpeg.\r
172         }\r
173 \r
174         const core::video_format_desc& get_video_format_desc() const\r
175         {\r
176                 return format_desc_;\r
177         }\r
178                 \r
179         std::wstring print() const\r
180         {\r
181                 return L"ffmpeg[" + widen(filename_) + L"]";\r
182         }\r
183 \r
184         std::shared_ptr<AVStream> add_video_stream(enum CodecID codec_id)\r
185         { \r
186                 auto st = av_new_stream(oc_.get(), 0);\r
187                 if (!st) \r
188                 {\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
192                 }\r
193 \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
202  \r
203                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
204                 {\r
205                         avcodec_close(st->codec);\r
206                         //av_freep(st);\r
207                 });\r
208         }\r
209         \r
210         std::shared_ptr<AVStream> add_audio_stream(enum CodecID codec_id)\r
211         {\r
212                 auto st = av_new_stream(oc_.get(), 1);\r
213                 if (!st) \r
214                 {\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
218                 }\r
219 \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
225                 \r
226                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
227                 {\r
228                         avcodec_close(st->codec);\r
229                         //av_freep(st);\r
230                 });\r
231         }\r
232          \r
233         void open_video(std::shared_ptr<AVStream>& st)\r
234         {  \r
235                 auto codec = avcodec_find_encoder(st->codec->codec_id);\r
236                 if (!codec)\r
237                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
238                 \r
239                 int errn = avcodec_open(st->codec, codec);\r
240                 if (errn < 0)\r
241                 {\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
248                 }\r
249         }\r
250 \r
251         void open_audio(std::shared_ptr<AVStream>& st)\r
252         {\r
253                 auto codec = avcodec_find_encoder(st->codec->codec_id);\r
254                 if (!codec) \r
255                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
256                 \r
257                 int errn = avcodec_open(st->codec, codec);\r
258                 if (errn < 0)\r
259                 {\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
266                 }\r
267         }\r
268   \r
269         void encode_video_frame(const safe_ptr<const core::read_frame>& frame)\r
270         { \r
271                 if(!video_st_)\r
272                         return;\r
273 \r
274                 AVCodecContext* c = video_st_->codec;\r
275  \r
276                 if(!img_convert_ctx_) \r
277                 {\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
281                 }\r
282 \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
285                                 \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
289 \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
291                                 \r
292                 int errn = avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), local_av_frame.get());\r
293                 if (errn < 0) \r
294                 {\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
301                 }\r
302 \r
303                 AVPacket pkt;\r
304                 av_init_packet(&pkt);\r
305                 pkt.size = errn;\r
306 \r
307                 // If zero size, it means the image was buffered.\r
308                 if (errn > 0) \r
309                 { \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
312                         \r
313                         if(c->coded_frame->key_frame)\r
314                                 pkt.flags |= AV_PKT_FLAG_KEY;\r
315 \r
316                         pkt.stream_index = video_st_->index;\r
317                         pkt.data             = video_outbuf_.data();\r
318 \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
321                 }               \r
322         }\r
323                 \r
324         void encode_audio_frame(const safe_ptr<const core::read_frame>& frame)\r
325         {       \r
326                 if(!audio_st_)\r
327                         return;\r
328 \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
331                 else\r
332                         audio_input_buffer_.insert(audio_input_buffer_.end(), 3840, 0);\r
333 \r
334                 while(encode_audio_packet()){}\r
335         }\r
336 \r
337         bool encode_audio_packet()\r
338         {               \r
339                 auto c = audio_st_->codec;\r
340 \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
343                         return false;\r
344 \r
345                 AVPacket pkt;\r
346                 av_init_packet(&pkt);\r
347                 \r
348                 int errn = avcodec_encode_audio(c, audio_outbuf_.data(), audio_outbuf_.size(), audio_input_buffer_.data());\r
349                 if (errn < 0) \r
350                 {\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
357                 }\r
358 \r
359                 pkt.size = errn;\r
360                 audio_input_buffer_ = std::vector<int16_t>(audio_input_buffer_.begin() + frame_bytes/2, audio_input_buffer_.end());\r
361 \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
364 \r
365                 pkt.flags                |= AV_PKT_FLAG_KEY;\r
366                 pkt.stream_index = audio_st_->index;\r
367                 pkt.data                 = audio_outbuf_.data();\r
368                 \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
371 \r
372                 return true;\r
373         }\r
374          \r
375         void send(const safe_ptr<const core::read_frame>& frame)\r
376         {\r
377                 executor_.begin_invoke([=]\r
378                 {                               \r
379                         encode_video_frame(frame);\r
380                         encode_audio_frame(frame);\r
381                 });\r
382         }\r
383 \r
384         size_t buffer_depth() const { return 1; }\r
385 };\r
386 \r
387 struct ffmpeg_consumer_proxy : public core::frame_consumer\r
388 {\r
389         const std::wstring filename_;\r
390         const bool key_only_;\r
391         const size_t bitrate_;\r
392 \r
393         std::unique_ptr<ffmpeg_consumer> consumer_;\r
394 \r
395 public:\r
396 \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
401         \r
402         virtual void initialize(const core::video_format_desc& format_desc)\r
403         {\r
404                 consumer_.reset(new ffmpeg_consumer(narrow(filename_), format_desc, bitrate_));\r
405         }\r
406         \r
407         virtual void send(const safe_ptr<const core::read_frame>& frame)\r
408         {\r
409                 consumer_->send(frame);\r
410         }\r
411         \r
412         virtual std::wstring print() const\r
413         {\r
414                 return consumer_->print();\r
415         }\r
416 \r
417         virtual bool key_only() const\r
418         {\r
419                 return key_only_;\r
420         }\r
421         \r
422         virtual bool has_synchronization_clock() const \r
423         {\r
424                 return false;\r
425         }\r
426 \r
427         virtual const core::video_format_desc& get_video_format_desc() const\r
428         {\r
429                 return consumer_->get_video_format_desc();\r
430         }\r
431 };      \r
432 \r
433 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const std::vector<std::wstring>& params)\r
434 {\r
435         if(params.size() < 2 || params[0] != L"FILE")\r
436                 return core::frame_consumer::empty();\r
437         \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
441 \r
442         return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + params[1], key_only, 100000000);\r
443 }\r
444 \r
445 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const boost::property_tree::ptree& ptree)\r
446 {\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
450         \r
451         return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + widen(filename), key_only, bitrate);\r
452 }\r
453 \r
454 }\r