]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/consumer/ffmpeg_consumer.cpp
2.0.2: ffmpeg_consumer: Added support for DVCPRO and DNXHD. Added multithreading...
[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_error.h"\r
24 \r
25 #include "ffmpeg_consumer.h"\r
26 \r
27 #include <core/mixer/read_frame.h>\r
28 #include <core/mixer/audio/audio_util.h>\r
29 #include <core/consumer/frame_consumer.h>\r
30 #include <core/video_format.h>\r
31 \r
32 #include <common/concurrency/executor.h>\r
33 #include <common/diagnostics/graph.h>\r
34 #include <common/utility/string.h>\r
35 #include <common/env.h>\r
36 \r
37 #include <boost/timer.hpp>\r
38 #include <boost/thread/once.hpp>\r
39 #include <boost/thread.hpp>\r
40 #include <boost/algorithm/string.hpp>\r
41 \r
42 #include <tbb/cache_aligned_allocator.h>\r
43 #include <tbb/parallel_invoke.h>\r
44 \r
45 #include <cstdio>\r
46 \r
47 #if defined(_MSC_VER)\r
48 #pragma warning (push)\r
49 #pragma warning (disable : 4244)\r
50 #endif\r
51 extern "C" \r
52 {\r
53         #define __STDC_CONSTANT_MACROS\r
54         #define __STDC_LIMIT_MACROS\r
55         #include <libavformat/avformat.h>\r
56         #include <libswscale/swscale.h>\r
57 }\r
58 #if defined(_MSC_VER)\r
59 #pragma warning (pop)\r
60 #endif\r
61 \r
62 namespace caspar { namespace ffmpeg {\r
63         \r
64 struct ffmpeg_consumer : boost::noncopyable\r
65 {               \r
66         const std::string                                               filename_;\r
67                 \r
68         const std::shared_ptr<AVFormatContext>  oc_;\r
69         const core::video_format_desc                   format_desc_;\r
70         \r
71         const safe_ptr<diagnostics::graph>              graph_;\r
72         boost::timer                                                    frame_timer_;\r
73         boost::timer                                                    write_timer_;\r
74 \r
75         executor                                                                executor_;\r
76         executor                                                                file_write_executor_;\r
77 \r
78         // Audio\r
79         std::shared_ptr<AVStream>                               audio_st_;\r
80         std::vector<uint8_t>                                    audio_outbuf_;\r
81 \r
82         std::vector<int16_t>                                    audio_input_buffer_;\r
83 \r
84         // Video\r
85         std::shared_ptr<AVStream>                               video_st_;\r
86         std::vector<uint8_t>                                    video_outbuf_;\r
87 \r
88         std::vector<uint8_t>                                    picture_buf_;\r
89         std::shared_ptr<SwsContext>                             img_convert_ctx_;\r
90         \r
91 public:\r
92         ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, const std::string& codec, int bitrate)\r
93                 : filename_(filename + ".mov")\r
94                 , video_outbuf_(1920*1080*8)\r
95                 , audio_outbuf_(48000)\r
96                 , oc_(avformat_alloc_context(), av_free)\r
97                 , format_desc_(format_desc)\r
98                 , executor_(print())\r
99                 , file_write_executor_(print() + L"/output")\r
100         {\r
101                 graph_->add_guide("frame-time", 0.5);\r
102                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
103                 graph_->set_color("write-time", diagnostics::color(0.5f, 0.5f, 0.1f));\r
104                 graph_->set_text(print());\r
105                 diagnostics::register_graph(graph_);\r
106 \r
107                 executor_.set_capacity(8);\r
108                 file_write_executor_.set_capacity(8);\r
109 \r
110                 oc_->oformat = av_guess_format(nullptr, filename_.c_str(), nullptr);\r
111                 if (!oc_->oformat)\r
112                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format."));\r
113                 \r
114                 THROW_ON_ERROR2(av_set_parameters(oc_.get(), nullptr), "[ffmpeg_consumer]");\r
115 \r
116                 strcpy_s(oc_->filename, filename_.c_str());\r
117                 \r
118                 auto video_codec = avcodec_find_encoder_by_name(codec.c_str());\r
119                 if(video_codec == nullptr)\r
120                         BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info(codec));\r
121 \r
122                 //  Add the audio and video streams using the default format codecs     and initialize the codecs .\r
123                 video_st_ = add_video_stream(video_codec->id, bitrate);\r
124                 audio_st_ = add_audio_stream();\r
125                                 \r
126                 dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
127                  \r
128                 // Open the output ffmpeg, if needed.\r
129                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
130                         THROW_ON_ERROR2(avio_open(&oc_->pb, filename_.c_str(), URL_WRONLY), "[ffmpeg_consumer]");\r
131                                 \r
132                 THROW_ON_ERROR2(av_write_header(oc_.get()), "[ffmpeg_consumer]");\r
133 \r
134                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";   \r
135         }\r
136 \r
137         ~ffmpeg_consumer()\r
138         {    \r
139                 file_write_executor_.stop();\r
140                 file_write_executor_.join();\r
141 \r
142                 executor_.stop();\r
143                 executor_.join();\r
144                 \r
145                 try\r
146                 {\r
147                         THROW_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");\r
148                 \r
149                         audio_st_.reset();\r
150                         video_st_.reset();\r
151                           \r
152                         for(size_t i = 0; i < oc_->nb_streams; i++) \r
153                         {\r
154                                 av_freep(&oc_->streams[i]->codec);\r
155                                 av_freep(&oc_->streams[i]);\r
156                         }\r
157 \r
158                         if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
159                                 THROW_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]"); // Close the output ffmpeg.\r
160 \r
161                         CASPAR_LOG(info) << print() << L" Successfully Uninitialized."; \r
162                 }\r
163                 catch(...)\r
164                 {\r
165                         CASPAR_LOG_CURRENT_EXCEPTION();\r
166                 }\r
167 \r
168         }\r
169                         \r
170         std::wstring print() const\r
171         {\r
172                 return L"ffmpeg[" + widen(filename_) + L"]";\r
173         }\r
174 \r
175         std::shared_ptr<AVStream> add_video_stream(enum CodecID codec_id, int bitrate)\r
176         { \r
177                 auto st = av_new_stream(oc_.get(), 0);\r
178                 if (!st) \r
179                 {\r
180                         BOOST_THROW_EXCEPTION(caspar_exception() \r
181                                 << msg_info("Could not alloc video-stream")                             \r
182                                 << boost::errinfo_api_function("av_new_stream"));\r
183                 }\r
184 \r
185                 bitrate *= 1000000;\r
186                 \r
187                 st->codec->codec_id                     = codec_id;\r
188                 st->codec->bit_rate                     = bitrate > 0 ? bitrate : format_desc_.width < 1280 ? 42*1000000 : 147*1000000;\r
189                 st->codec->codec_type           = AVMEDIA_TYPE_VIDEO;\r
190                 st->codec->width                        = format_desc_.width;\r
191                 st->codec->height                       = format_desc_.height;\r
192                 st->codec->time_base.den        = format_desc_.time_scale;\r
193                 st->codec->time_base.num        = format_desc_.duration;\r
194 \r
195                 if(st->codec->codec_id == CODEC_ID_PRORES)\r
196                 {                       \r
197                         st->codec->bit_rate     = bitrate > 0 ? bitrate : format_desc_.width < 1280 ? 42*1000000 : 147*1000000;\r
198                         st->codec->pix_fmt      = PIX_FMT_YUV422P10;\r
199                 }\r
200                 else if(st->codec->codec_id == CODEC_ID_DNXHD)\r
201                 {\r
202                         if(format_desc_.width < 1280 || format_desc_.height < 720)\r
203                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("unsupported dimension"));\r
204 \r
205                         st->codec->bit_rate     = bitrate > 0 ? bitrate : 145*1000000;\r
206                         st->codec->pix_fmt      = PIX_FMT_YUV422P;\r
207 \r
208                 }\r
209                 else if(st->codec->codec_id == CODEC_ID_DVVIDEO)\r
210                 {\r
211                         st->codec->bit_rate     = bitrate > 0 ? bitrate : format_desc_.width < 1280 ? 50*1000000 : 100*1000000;\r
212                         st->codec->pix_fmt      = PIX_FMT_YUV422P;\r
213                 }\r
214                 //else if(st->codec->codec_id == CODEC_ID_H264)\r
215                 //{                     \r
216                 //      st->codec->pix_fmt              = PIX_FMT_YUV422P;\r
217                 //      st->codec->me_range             = 16;\r
218                 //      st->codec->max_qdiff    = 4;\r
219                 //      st->codec->qmin                 = 10;\r
220                 //      st->codec->qmax                 = 51;\r
221                 //      st->codec->qcompress    = 0.6;\r
222                 //      st->codec->gop_size             = 25;\r
223                 //}\r
224                 else\r
225                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("unsupported codec"));\r
226                 \r
227                 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)\r
228                         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
229 \r
230                 auto codec = avcodec_find_encoder(st->codec->codec_id);\r
231                 if (!codec)\r
232                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
233 \r
234                 st->codec->thread_count = boost::thread::hardware_concurrency();\r
235                 THROW_ON_ERROR2(avcodec_open(st->codec, codec), "[ffmpeg_consumer]");\r
236 \r
237                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
238                 {\r
239                         avcodec_close(st->codec);\r
240                 });\r
241         }\r
242         \r
243         std::shared_ptr<AVStream> add_audio_stream()\r
244         {\r
245                 auto st = av_new_stream(oc_.get(), 1);\r
246                 if (!st) \r
247                 {\r
248                         BOOST_THROW_EXCEPTION(caspar_exception() \r
249                                 << msg_info("Could not alloc audio-stream")                             \r
250                                 << boost::errinfo_api_function("av_new_stream"));\r
251                 }\r
252 \r
253                 st->codec->codec_id                     = CODEC_ID_PCM_S16LE;\r
254                 st->codec->codec_type           = AVMEDIA_TYPE_AUDIO;\r
255                 st->codec->sample_rate          = 48000;\r
256                 st->codec->channels                     = 2;\r
257                 st->codec->sample_fmt           = SAMPLE_FMT_S16;\r
258                 \r
259                 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)\r
260                         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
261                 \r
262                 auto codec = avcodec_find_encoder(st->codec->codec_id);\r
263                 if (!codec)\r
264                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
265 \r
266                 THROW_ON_ERROR2(avcodec_open(st->codec, codec), "[ffmpeg_consumer]");\r
267 \r
268                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
269                 {\r
270                         avcodec_close(st->codec);\r
271                 });\r
272         }\r
273   \r
274         std::shared_ptr<AVPacket> encode_video_frame(const safe_ptr<core::read_frame>& frame)\r
275         { \r
276                 auto 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                 local_av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;\r
290                 local_av_frame->top_field_first  = format_desc_.field_mode == core::field_mode::upper;\r
291 \r
292                 picture_buf_.resize(avpicture_get_size(c->pix_fmt, format_desc_.width, format_desc_.height));\r
293                 avpicture_fill(reinterpret_cast<AVPicture*>(local_av_frame.get()), picture_buf_.data(), c->pix_fmt, format_desc_.width, format_desc_.height);\r
294 \r
295                 sws_scale(img_convert_ctx_.get(), av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);\r
296                                 \r
297                 int out_size = THROW_ON_ERROR2(avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), local_av_frame.get()), "[ffmpeg_consumer]");\r
298                 if(out_size > 0)\r
299                 {\r
300                         safe_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)\r
301                         {\r
302                                 av_free_packet(p);\r
303                                 delete p;\r
304                         });\r
305                         av_init_packet(pkt.get());\r
306  \r
307                         if (c->coded_frame->pts != AV_NOPTS_VALUE)\r
308                                 pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);\r
309 \r
310                         if(c->coded_frame->key_frame)\r
311                                 pkt->flags |= AV_PKT_FLAG_KEY;\r
312 \r
313                         pkt->stream_index       = video_st_->index;\r
314                         pkt->data                       = video_outbuf_.data();\r
315                         pkt->size                       = out_size;\r
316  \r
317                         av_dup_packet(pkt.get());\r
318                         return pkt;\r
319                 }       \r
320                 return nullptr;\r
321         }\r
322                 \r
323         std::shared_ptr<AVPacket> encode_audio_frame(const safe_ptr<core::read_frame>& frame)\r
324         {                       \r
325                 auto c = audio_st_->codec;\r
326 \r
327                 auto audio_data = core::audio_32_to_16(frame->audio_data());\r
328                 \r
329                 safe_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)\r
330                 {\r
331                         av_free_packet(p);\r
332                         delete p;\r
333                 });\r
334                 av_init_packet(pkt.get());\r
335                 \r
336                 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)\r
337                         pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);\r
338 \r
339                 pkt->flags               |= AV_PKT_FLAG_KEY;\r
340                 pkt->stream_index = audio_st_->index;\r
341                 pkt->size                = audio_data.size()*2;\r
342                 pkt->data                = reinterpret_cast<uint8_t*>(audio_data.data());\r
343                 \r
344                 av_dup_packet(pkt.get());\r
345                 return pkt;\r
346         }\r
347                  \r
348         void send(const safe_ptr<core::read_frame>& frame)\r
349         {\r
350                 executor_.begin_invoke([=]\r
351                 {               \r
352                         frame_timer_.restart();\r
353                         auto video = encode_video_frame(frame);\r
354                         auto audio = encode_audio_frame(frame);\r
355                         graph_->update_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
356                         \r
357                         file_write_executor_.begin_invoke([=]\r
358                         {\r
359                                 write_timer_.restart();\r
360                                 if(video)\r
361                                         av_write_frame(oc_.get(), video.get());\r
362                                 if(audio)\r
363                                         av_write_frame(oc_.get(), audio.get());\r
364                                 graph_->update_value("write-time", write_timer_.elapsed()*format_desc_.fps*0.5);\r
365                         });\r
366                 });\r
367         }\r
368 };\r
369 \r
370 struct ffmpeg_consumer_proxy : public core::frame_consumer\r
371 {\r
372         const std::wstring      filename_;\r
373         const bool                      key_only_;\r
374         const std::string       codec_;\r
375         const int                       bitrate_;\r
376 \r
377         std::unique_ptr<ffmpeg_consumer> consumer_;\r
378 \r
379 public:\r
380 \r
381         ffmpeg_consumer_proxy(const std::wstring& filename, bool key_only, const std::string codec, int bitrate)\r
382                 : filename_(filename)\r
383                 , key_only_(key_only)\r
384                 , codec_(boost::to_lower_copy(codec))\r
385                 , bitrate_(bitrate)\r
386         {\r
387         }\r
388         \r
389         virtual void initialize(const core::video_format_desc& format_desc, int, int)\r
390         {\r
391                 consumer_.reset();\r
392                 consumer_.reset(new ffmpeg_consumer(narrow(filename_), format_desc, codec_, bitrate_));\r
393         }\r
394         \r
395         virtual bool send(const safe_ptr<core::read_frame>& frame) override\r
396         {\r
397                 consumer_->send(frame);\r
398                 return true;\r
399         }\r
400         \r
401         virtual std::wstring print() const override\r
402         {\r
403                 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";\r
404         }\r
405                 \r
406         virtual bool has_synchronization_clock() const override\r
407         {\r
408                 return false;\r
409         }\r
410 \r
411         virtual size_t buffer_depth() const override\r
412         {\r
413                 return 1;\r
414         }\r
415 };      \r
416 \r
417 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const std::vector<std::wstring>& params)\r
418 {\r
419         if(params.size() < 2 || params[0] != L"FILE")\r
420                 return core::frame_consumer::empty();\r
421         \r
422         // TODO: Ask stakeholders about case where file already exists.\r
423         boost::filesystem::remove(boost::filesystem::wpath(env::media_folder() + params[1])); // Delete the file if it exists\r
424         bool key_only = std::find(params.begin(), params.end(), L"KEY_ONLY") != params.end();\r
425 \r
426         std::string codec = "dnxhd";\r
427         auto codec_it = std::find(params.begin(), params.end(), L"CODEC");\r
428         if(codec_it != params.end() && codec_it++ != params.end())\r
429                 codec = narrow(*codec_it);\r
430 \r
431         int bitrate = 0;        \r
432         auto bitrate_it = std::find(params.begin(), params.end(), L"BITRATE");\r
433         if(bitrate_it != params.end() && bitrate_it++ != params.end())\r
434                 bitrate = boost::lexical_cast<int>(*bitrate_it);\r
435 \r
436         return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + params[1], key_only, codec, bitrate);\r
437 }\r
438 \r
439 safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const boost::property_tree::ptree& ptree)\r
440 {\r
441         std::string filename = ptree.get<std::string>("path");\r
442         auto key_only            = ptree.get("key-only", false);\r
443         auto codec                       = ptree.get("codec", "dnxhd");\r
444         auto bitrate             = ptree.get("bitrate", 0);\r
445         \r
446         return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + widen(filename), key_only, codec, bitrate);\r
447 }\r
448 \r
449 }}\r