]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/consumer/ffmpeg_consumer.cpp
a38004743f2b71332cb7fcc034848c415b3458f0
[casparcg] / modules / ffmpeg / consumer / ffmpeg_consumer.cpp
1 /*\r
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 * This file is part of CasparCG (www.casparcg.com).\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 * Author: Robert Nagy, ronag89@gmail.com\r
20 */\r
21  \r
22 #include "../StdAfx.h"\r
23 \r
24 #include "../ffmpeg_error.h"\r
25 \r
26 #include "ffmpeg_consumer.h"\r
27 \r
28 #include <core/mixer/read_frame.h>\r
29 #include <core/mixer/audio/audio_util.h>\r
30 #include <core/consumer/frame_consumer.h>\r
31 #include <core/video_format.h>\r
32 \r
33 #include <common/concurrency/executor.h>\r
34 #include <common/diagnostics/graph.h>\r
35 #include <common/env.h>\r
36 #include <common/utility/string.h>\r
37 #include <common/utility/param.h>\r
38 \r
39 #include <boost/algorithm/string.hpp>\r
40 #include <boost/timer.hpp>\r
41 #include <boost/property_tree/ptree.hpp>\r
42 \r
43 #include <tbb/cache_aligned_allocator.h>\r
44 #include <tbb/parallel_invoke.h>\r
45 \r
46 #if defined(_MSC_VER)\r
47 #pragma warning (push)\r
48 #pragma warning (disable : 4244)\r
49 #endif\r
50 extern "C" \r
51 {\r
52         #define __STDC_CONSTANT_MACROS\r
53         #define __STDC_LIMIT_MACROS\r
54         #include <libavformat/avformat.h>\r
55         #include <libswscale/swscale.h>\r
56         #include <libavutil/opt.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::wstring                                              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         \r
81         // Video\r
82         std::shared_ptr<AVStream>                               video_st_;\r
83 \r
84         std::vector<uint8_t>                                    video_outbuf_;\r
85         std::vector<uint8_t>                                    picture_buf_;\r
86         std::shared_ptr<SwsContext>                             sws_;\r
87 \r
88         int64_t                                                                 frame_number_;\r
89         \r
90 public:\r
91         ffmpeg_consumer(const std::wstring& filename, const core::video_format_desc& format_desc, const std::wstring& codec, const std::wstring& options)\r
92                 : filename_(filename)\r
93                 , video_outbuf_(1920*1080*8)\r
94                 , oc_(avformat_alloc_context(), av_free)\r
95                 , format_desc_(format_desc)\r
96                 , executor_(print())\r
97                 , file_write_executor_(print() + L"/output")\r
98                 , frame_number_(0)\r
99         {\r
100                 // TODO: Ask stakeholders about case where file already exists.\r
101                 boost::filesystem::remove(boost::filesystem::path(env::media_folder() + filename)); // Delete the file if it exists\r
102 \r
103                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
104                 graph_->set_color("write-time", diagnostics::color(0.5f, 0.5f, 0.1f));\r
105                 graph_->set_text(print());\r
106                 diagnostics::register_graph(graph_);\r
107 \r
108                 executor_.set_capacity(8);\r
109                 file_write_executor_.set_capacity(8);\r
110 \r
111                 oc_->oformat = av_guess_format(nullptr, u8(filename_).c_str(), nullptr);\r
112                 if (!oc_->oformat)\r
113                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format."));\r
114                 \r
115                 THROW_ON_ERROR2(av_set_parameters(oc_.get(), nullptr), "[ffmpeg_consumer]");\r
116 \r
117                 strcpy_s(oc_->filename, u8(filename_).c_str());\r
118                 \r
119                 auto video_codec = avcodec_find_encoder_by_name(u8(codec).c_str());\r
120                 if(video_codec == nullptr)\r
121                         BOOST_THROW_EXCEPTION(invalid_argument() << warg_name_info(codec));\r
122 \r
123                 //  Add the audio and video streams using the default format codecs     and initialize the codecs .\r
124                 video_st_ = add_video_stream(video_codec->id, u8(options));\r
125                 audio_st_ = add_audio_stream();\r
126                                 \r
127                 dump_format(oc_.get(), 0, u8(filename_).c_str(), 1);\r
128                  \r
129                 // Open the output ffmpeg, if needed.\r
130                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
131                         THROW_ON_ERROR2(avio_open(&oc_->pb, u8(filename_).c_str(), URL_WRONLY), "[ffmpeg_consumer]");\r
132                                 \r
133                 THROW_ON_ERROR2(av_write_header(oc_.get()), "[ffmpeg_consumer]");\r
134 \r
135                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";   \r
136         }\r
137 \r
138         ~ffmpeg_consumer()\r
139         {    \r
140                 executor_.wait();\r
141                 executor_.stop();\r
142                 executor_.join();\r
143 \r
144                 file_write_executor_.wait();\r
145                 file_write_executor_.stop();\r
146                 file_write_executor_.join();\r
147                 \r
148                 LOG_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");\r
149                 \r
150                 audio_st_.reset();\r
151                 video_st_.reset();\r
152                           \r
153                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
154                         LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]"); // Close the output ffmpeg.\r
155 \r
156                 CASPAR_LOG(info) << print() << L" Successfully Uninitialized."; \r
157         }\r
158                         \r
159         std::wstring print() const\r
160         {\r
161                 return L"ffmpeg[" + filename_ + L"]";\r
162         }\r
163 \r
164         std::shared_ptr<AVStream> add_video_stream(enum CodecID codec_id, const std::string& options)\r
165         { \r
166                 auto st = av_new_stream(oc_.get(), 0);\r
167                 if (!st)                \r
168                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream") << boost::errinfo_api_function("av_new_stream"));               \r
169 \r
170                 auto encoder = avcodec_find_encoder(codec_id);\r
171                 if (!encoder)\r
172                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
173 \r
174                 auto c = st->codec;\r
175 \r
176                 avcodec_get_context_defaults3(c, encoder);\r
177                                 \r
178                 c->codec_id                     = codec_id;\r
179                 c->codec_type           = AVMEDIA_TYPE_VIDEO;\r
180                 c->width                        = format_desc_.width;\r
181                 c->height                       = format_desc_.height;\r
182                 c->time_base.den        = format_desc_.time_scale;\r
183                 c->time_base.num        = format_desc_.duration;\r
184                 c->gop_size                     = 25;\r
185                 c->flags                   |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);\r
186 \r
187                 if(c->codec_id == CODEC_ID_PRORES)\r
188                 {                       \r
189                         c->bit_rate     = format_desc_.width < 1280 ? 63*1000000 : 220*1000000;\r
190                         c->pix_fmt      = PIX_FMT_YUV422P10;\r
191                         THROW_ON_ERROR2(av_set_options_string(c->priv_data, options.c_str(), "=", ":"), "[ffmpeg_consumer]");\r
192                 }\r
193                 else if(c->codec_id == CODEC_ID_DNXHD)\r
194                 {\r
195                         if(format_desc_.width < 1280 || format_desc_.height < 720)\r
196                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("unsupported dimension"));\r
197 \r
198                         c->bit_rate     = 220*1000000;\r
199                         c->pix_fmt      = PIX_FMT_YUV422P;\r
200                         \r
201                         THROW_ON_ERROR2(av_set_options_string(c->priv_data, options.c_str(), "=", ":"), "[ffmpeg_consumer]");\r
202                 }\r
203                 else if(c->codec_id == CODEC_ID_DVVIDEO)\r
204                 {\r
205                         c->bit_rate     = format_desc_.width < 1280 ? 50*1000000 : 100*1000000;\r
206                         c->pix_fmt      = PIX_FMT_YUV422P;\r
207                         \r
208                         c->width = format_desc_.height == 1280 ? 960  : c->width;\r
209 \r
210                         if(format_desc_.duration == 1001)                       \r
211                                 c->width = format_desc_.height == 1080 ? 1280 : c->width;                       \r
212                         else\r
213                                 c->width = format_desc_.height == 1080 ? 1440 : c->width;\r
214                         \r
215                         THROW_ON_ERROR2(av_set_options_string(c->priv_data, options.c_str(), "=", ":"), "[ffmpeg_consumer]");\r
216                 }\r
217                 else if(c->codec_id == CODEC_ID_H264)\r
218                 {                          \r
219                         c->pix_fmt = PIX_FMT_YUV420P;    \r
220                         if(options.empty())\r
221                         {\r
222                                 av_opt_set(c->priv_data, "preset", "ultrafast", 0);\r
223                                 av_opt_set(c->priv_data, "tune",   "fastdecode",   0);\r
224                                 av_opt_set(c->priv_data, "crf",    "5",     0);\r
225                         }\r
226 \r
227                         THROW_ON_ERROR2(av_set_options_string(c->priv_data, options.c_str(), "=", ":"), "[ffmpeg_consumer]");\r
228                 }\r
229                 else\r
230                 {\r
231                         THROW_ON_ERROR2(av_set_options_string(c->priv_data, options.c_str(), "=", ":"), "[ffmpeg_consumer]");\r
232                         CASPAR_LOG(warning) << " Potentially unsupported output parameters.";\r
233                 }\r
234                 \r
235                 c->max_b_frames = 0; // b-franes not supported.\r
236 \r
237                 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)\r
238                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
239                 \r
240                 c->thread_count = boost::thread::hardware_concurrency();\r
241                 THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
242 \r
243                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
244                 {\r
245                         LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");\r
246                         av_freep(&st->codec);\r
247                         av_freep(&st);\r
248                 });\r
249         }\r
250         \r
251         std::shared_ptr<AVStream> add_audio_stream()\r
252         {\r
253                 auto st = av_new_stream(oc_.get(), 1);\r
254                 if(!st)\r
255                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate audio-stream") << boost::errinfo_api_function("av_new_stream"));               \r
256 \r
257                 st->codec->codec_id                     = CODEC_ID_PCM_S16LE;\r
258                 st->codec->codec_type           = AVMEDIA_TYPE_AUDIO;\r
259                 st->codec->sample_rate          = 48000;\r
260                 st->codec->channels                     = 2;\r
261                 st->codec->sample_fmt           = SAMPLE_FMT_S16;\r
262                 \r
263                 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)\r
264                         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
265                 \r
266                 auto codec = avcodec_find_encoder(st->codec->codec_id);\r
267                 if (!codec)\r
268                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
269 \r
270                 THROW_ON_ERROR2(avcodec_open(st->codec, codec), "[ffmpeg_consumer]");\r
271 \r
272                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
273                 {\r
274                         LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");;\r
275                         av_freep(&st->codec);\r
276                         av_freep(&st);\r
277                 });\r
278         }\r
279 \r
280         std::shared_ptr<AVFrame> convert_video_frame(const safe_ptr<core::read_frame>& frame, AVCodecContext* c)\r
281         {\r
282                 if(!sws_) \r
283                 {\r
284                         sws_.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
285                         if (sws_ == nullptr) \r
286                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));\r
287                 }\r
288 \r
289                 std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);\r
290                 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
291                                 \r
292                 std::shared_ptr<AVFrame> local_av_frame(avcodec_alloc_frame(), av_free);\r
293                 picture_buf_.resize(avpicture_get_size(c->pix_fmt, format_desc_.width, format_desc_.height));\r
294                 avpicture_fill(reinterpret_cast<AVPicture*>(local_av_frame.get()), picture_buf_.data(), c->pix_fmt, format_desc_.width, format_desc_.height);\r
295 \r
296                 sws_scale(sws_.get(), av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);\r
297 \r
298                 return local_av_frame;\r
299         }\r
300   \r
301         std::shared_ptr<AVPacket> encode_video_frame(const safe_ptr<core::read_frame>& frame)\r
302         { \r
303                 auto c = video_st_->codec;\r
304  \r
305                 auto av_frame = convert_video_frame(frame, c);\r
306                 av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
307                 av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper;\r
308                 av_frame->pts                           = frame_number_++;\r
309                 \r
310                 int out_size = THROW_ON_ERROR2(avcodec_encode_video(c, video_outbuf_.data(), static_cast<int>(video_outbuf_.size()), av_frame.get()), "[ffmpeg_consumer]");\r
311                 if(out_size > 0)\r
312                 {\r
313                         safe_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)\r
314                         {\r
315                                 av_free_packet(p);\r
316                                 delete p;\r
317                         });\r
318                         av_init_packet(pkt.get());\r
319  \r
320                         if (c->coded_frame->pts != AV_NOPTS_VALUE)\r
321                                 pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);\r
322 \r
323                         if(c->coded_frame->key_frame)\r
324                                 pkt->flags |= AV_PKT_FLAG_KEY;\r
325 \r
326                         pkt->stream_index       = video_st_->index;\r
327                         pkt->data                       = video_outbuf_.data();\r
328                         pkt->size                       = out_size;\r
329  \r
330                         av_dup_packet(pkt.get());\r
331                         return pkt;\r
332                 }       \r
333                 return nullptr;\r
334         }\r
335                 \r
336         std::shared_ptr<AVPacket> encode_audio_frame(const safe_ptr<core::read_frame>& frame)\r
337         {                       \r
338                 auto c = audio_st_->codec;\r
339 \r
340                 auto audio_data = core::audio_32_to_16(frame->audio_data());\r
341                 \r
342                 safe_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)\r
343                 {\r
344                         av_free_packet(p);\r
345                         delete p;\r
346                 });\r
347                 av_init_packet(pkt.get());\r
348                 \r
349                 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)\r
350                         pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);\r
351 \r
352                 pkt->flags               |= AV_PKT_FLAG_KEY;\r
353                 pkt->stream_index = audio_st_->index;\r
354                 pkt->size                = static_cast<int>(audio_data.size()*2);\r
355                 pkt->data                = reinterpret_cast<uint8_t*>(audio_data.data());\r
356                 \r
357                 av_dup_packet(pkt.get());\r
358                 return pkt;\r
359         }\r
360                  \r
361         void send(const safe_ptr<core::read_frame>& frame)\r
362         {\r
363                 executor_.begin_invoke([=]\r
364                 {               \r
365                         frame_timer_.restart();\r
366 \r
367                         auto video = encode_video_frame(frame);\r
368                         auto audio = encode_audio_frame(frame);\r
369 \r
370                         graph_->set_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
371                         \r
372                         file_write_executor_.begin_invoke([=]\r
373                         {\r
374                                 write_timer_.restart();\r
375 \r
376                                 if(video)\r
377                                         av_write_frame(oc_.get(), video.get());\r
378                                 if(audio)\r
379                                         av_write_frame(oc_.get(), audio.get());\r
380 \r
381                                 graph_->set_value("write-time", write_timer_.elapsed()*format_desc_.fps*0.5);\r
382                         });\r
383                 });\r
384         }\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 std::wstring      codec_;\r
392         const std::wstring      options_;\r
393 \r
394         std::unique_ptr<ffmpeg_consumer> consumer_;\r
395 \r
396 public:\r
397 \r
398         ffmpeg_consumer_proxy(const std::wstring& filename, bool key_only, const std::wstring codec, const std::wstring& options)\r
399                 : filename_(filename)\r
400                 , key_only_(key_only)\r
401                 , codec_(boost::to_lower_copy(codec))\r
402                 , options_(options)\r
403         {\r
404         }\r
405         \r
406         virtual void initialize(const core::video_format_desc& format_desc, int)\r
407         {\r
408                 consumer_.reset();\r
409                 consumer_.reset(new ffmpeg_consumer(filename_, format_desc, codec_, options_));\r
410         }\r
411         \r
412         virtual bool send(const safe_ptr<core::read_frame>& frame) override\r
413         {\r
414                 consumer_->send(frame);\r
415                 return true;\r
416         }\r
417         \r
418         virtual std::wstring print() const override\r
419         {\r
420                 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";\r
421         }\r
422 \r
423         virtual boost::property_tree::wptree info() const override\r
424         {\r
425                 boost::property_tree::wptree info;\r
426                 info.add(L"type", L"ffmpeg-consumer");\r
427                 info.add(L"key-only", key_only_);\r
428                 info.add(L"filename", filename_);\r
429                 info.add(L"codec", codec_);\r
430                 info.add(L"options", options_);\r
431                 return info;\r
432         }\r
433                 \r
434         virtual bool has_synchronization_clock() const override\r
435         {\r
436                 return false;\r
437         }\r
438 \r
439         virtual int buffer_depth() const override\r
440         {\r
441                 return 1;\r
442         }\r
443 \r
444         virtual int index() const override\r
445         {\r
446                 return 200;\r
447         }\r
448 };      \r
449 \r
450 safe_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)\r
451 {\r
452         if(params.size() < 1 || params[0] != L"FILE")\r
453                 return core::frame_consumer::empty();\r
454         \r
455         auto filename   = (params.size() > 1 ? params[1] : L"");\r
456         bool key_only   = get_param(L"KEY_ONLY", params, false);\r
457         auto codec              = get_param(L"CODEC", params, L"libx264");\r
458         auto options    = get_param(L"OPTIONS", params);\r
459         \r
460         if(codec == L"H264")\r
461                 codec = L"libx264";\r
462 \r
463         if(codec == L"DVCPRO")\r
464                 codec = L"dvvideo";\r
465 \r
466         boost::to_lower(options);\r
467 \r
468         return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + filename, key_only, codec, options);\r
469 }\r
470 \r
471 safe_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree)\r
472 {\r
473         auto filename   = ptree.get<std::wstring>(L"path");\r
474         auto key_only   = ptree.get(L"key-only", false);\r
475         auto codec              = ptree.get(L"codec", L"libx264");\r
476         auto options    = ptree.get(L"options", L"");\r
477         \r
478         return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + filename, key_only, codec, options);\r
479 }\r
480 \r
481 }}\r