]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/consumer/ffmpeg_consumer.cpp
2.1.0: Send ffmpeg_consumer frame-number through OSC.
[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 "../producer/tbb_avcodec.h"\r
29 \r
30 #include <core/frame/frame.h>\r
31 #include <core/mixer/audio/audio_util.h>\r
32 #include <core/consumer/frame_consumer.h>\r
33 #include <core/video_format.h>\r
34 \r
35 #include <common/array.h>\r
36 #include <common/env.h>\r
37 #include <common/except.h>\r
38 #include <common/executor.h>\r
39 #include <common/diagnostics/graph.h>\r
40 #include <common/lock.h>\r
41 #include <common/memory.h>\r
42 #include <common/param.h>\r
43 #include <common/utf.h>\r
44 \r
45 #include <boost/algorithm/string.hpp>\r
46 #include <boost/timer.hpp>\r
47 #include <boost/property_tree/ptree.hpp>\r
48 #include <boost/filesystem.hpp>\r
49 #include <boost/range/algorithm.hpp>\r
50 #include <boost/range/algorithm_ext.hpp>\r
51 #include <boost/lexical_cast.hpp>\r
52 \r
53 #include <tbb/spin_mutex.h>\r
54 \r
55 #if defined(_MSC_VER)\r
56 #pragma warning (push)\r
57 #pragma warning (disable : 4244)\r
58 #endif\r
59 extern "C" \r
60 {\r
61         #define __STDC_CONSTANT_MACROS\r
62         #define __STDC_LIMIT_MACROS\r
63         #include <libavformat/avformat.h>\r
64         #include <libswscale/swscale.h>\r
65         #include <libavutil/opt.h>\r
66         #include <libavutil/pixdesc.h>\r
67         #include <libavutil/parseutils.h>\r
68         #include <libavutil/samplefmt.h>\r
69         #include <libswresample/swresample.h>\r
70 }\r
71 #if defined(_MSC_VER)\r
72 #pragma warning (pop)\r
73 #endif\r
74 \r
75 namespace caspar { namespace ffmpeg {\r
76         \r
77 int av_opt_set(void *obj, const char *name, const char *val, int search_flags)\r
78 {\r
79         AVClass* av_class = *(AVClass**)obj;\r
80 \r
81         if((strcmp(name, "pix_fmt") == 0 || strcmp(name, "pixel_format") == 0) && strcmp(av_class->class_name, "AVCodecContext") == 0)\r
82         {\r
83                 AVCodecContext* c = (AVCodecContext*)obj;               \r
84                 auto pix_fmt = av_get_pix_fmt(val);\r
85                 if(pix_fmt == PIX_FMT_NONE)\r
86                         return -1;              \r
87                 c->pix_fmt = pix_fmt;\r
88                 return 0;\r
89         }\r
90         //if((strcmp(name, "r") == 0 || strcmp(name, "frame_rate") == 0) && strcmp(av_class->class_name, "AVCodecContext") == 0)\r
91         //{\r
92         //      AVCodecContext* c = (AVCodecContext*)obj;       \r
93 \r
94         //      if(c->codec_type != AVMEDIA_TYPE_VIDEO)\r
95         //              return -1;\r
96 \r
97         //      AVRational rate;\r
98         //      int ret = av_parse_video_rate(&rate, val);\r
99         //      if(ret < 0)\r
100         //              return ret;\r
101 \r
102         //      c->time_base.num = rate.den;\r
103         //      c->time_base.den = rate.num;\r
104         //      return 0;\r
105         //}\r
106 \r
107         return ::av_opt_set(obj, name, val, search_flags);\r
108 }\r
109 \r
110 struct option\r
111 {\r
112         std::string name;\r
113         std::string value;\r
114 \r
115         option(std::string name, std::string value)\r
116                 : name(std::move(name))\r
117                 , value(std::move(value))\r
118         {\r
119         }\r
120 };\r
121         \r
122 struct output_format\r
123 {\r
124         AVOutputFormat* format;\r
125         int                             width;\r
126         int                             height;\r
127         CodecID                 vcodec;\r
128         CodecID                 acodec;\r
129         int                             croptop;\r
130         int                             cropbot;\r
131 \r
132         output_format(const core::video_format_desc& format_desc, const std::string& filename, std::vector<option>& options)\r
133                 : format(av_guess_format(nullptr, filename.c_str(), nullptr))\r
134                 , width(format_desc.width)\r
135                 , height(format_desc.height)\r
136                 , vcodec(CODEC_ID_NONE)\r
137                 , acodec(CODEC_ID_NONE)\r
138                 , croptop(0)\r
139                 , cropbot(0)\r
140         {\r
141                 boost::range::remove_erase_if(options, [&](const option& o)\r
142                 {\r
143                         return set_opt(o.name, o.value);\r
144                 });\r
145                 \r
146                 if(vcodec == CODEC_ID_NONE)\r
147                         vcodec = format->video_codec;\r
148 \r
149                 if(acodec == CODEC_ID_NONE)\r
150                         acodec = format->audio_codec;\r
151                 \r
152                 if(vcodec == CODEC_ID_NONE)\r
153                         vcodec = CODEC_ID_H264;\r
154                 \r
155                 if(acodec == CODEC_ID_NONE)\r
156                         acodec = CODEC_ID_PCM_S16LE;\r
157         }\r
158         \r
159         bool set_opt(const std::string& name, const std::string& value)\r
160         {\r
161                 //if(name == "target")\r
162                 //{ \r
163                 //      enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;\r
164                 //      \r
165                 //      if(name.find("pal-") != std::string::npos)\r
166                 //              norm = PAL;\r
167                 //      else if(name.find("ntsc-") != std::string::npos)\r
168                 //              norm = NTSC;\r
169 \r
170                 //      if(norm == UNKNOWN)\r
171                 //              CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("target"));\r
172                 //      \r
173                 //      if (name.find("-dv") != std::string::npos) \r
174                 //      {\r
175                 //              set_opt("f", "dv");\r
176                 //              set_opt("s", norm == PAL ? "720x576" : "720x480");\r
177                 //              //set_opt("pix_fmt", name.find("-dv50") != std::string::npos ? "yuv422p" : norm == PAL ? "yuv420p" : "yuv411p");\r
178                 //              //set_opt("ar", "48000");\r
179                 //              //set_opt("ac", "2");\r
180                 //      } \r
181                 //}\r
182                 if(name == "f")\r
183                 {\r
184                         format = av_guess_format(value.c_str(), nullptr, nullptr);\r
185 \r
186                         if(format == nullptr)\r
187                                 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("f"));\r
188 \r
189                         return true;\r
190                 }\r
191                 else if(name == "vcodec")\r
192                 {\r
193                         auto c = avcodec_find_encoder_by_name(value.c_str());\r
194                         if(c == nullptr)\r
195                                 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("vcodec"));\r
196 \r
197                         vcodec = avcodec_find_encoder_by_name(value.c_str())->id;\r
198                         return true;\r
199 \r
200                 }\r
201                 else if(name == "acodec")\r
202                 {\r
203                         auto c = avcodec_find_encoder_by_name(value.c_str());\r
204                         if(c == nullptr)\r
205                                 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("acodec"));\r
206 \r
207                         acodec = avcodec_find_encoder_by_name(value.c_str())->id;\r
208 \r
209                         return true;\r
210                 }\r
211                 else if(name == "s")\r
212                 {\r
213                         if(av_parse_video_size(&width, &height, value.c_str()) < 0)\r
214                                 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("s"));\r
215                         \r
216                         return true;\r
217                 }\r
218                 else if(name == "croptop")\r
219                 {\r
220                         croptop = boost::lexical_cast<int>(value);\r
221 \r
222                         return true;\r
223                 }\r
224                 else if(name == "cropbot")\r
225                 {\r
226                         cropbot = boost::lexical_cast<int>(value);\r
227 \r
228                         return true;\r
229                 }\r
230                 \r
231                 return false;\r
232         }\r
233 };\r
234 \r
235 typedef std::vector<uint8_t, tbb::cache_aligned_allocator<uint8_t>>     byte_vector;\r
236 \r
237 struct ffmpeg_consumer : boost::noncopyable\r
238 {               \r
239         const spl::shared_ptr<diagnostics::graph>       graph_;\r
240         const std::string                                                       filename_;              \r
241         const std::shared_ptr<AVFormatContext>          oc_;\r
242         const core::video_format_desc                           format_desc_;   \r
243 \r
244         monitor::basic_subject                                          event_subject_;\r
245         \r
246         tbb::spin_mutex                                                         exception_mutex_;\r
247         std::exception_ptr                                                      exception_;\r
248         \r
249         std::shared_ptr<AVStream>                                       audio_st_;\r
250         std::shared_ptr<AVStream>                                       video_st_;\r
251         \r
252         byte_vector                                                                     picture_buffer_;\r
253         byte_vector                                                                     audio_buffer_;\r
254         std::shared_ptr<SwrContext>                                     swr_;\r
255         std::shared_ptr<SwsContext>                                     sws_;\r
256 \r
257         int64_t                                                                         frame_number_;\r
258 \r
259         output_format                                                           output_format_;\r
260         \r
261         executor                                                                        executor_;\r
262 public:\r
263         ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, std::vector<option> options)\r
264                 : filename_(filename)\r
265                 , oc_(avformat_alloc_context(), av_free)\r
266                 , format_desc_(format_desc)\r
267                 , frame_number_(0)\r
268                 , output_format_(format_desc, filename, options)\r
269                 , executor_(print())\r
270         {\r
271                 check_space();\r
272 \r
273                 // TODO: Ask stakeholders about case where file already exists.\r
274                 boost::filesystem::remove(boost::filesystem::path(env::media_folder() + u16(filename))); // Delete the file if it exists\r
275 \r
276                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
277                 graph_->set_text(print());\r
278                 diagnostics::register_graph(graph_);\r
279 \r
280                 executor_.set_capacity(8);\r
281 \r
282                 oc_->oformat = output_format_.format;\r
283                                 \r
284                 strcpy_s(oc_->filename, filename_.c_str());\r
285                 \r
286                 //  Add the audio and video streams using the default format codecs     and initialize the codecs.\r
287                 video_st_ = add_video_stream(options);\r
288                 audio_st_ = add_audio_stream(options);\r
289                                 \r
290                 av_dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
291                  \r
292                 // Open the output ffmpeg, if needed.\r
293                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
294                         THROW_ON_ERROR2(avio_open(&oc_->pb, filename.c_str(), AVIO_FLAG_WRITE), "[ffmpeg_consumer]");\r
295                                 \r
296                 THROW_ON_ERROR2(avformat_write_header(oc_.get(), nullptr), "[ffmpeg_consumer]");\r
297 \r
298                 if(options.size() > 0)\r
299                 {\r
300                         BOOST_FOREACH(auto& option, options)\r
301                                 CASPAR_LOG(warning) << L"Invalid option: -" << u16(option.name) << L" " << u16(option.value);\r
302                 }\r
303 \r
304                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";   \r
305         }\r
306 \r
307         ~ffmpeg_consumer()\r
308         {    \r
309                 executor_.wait();\r
310                 \r
311                 LOG_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");\r
312                 \r
313                 audio_st_.reset();\r
314                 video_st_.reset();\r
315                           \r
316                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
317                         LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]");\r
318 \r
319                 CASPAR_LOG(info) << print() << L" Successfully Uninitialized."; \r
320         }\r
321         \r
322         // frame_consumer\r
323 \r
324         bool send(core::const_frame& frame)\r
325         {\r
326                 auto exception = lock(exception_mutex_, [&]\r
327                 {\r
328                         return exception_;\r
329                 });\r
330 \r
331                 if(exception != nullptr)\r
332                         std::rethrow_exception(exception);\r
333                         \r
334                 executor_.begin_invoke([=]\r
335                 {               \r
336                         encode(frame);\r
337                 });\r
338                 \r
339                 return true;\r
340         }\r
341 \r
342         std::wstring print() const\r
343         {\r
344                 return L"ffmpeg[" + u16(filename_) + L"]";\r
345         }\r
346         \r
347         void subscribe(const monitor::observable::observer_ptr& o)\r
348         {\r
349                 event_subject_.subscribe(o);\r
350         }\r
351 \r
352         void unsubscribe(const monitor::observable::observer_ptr& o)\r
353         {\r
354                 event_subject_.unsubscribe(o);\r
355         }               \r
356 \r
357 private:\r
358         std::shared_ptr<AVStream> add_video_stream(std::vector<option>& options)\r
359         { \r
360                 if(output_format_.vcodec == CODEC_ID_NONE)\r
361                         return nullptr;\r
362 \r
363                 auto st = av_new_stream(oc_.get(), 0);\r
364                 if (!st)                \r
365                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("av_new_stream"));             \r
366 \r
367                 auto encoder = avcodec_find_encoder(output_format_.vcodec);\r
368                 if (!encoder)\r
369                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Codec not found."));\r
370 \r
371                 auto c = st->codec;\r
372 \r
373                 avcodec_get_context_defaults3(c, encoder);\r
374                                 \r
375                 c->codec_id                     = output_format_.vcodec;\r
376                 c->codec_type           = AVMEDIA_TYPE_VIDEO;\r
377                 c->width                        = output_format_.width;\r
378                 c->height                       = output_format_.height - output_format_.croptop - output_format_.cropbot;\r
379                 c->time_base.den        = format_desc_.time_scale;\r
380                 c->time_base.num        = format_desc_.duration;\r
381                 c->gop_size                     = 25;\r
382                 c->flags                   |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);\r
383                 c->pix_fmt                      = c->pix_fmt != PIX_FMT_NONE ? c->pix_fmt : PIX_FMT_YUV420P;\r
384 \r
385                 if(c->codec_id == CODEC_ID_PRORES)\r
386                 {                       \r
387                         c->bit_rate     = c->width < 1280 ? 63*1000000 : 220*1000000;\r
388                         c->pix_fmt      = PIX_FMT_YUV422P10;\r
389                 }\r
390                 else if(c->codec_id == CODEC_ID_DNXHD)\r
391                 {\r
392                         if(c->width < 1280 || c->height < 720)\r
393                                 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Unsupported video dimensions."));\r
394 \r
395                         c->bit_rate     = 220*1000000;\r
396                         c->pix_fmt      = PIX_FMT_YUV422P;\r
397                 }\r
398                 else if(c->codec_id == CODEC_ID_DVVIDEO)\r
399                 {\r
400                         c->width = c->height == 1280 ? 960  : c->width;\r
401                         \r
402                         if(format_desc_.format == core::video_format::ntsc)\r
403                                 c->pix_fmt = PIX_FMT_YUV411P;\r
404                         else if(format_desc_.format == core::video_format::pal)\r
405                                 c->pix_fmt = PIX_FMT_YUV420P;\r
406                         else // dv50\r
407                                 c->pix_fmt = PIX_FMT_YUV422P;\r
408                         \r
409                         if(format_desc_.duration == 1001)                       \r
410                                 c->width = c->height == 1080 ? 1280 : c->width;                 \r
411                         else\r
412                                 c->width = c->height == 1080 ? 1440 : c->width;                 \r
413                 }\r
414                 else if(c->codec_id == CODEC_ID_H264)\r
415                 {                          \r
416                         c->pix_fmt = PIX_FMT_YUV420P;    \r
417                         av_opt_set(c->priv_data, "preset", "ultrafast", 0);\r
418                         av_opt_set(c->priv_data, "tune",   "fastdecode",   0);\r
419                         av_opt_set(c->priv_data, "crf",    "5",     0);\r
420                 }\r
421                 else if(c->codec_id == CODEC_ID_QTRLE)\r
422                 {\r
423                         c->pix_fmt = PIX_FMT_ARGB;\r
424                 }\r
425                                                                 \r
426                 boost::range::remove_erase_if(options, [&](const option& o)\r
427                 {\r
428                         return o.name.at(0) != 'a' && ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;\r
429                 });\r
430                                 \r
431                 if(output_format_.format->flags & AVFMT_GLOBALHEADER)\r
432                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
433                 \r
434                 THROW_ON_ERROR2(tbb_avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
435 \r
436                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
437                 {\r
438                         LOG_ON_ERROR2(tbb_avcodec_close(st->codec), "[ffmpeg_consumer]");\r
439                         av_freep(&st->codec);\r
440                         av_freep(&st);\r
441                 });\r
442         }\r
443                 \r
444         std::shared_ptr<AVStream> add_audio_stream(std::vector<option>& options)\r
445         {\r
446                 if(output_format_.acodec == CODEC_ID_NONE)\r
447                         return nullptr;\r
448 \r
449                 auto st = av_new_stream(oc_.get(), 1);\r
450                 if(!st)\r
451                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate audio-stream") << boost::errinfo_api_function("av_new_stream"));              \r
452                 \r
453                 auto encoder = avcodec_find_encoder(output_format_.acodec);\r
454                 if (!encoder)\r
455                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
456                 \r
457                 auto c = st->codec;\r
458 \r
459                 avcodec_get_context_defaults3(c, encoder);\r
460 \r
461                 c->codec_id                     = output_format_.acodec;\r
462                 c->codec_type           = AVMEDIA_TYPE_AUDIO;\r
463                 c->sample_rate          = 48000;\r
464                 c->channels                     = 2;\r
465                 c->sample_fmt           = AV_SAMPLE_FMT_S16;\r
466                 c->time_base.num        = 1;\r
467                 c->time_base.den        = c->sample_rate;\r
468 \r
469                 if(output_format_.vcodec == CODEC_ID_FLV1)              \r
470                         c->sample_rate  = 44100;                \r
471 \r
472                 if(output_format_.format->flags & AVFMT_GLOBALHEADER)\r
473                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
474                                 \r
475                 boost::range::remove_erase_if(options, [&](const option& o)\r
476                 {\r
477                         return ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;\r
478                 });\r
479 \r
480                 THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
481 \r
482                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
483                 {\r
484                         LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");;\r
485                         av_freep(&st->codec);\r
486                         av_freep(&st);\r
487                 });\r
488         }\r
489   \r
490         void encode_video_frame(core::const_frame frame)\r
491         { \r
492                 if(!video_st_)\r
493                         return;\r
494                 \r
495                 auto enc = video_st_->codec;\r
496          \r
497                 auto av_frame                           = convert_video(frame, enc);\r
498                 av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
499                 av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper;\r
500                 av_frame->pts                           = frame_number_++;\r
501 \r
502                 event_subject_ << monitor::event("frame")       % static_cast<int64_t>(frame_number_)\r
503                                                                                                         % static_cast<int64_t>(std::numeric_limits<int64_t>::max());\r
504 \r
505                 AVPacket pkt;\r
506                 av_init_packet(&pkt);\r
507                 pkt.data = nullptr;\r
508                 pkt.size = 0;\r
509 \r
510                 int got_packet = 0;\r
511                 THROW_ON_ERROR2(avcodec_encode_video2(enc, &pkt, av_frame.get(), &got_packet), "[ffmpeg_consumer]");\r
512                 std::shared_ptr<AVPacket> guard(&pkt, av_free_packet);\r
513 \r
514                 if(!got_packet)\r
515                         return;\r
516                  \r
517                 if (pkt.pts != AV_NOPTS_VALUE)\r
518                         pkt.pts = av_rescale_q(pkt.pts, enc->time_base, video_st_->time_base);\r
519                 if (pkt.dts != AV_NOPTS_VALUE)\r
520                         pkt.dts = av_rescale_q(pkt.dts, enc->time_base, video_st_->time_base);\r
521                  \r
522                 pkt.stream_index = video_st_->index;\r
523                         \r
524                 THROW_ON_ERROR2(av_interleaved_write_frame(oc_.get(), &pkt), "[ffmpeg_consumer]");\r
525         }\r
526                 \r
527         uint64_t get_channel_layout(AVCodecContext* dec)\r
528         {\r
529                 auto layout = (dec->channel_layout && dec->channels == av_get_channel_layout_nb_channels(dec->channel_layout)) ? dec->channel_layout : av_get_default_channel_layout(dec->channels);\r
530                 return layout;\r
531         }\r
532                 \r
533         void encode_audio_frame(core::const_frame frame)\r
534         {               \r
535                 if(!audio_st_)\r
536                         return;\r
537                 \r
538                 auto enc = audio_st_->codec;\r
539 \r
540                 boost::push_back(audio_buffer_, convert_audio(frame, enc));\r
541                         \r
542                 auto frame_size = enc->frame_size != 0 ? enc->frame_size * enc->channels * av_get_bytes_per_sample(enc->sample_fmt) : static_cast<int>(audio_buffer_.size());\r
543                         \r
544                 while(audio_buffer_.size() >= frame_size)\r
545                 {                       \r
546                         std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);\r
547                         avcodec_get_frame_defaults(av_frame.get());             \r
548                         av_frame->nb_samples = frame_size / (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));\r
549 \r
550                         AVPacket pkt;\r
551                         av_init_packet(&pkt);\r
552                         pkt.data = nullptr;\r
553                         pkt.size = 0;                           \r
554                         \r
555                         THROW_ON_ERROR2(avcodec_fill_audio_frame(av_frame.get(), enc->channels, enc->sample_fmt, audio_buffer_.data(), frame_size, 1), "[ffmpeg_consumer]");\r
556 \r
557                         int got_packet = 0;\r
558                         THROW_ON_ERROR2(avcodec_encode_audio2(enc, &pkt, av_frame.get(), &got_packet), "[ffmpeg_consumer]");\r
559                         std::shared_ptr<AVPacket> guard(&pkt, av_free_packet);\r
560                                 \r
561                         audio_buffer_.erase(audio_buffer_.begin(), audio_buffer_.begin() + frame_size);\r
562 \r
563                         if(!got_packet)\r
564                                 return;\r
565                 \r
566                         if (pkt.pts != AV_NOPTS_VALUE)\r
567                                 pkt.pts      = av_rescale_q(pkt.pts, enc->time_base, audio_st_->time_base);\r
568                         if (pkt.dts != AV_NOPTS_VALUE)\r
569                                 pkt.dts      = av_rescale_q(pkt.dts, enc->time_base, audio_st_->time_base);\r
570                         if (pkt.duration > 0)\r
571                                 pkt.duration = static_cast<int>(av_rescale_q(pkt.duration, enc->time_base, audio_st_->time_base));\r
572                 \r
573                         pkt.stream_index = audio_st_->index;\r
574                                                 \r
575                         THROW_ON_ERROR2(av_interleaved_write_frame(oc_.get(), &pkt), "[ffmpeg_consumer]");\r
576                 }\r
577         }                \r
578         \r
579         std::shared_ptr<AVFrame> convert_video(core::const_frame frame, AVCodecContext* c)\r
580         {\r
581                 if(!sws_) \r
582                 {\r
583                         sws_.reset(sws_getContext(format_desc_.width, \r
584                                                                           format_desc_.height - output_format_.croptop  - output_format_.cropbot, \r
585                                                                           PIX_FMT_BGRA,\r
586                                                                           c->width,\r
587                                                                           c->height, \r
588                                                                           c->pix_fmt, \r
589                                                                           SWS_BICUBIC, nullptr, nullptr, nullptr), \r
590                                                 sws_freeContext);\r
591                         if (sws_ == nullptr) \r
592                                 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));\r
593                 }\r
594 \r
595                 std::shared_ptr<AVFrame> in_frame(avcodec_alloc_frame(), av_free);\r
596 \r
597                 avpicture_fill(reinterpret_cast<AVPicture*>(in_frame.get()), \r
598                                            const_cast<uint8_t*>(frame.image_data().begin()),\r
599                                            PIX_FMT_BGRA, \r
600                                            format_desc_.width,\r
601                                            format_desc_.height - output_format_.croptop  - output_format_.cropbot);\r
602 \r
603                 for(int n = 0; n < 4; ++n)              \r
604                         in_frame->data[n] += in_frame->linesize[n] * output_format_.croptop;            \r
605                                         \r
606                 picture_buffer_.resize(avpicture_get_size(c->pix_fmt, c->width, c->height));\r
607 \r
608                 std::shared_ptr<AVFrame> out_frame(avcodec_alloc_frame(), av_free);\r
609                 \r
610                 avpicture_fill(reinterpret_cast<AVPicture*>(out_frame.get()),\r
611                                            picture_buffer_.data(), \r
612                                            c->pix_fmt, \r
613                                            c->width, \r
614                                            c->height);\r
615 \r
616                 sws_scale(sws_.get(), \r
617                                   in_frame->data, \r
618                                   in_frame->linesize,\r
619                                   0, \r
620                                   format_desc_.height - output_format_.cropbot - output_format_.croptop, \r
621                                   out_frame->data, \r
622                                   out_frame->linesize);\r
623 \r
624                 return out_frame;\r
625         }\r
626         \r
627         byte_vector convert_audio(core::const_frame& frame, AVCodecContext* c)\r
628         {\r
629                 if(!swr_) \r
630                 {\r
631                         swr_ = std::shared_ptr<SwrContext>(swr_alloc_set_opts(nullptr,\r
632                                                                                 get_channel_layout(c), c->sample_fmt, c->sample_rate,\r
633                                                                                 av_get_default_channel_layout(format_desc_.audio_channels), AV_SAMPLE_FMT_S32, format_desc_.audio_sample_rate,\r
634                                                                                 0, nullptr), [](SwrContext* p){swr_free(&p);});\r
635 \r
636                         if(!swr_)\r
637                                 CASPAR_THROW_EXCEPTION(bad_alloc());\r
638 \r
639                         THROW_ON_ERROR2(swr_init(swr_.get()), "[audio_decoder]");\r
640                 }\r
641                                 \r
642                 byte_vector buffer(48000);\r
643 \r
644                 const uint8_t* in[]  = {reinterpret_cast<const uint8_t*>(frame.audio_data().data())};\r
645                 uint8_t*       out[] = {buffer.data()};\r
646 \r
647                 auto channel_samples = swr_convert(swr_.get(), \r
648                                                                                    out, static_cast<int>(buffer.size()) / c->channels / av_get_bytes_per_sample(c->sample_fmt), \r
649                                                                                    in, static_cast<int>(frame.audio_data().size()/format_desc_.audio_channels));\r
650 \r
651                 buffer.resize(channel_samples * c->channels * av_get_bytes_per_sample(c->sample_fmt));  \r
652 \r
653                 return buffer;\r
654         }\r
655 \r
656         void check_space()\r
657         {\r
658                 auto space = boost::filesystem::space(boost::filesystem::path(filename_).parent_path());\r
659                 if(space.available < 512*1000000)\r
660                         BOOST_THROW_EXCEPTION(file_write_error() << msg_info("out of space"));\r
661         }\r
662 \r
663         void encode(const core::const_frame& frame)\r
664         {\r
665                 try\r
666                 {\r
667                         if(frame_number_ % 25 == 0)\r
668                                 check_space();\r
669 \r
670                         boost::timer frame_timer;\r
671 \r
672                         encode_video_frame(frame);\r
673                         encode_audio_frame(frame);\r
674 \r
675                         graph_->set_value("frame-time", frame_timer.elapsed()*format_desc_.fps*0.5);\r
676                 }\r
677                 catch(...)\r
678                 {                       \r
679                         lock(exception_mutex_, [&]\r
680                         {\r
681                                 exception_ = std::current_exception();\r
682                         });\r
683                 }\r
684         }\r
685 };\r
686 \r
687 struct ffmpeg_consumer_proxy : public core::frame_consumer\r
688 {\r
689         const std::wstring                              filename_;\r
690         const std::vector<option>               options_;\r
691 \r
692         std::unique_ptr<ffmpeg_consumer> consumer_;\r
693 \r
694 public:\r
695 \r
696         ffmpeg_consumer_proxy(const std::wstring& filename, const std::vector<option>& options)\r
697                 : filename_(filename)\r
698                 , options_(options)\r
699         {\r
700         }\r
701         \r
702         virtual void initialize(const core::video_format_desc& format_desc, int)\r
703         {\r
704                 if(consumer_)\r
705                         BOOST_THROW_EXCEPTION(invalid_operation() << msg_info("Cannot reinitialize ffmpeg-consumer."));\r
706 \r
707                 consumer_.reset(new ffmpeg_consumer(u8(filename_), format_desc, options_));\r
708         }\r
709         \r
710         bool send(core::const_frame frame) override\r
711         {\r
712                 return consumer_->send(frame);\r
713         }\r
714         \r
715         std::wstring print() const override\r
716         {\r
717                 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";\r
718         }\r
719 \r
720         std::wstring name() const override\r
721         {\r
722                 return L"file";\r
723         }\r
724 \r
725         boost::property_tree::wptree info() const override\r
726         {\r
727                 boost::property_tree::wptree info;\r
728                 info.add(L"type", L"file");\r
729                 info.add(L"filename", filename_);\r
730                 return info;\r
731         }\r
732                 \r
733         bool has_synchronization_clock() const override\r
734         {\r
735                 return false;\r
736         }\r
737 \r
738         int buffer_depth() const override\r
739         {\r
740                 return 1;\r
741         }\r
742 \r
743         int index() const override\r
744         {\r
745                 return 200;\r
746         }\r
747 \r
748         void subscribe(const monitor::observable::observer_ptr& o) override\r
749         {\r
750                 consumer_->subscribe(o);\r
751         }\r
752 \r
753         void unsubscribe(const monitor::observable::observer_ptr& o) override\r
754         {\r
755                 consumer_->unsubscribe(o);\r
756         }               \r
757 };      \r
758 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)\r
759 {\r
760         if(params.size() < 1 || params[0] != L"FILE")\r
761                 return core::frame_consumer::empty();\r
762         \r
763         auto filename   = (params.size() > 1 ? params[1] : L"");\r
764                         \r
765         std::vector<option> options;\r
766         \r
767         if(params.size() >= 3)\r
768         {\r
769                 for(auto opt_it = params.begin()+2; opt_it != params.end();)\r
770                 {\r
771                         auto name  = u8(boost::trim_copy(boost::to_lower_copy(*opt_it++))).substr(1);\r
772                         auto value = u8(boost::trim_copy(boost::to_lower_copy(*opt_it++)));\r
773                                 \r
774                         if(value == "h264")\r
775                                 value = "libx264";\r
776                         else if(value == "dvcpro")\r
777                                 value = "dvvideo";\r
778 \r
779                         options.push_back(option(name, value));\r
780                 }\r
781         }\r
782                 \r
783         return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);\r
784 }\r
785 \r
786 spl::shared_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree)\r
787 {\r
788         auto filename   = ptree.get<std::wstring>(L"path");\r
789         auto codec              = ptree.get(L"vcodec", L"libx264");\r
790 \r
791         std::vector<option> options;\r
792         options.push_back(option("vcodec", u8(codec)));\r
793         \r
794         return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);\r
795 }\r
796 \r
797 }}\r