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