]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/consumer/ffmpeg_consumer.cpp
2ddaa3bbfe8484c2ab6de7662c23265ea72bf903
[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/audio/audio_resampler.h"\r
29 \r
30 #include <core/mixer/read_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/concurrency/executor.h>\r
36 #include <common/concurrency/future_util.h>\r
37 #include <common/diagnostics/graph.h>\r
38 #include <common/env.h>\r
39 #include <common/utility/string.h>\r
40 #include <common/utility/param.h>\r
41 \r
42 #include <boost/algorithm/string.hpp>\r
43 #include <boost/timer.hpp>\r
44 #include <boost/property_tree/ptree.hpp>\r
45 \r
46 #include <tbb/cache_aligned_allocator.h>\r
47 #include <tbb/parallel_invoke.h>\r
48 \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 <string>\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 }\r
69 #if defined(_MSC_VER)\r
70 #pragma warning (pop)\r
71 #endif\r
72 \r
73 namespace caspar { namespace ffmpeg {\r
74         \r
75 int av_opt_set(void *obj, const char *name, const char *val, int search_flags)\r
76 {\r
77         AVClass* av_class = *(AVClass**)obj;\r
78 \r
79         if((strcmp(name, "pix_fmt") == 0 || strcmp(name, "pixel_format") == 0) && strcmp(av_class->class_name, "AVCodecContext") == 0)\r
80         {\r
81                 AVCodecContext* c = (AVCodecContext*)obj;               \r
82                 auto pix_fmt = av_get_pix_fmt(val);\r
83                 if(pix_fmt == PIX_FMT_NONE)\r
84                         return -1;              \r
85                 c->pix_fmt = pix_fmt;\r
86                 return 0;\r
87         }\r
88         if((strcmp(name, "r") == 0 || strcmp(name, "frame_rate") == 0) && strcmp(av_class->class_name, "AVCodecContext") == 0)\r
89         {\r
90                 AVCodecContext* c = (AVCodecContext*)obj;       \r
91 \r
92                 if(c->codec_type != AVMEDIA_TYPE_VIDEO)\r
93                         return -1;\r
94 \r
95                 AVRational rate;\r
96                 int ret = av_parse_video_rate(&rate, val);\r
97                 if(ret < 0)\r
98                         return ret;\r
99 \r
100                 c->time_base.num = rate.den;\r
101                 c->time_base.den = rate.num;\r
102                 return 0;\r
103         }\r
104 \r
105         return ::av_opt_set(obj, name, val, search_flags);\r
106 }\r
107 \r
108 struct option\r
109 {\r
110         std::string name;\r
111         std::string value;\r
112 \r
113         option(std::string name, std::string value)\r
114                 : name(std::move(name))\r
115                 , value(std::move(value))\r
116         {\r
117         }\r
118 };\r
119         \r
120 struct output_format\r
121 {\r
122         AVOutputFormat* format;\r
123         int                             width;\r
124         int                             height;\r
125         CodecID                 vcodec;\r
126         CodecID                 acodec;\r
127 \r
128         output_format(const core::video_format_desc& format_desc, const std::string& filename, std::vector<option>& options)\r
129                 : format(av_guess_format(nullptr, filename.c_str(), nullptr))\r
130                 , width(format_desc.width)\r
131                 , height(format_desc.height)\r
132                 , vcodec(CODEC_ID_NONE)\r
133                 , acodec(CODEC_ID_NONE)\r
134         {\r
135                 boost::range::remove_erase_if(options, [&](const option& o)\r
136                 {\r
137                         return set_opt(o.name, o.value);\r
138                 });\r
139                 \r
140                 if(vcodec == CODEC_ID_NONE)\r
141                         vcodec = format->video_codec;\r
142 \r
143                 if(acodec == CODEC_ID_NONE)\r
144                         acodec = format->audio_codec;\r
145                 \r
146                 if(vcodec == CODEC_ID_NONE)\r
147                         vcodec = CODEC_ID_H264;\r
148                 \r
149                 if(acodec == CODEC_ID_NONE)\r
150                         acodec = CODEC_ID_PCM_S16LE;\r
151         }\r
152         \r
153         bool set_opt(const std::string& name, const std::string& value)\r
154         {\r
155                 //if(name == "target")\r
156                 //{ \r
157                 //      enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;\r
158                 //      \r
159                 //      if(name.find("pal-") != std::string::npos)\r
160                 //              norm = PAL;\r
161                 //      else if(name.find("ntsc-") != std::string::npos)\r
162                 //              norm = NTSC;\r
163 \r
164                 //      if(norm == UNKNOWN)\r
165                 //              BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("target"));\r
166                 //      \r
167                 //      if (name.find("-dv") != std::string::npos) \r
168                 //      {\r
169                 //              set_opt("f", "dv");\r
170                 //              set_opt("s", norm == PAL ? "720x576" : "720x480");\r
171                 //              //set_opt("pix_fmt", name.find("-dv50") != std::string::npos ? "yuv422p" : norm == PAL ? "yuv420p" : "yuv411p");\r
172                 //              //set_opt("ar", "48000");\r
173                 //              //set_opt("ac", "2");\r
174                 //      } \r
175                 //}\r
176                 if(name == "f")\r
177                 {\r
178                         format = av_guess_format(value.c_str(), nullptr, nullptr);\r
179 \r
180                         if(format == nullptr)\r
181                                 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("f"));\r
182 \r
183                         return true;\r
184                 }\r
185                 else if(name == "vcodec")\r
186                 {\r
187                         auto c = avcodec_find_encoder_by_name(value.c_str());\r
188                         if(c == nullptr)\r
189                                 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("vcodec"));\r
190 \r
191                         vcodec = avcodec_find_encoder_by_name(value.c_str())->id;\r
192                         return true;\r
193 \r
194                 }\r
195                 else if(name == "acodec")\r
196                 {\r
197                         auto c = avcodec_find_encoder_by_name(value.c_str());\r
198                         if(c == nullptr)\r
199                                 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("acodec"));\r
200 \r
201                         acodec = avcodec_find_encoder_by_name(value.c_str())->id;\r
202 \r
203                         return true;\r
204                 }\r
205                 else if(name == "s")\r
206                 {\r
207                         if(av_parse_video_size(&width, &height, value.c_str()) < 0)\r
208                                 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("s"));\r
209                         \r
210                         return true;\r
211                 }\r
212 \r
213                 return false;\r
214         }\r
215 };\r
216 \r
217 typedef std::vector<uint8_t, tbb::cache_aligned_allocator<uint8_t>>     byte_vector;\r
218 \r
219 struct ffmpeg_consumer : boost::noncopyable\r
220 {               \r
221         const std::string                                               filename_;\r
222                 \r
223         const std::shared_ptr<AVFormatContext>  oc_;\r
224         const core::video_format_desc                   format_desc_;\r
225         \r
226         const safe_ptr<diagnostics::graph>              graph_;\r
227 \r
228         executor                                                                encode_executor_;\r
229         \r
230         std::shared_ptr<AVStream>                               audio_st_;\r
231         std::shared_ptr<AVStream>                               video_st_;\r
232         \r
233         byte_vector                                                             audio_outbuf_;\r
234         byte_vector                                                             audio_buf_;\r
235         byte_vector                                                             video_outbuf_;\r
236         byte_vector                                                             picture_buf_;\r
237         std::shared_ptr<audio_resampler>                swr_;\r
238         std::shared_ptr<SwsContext>                             sws_;\r
239 \r
240         int64_t                                                                 in_frame_number_;\r
241         int64_t                                                                 out_frame_number_;\r
242 \r
243         output_format                                                   output_format_;\r
244         \r
245 public:\r
246         ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, std::vector<option> options)\r
247                 : filename_(filename)\r
248                 , video_outbuf_(1920*1080*8)\r
249                 , audio_outbuf_(10000)\r
250                 , oc_(avformat_alloc_context(), av_free)\r
251                 , format_desc_(format_desc)\r
252                 , encode_executor_(print())\r
253                 , in_frame_number_(0)\r
254                 , out_frame_number_(0)\r
255                 , output_format_(format_desc, filename, options)\r
256         {\r
257                 // TODO: Ask stakeholders about case where file already exists.\r
258                 boost::filesystem2::remove(boost::filesystem2::wpath(env::media_folder() + widen(filename))); // Delete the file if it exists\r
259 \r
260                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
261                 graph_->set_text(print());\r
262                 diagnostics::register_graph(graph_);\r
263 \r
264                 encode_executor_.set_capacity(8);\r
265 \r
266                 oc_->oformat = output_format_.format;\r
267                                 \r
268                 THROW_ON_ERROR2(av_set_parameters(oc_.get(), nullptr), "[ffmpeg_consumer]");\r
269 \r
270                 strcpy_s(oc_->filename, filename_.c_str());\r
271                 \r
272                 //  Add the audio and video streams using the default format codecs     and initialize the codecs.\r
273                 auto options2 = options;\r
274                 video_st_ = add_video_stream(options2);\r
275                 audio_st_ = add_audio_stream(options);\r
276                                 \r
277                 dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
278                  \r
279                 // Open the output ffmpeg, if needed.\r
280                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
281                         THROW_ON_ERROR2(avio_open(&oc_->pb, filename_.c_str(), URL_WRONLY), "[ffmpeg_consumer]");\r
282                                 \r
283                 THROW_ON_ERROR2(av_write_header(oc_.get()), "[ffmpeg_consumer]");\r
284 \r
285                 if(options.size() > 0)\r
286                 {\r
287                         BOOST_FOREACH(auto& option, options)\r
288                                 CASPAR_LOG(warning) << L"Invalid option: -" << widen(option.name) << L" " << widen(option.value);\r
289                 }\r
290 \r
291                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";   \r
292         }\r
293 \r
294         ~ffmpeg_consumer()\r
295         {    \r
296                 encode_executor_.stop();\r
297                 encode_executor_.join();\r
298                 \r
299                 LOG_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");\r
300                 \r
301                 audio_st_.reset();\r
302                 video_st_.reset();\r
303                           \r
304                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
305                         LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]"); // Close the output ffmpeg.\r
306 \r
307                 CASPAR_LOG(info) << print() << L" Successfully Uninitialized."; \r
308         }\r
309                         \r
310         std::wstring print() const\r
311         {\r
312                 return L"ffmpeg[" + widen(filename_) + L"]";\r
313         }\r
314 \r
315         std::shared_ptr<AVStream> add_video_stream(std::vector<option>& options)\r
316         { \r
317                 if(output_format_.vcodec == CODEC_ID_NONE)\r
318                         return nullptr;\r
319 \r
320                 auto st = av_new_stream(oc_.get(), 0);\r
321                 if (!st)                \r
322                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("av_new_stream"));              \r
323 \r
324                 auto encoder = avcodec_find_encoder(output_format_.vcodec);\r
325                 if (!encoder)\r
326                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Codec not found."));\r
327 \r
328                 auto c = st->codec;\r
329 \r
330                 avcodec_get_context_defaults3(c, encoder);\r
331                                 \r
332                 c->codec_id                     = output_format_.vcodec;\r
333                 c->codec_type           = AVMEDIA_TYPE_VIDEO;\r
334                 c->width                        = output_format_.width;\r
335                 c->height                       = output_format_.height;\r
336                 c->time_base.den        = format_desc_.time_scale;\r
337                 c->time_base.num        = format_desc_.duration;\r
338                 c->gop_size                     = 25;\r
339                 c->flags                   |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);\r
340                 if(c->pix_fmt == PIX_FMT_NONE)\r
341                         c->pix_fmt = PIX_FMT_YUV420P;\r
342 \r
343                 if(c->codec_id == CODEC_ID_PRORES)\r
344                 {                       \r
345                         c->bit_rate     = c->width < 1280 ? 63*1000000 : 220*1000000;\r
346                         c->pix_fmt      = PIX_FMT_YUV422P10;\r
347                 }\r
348                 else if(c->codec_id == CODEC_ID_DNXHD)\r
349                 {\r
350                         if(c->width < 1280 || c->height < 720)\r
351                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Unsupported video dimensions."));\r
352 \r
353                         c->bit_rate     = 220*1000000;\r
354                         c->pix_fmt      = PIX_FMT_YUV422P;\r
355                 }\r
356                 else if(c->codec_id == CODEC_ID_DVVIDEO)\r
357                 {\r
358                         c->width = c->height == 1280 ? 960  : c->width;\r
359                         \r
360                         if(format_desc_.format == core::video_format::ntsc)\r
361                                 c->pix_fmt = PIX_FMT_YUV411P;\r
362                         else if(format_desc_.format == core::video_format::pal)\r
363                                 c->pix_fmt = PIX_FMT_YUV420P;\r
364                         else // dv50\r
365                                 c->pix_fmt = PIX_FMT_YUV422P;\r
366                         \r
367                         if(format_desc_.duration == 1001)                       \r
368                                 c->width = c->height == 1080 ? 1280 : c->width;                 \r
369                         else\r
370                                 c->width = c->height == 1080 ? 1440 : c->width;                 \r
371                 }\r
372                 else if(c->codec_id == CODEC_ID_H264)\r
373                 {                          \r
374                         c->pix_fmt = PIX_FMT_YUV420P;    \r
375                         if(options.empty())\r
376                         {\r
377                                 av_opt_set(c->priv_data, "preset", "ultrafast", 0);\r
378                                 av_opt_set(c->priv_data, "tune",   "fastdecode",   0);\r
379                                 av_opt_set(c->priv_data, "crf",    "5",     0);\r
380                         }\r
381                 }\r
382                 else if(c->codec_id == CODEC_ID_QTRLE)\r
383                 {\r
384                         c->pix_fmt = PIX_FMT_ARGB;\r
385                 }\r
386                                 \r
387                 c->max_b_frames = 0; // b-frames not supported.\r
388                                 \r
389                 boost::range::remove_erase_if(options, [&](const option& o)\r
390                 {\r
391                         return ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1 ||\r
392                                    ffmpeg::av_opt_set(c->priv_data, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;\r
393                 });\r
394                                 \r
395                 if(output_format_.format->flags & AVFMT_GLOBALHEADER)\r
396                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
397                 \r
398                 c->thread_count = boost::thread::hardware_concurrency();\r
399                 if(avcodec_open(c, encoder) < 0)\r
400                 {\r
401                         c->thread_count = 1;\r
402                         THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
403                 }\r
404 \r
405                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
406                 {\r
407                         LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");\r
408                         av_freep(&st->codec);\r
409                         av_freep(&st);\r
410                 });\r
411         }\r
412                 \r
413         std::shared_ptr<AVStream> add_audio_stream(std::vector<option>& options)\r
414         {\r
415                 if(output_format_.acodec == CODEC_ID_NONE)\r
416                         return nullptr;\r
417 \r
418                 auto st = av_new_stream(oc_.get(), 1);\r
419                 if(!st)\r
420                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate audio-stream") << boost::errinfo_api_function("av_new_stream"));               \r
421                 \r
422                 auto encoder = avcodec_find_encoder(output_format_.acodec);\r
423                 if (!encoder)\r
424                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
425                 \r
426                 auto c = st->codec;\r
427 \r
428                 avcodec_get_context_defaults3(c, encoder);\r
429 \r
430                 c->codec_id                     = output_format_.acodec;\r
431                 c->codec_type           = AVMEDIA_TYPE_AUDIO;\r
432                 c->sample_rate          = 48000;\r
433                 c->channels                     = 2;\r
434                 c->sample_fmt           = SAMPLE_FMT_S16;\r
435 \r
436                 if(output_format_.vcodec == CODEC_ID_FLV1)              \r
437                         c->sample_rate  = 44100;                \r
438 \r
439                 if(output_format_.format->flags & AVFMT_GLOBALHEADER)\r
440                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
441                                 \r
442                 boost::range::remove_erase_if(options, [&](const option& o)\r
443                 {\r
444                         return ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;\r
445                 });\r
446 \r
447                 THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
448 \r
449                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
450                 {\r
451                         LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");;\r
452                         av_freep(&st->codec);\r
453                         av_freep(&st);\r
454                 });\r
455         }\r
456 \r
457         std::shared_ptr<AVFrame> convert_video(core::read_frame& frame, AVCodecContext* c)\r
458         {\r
459                 if(!sws_) \r
460                 {\r
461                         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
462                         if (sws_ == nullptr) \r
463                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));\r
464                 }\r
465 \r
466                 std::shared_ptr<AVFrame> in_frame(avcodec_alloc_frame(), av_free);\r
467                 avpicture_fill(reinterpret_cast<AVPicture*>(in_frame.get()), const_cast<uint8_t*>(frame.image_data().begin()), PIX_FMT_BGRA, format_desc_.width, format_desc_.height);\r
468                                 \r
469                 std::shared_ptr<AVFrame> out_frame(avcodec_alloc_frame(), av_free);\r
470                 picture_buf_.resize(avpicture_get_size(c->pix_fmt, c->width, c->height));\r
471                 avpicture_fill(reinterpret_cast<AVPicture*>(out_frame.get()), picture_buf_.data(), c->pix_fmt, c->width, c->height);\r
472 \r
473                 sws_scale(sws_.get(), in_frame->data, in_frame->linesize, 0, format_desc_.height, out_frame->data, out_frame->linesize);\r
474 \r
475                 return out_frame;\r
476         }\r
477   \r
478         void encode_video_frame(core::read_frame& frame)\r
479         { \r
480                 auto c = video_st_->codec;\r
481                 \r
482                 auto in_time  = static_cast<double>(in_frame_number_) / format_desc_.fps;\r
483                 auto out_time = static_cast<double>(out_frame_number_) / (static_cast<double>(c->time_base.den) / static_cast<double>(c->time_base.num));\r
484                 \r
485                 in_frame_number_++;\r
486 \r
487                 if(out_time - in_time > 0.01)\r
488                         return;\r
489  \r
490                 auto av_frame = convert_video(frame, c);\r
491                 av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
492                 av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper;\r
493                 av_frame->pts                           = out_frame_number_++;\r
494 \r
495                 int out_size = THROW_ON_ERROR2(avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), av_frame.get()), "[ffmpeg_consumer]");\r
496                 if(out_size == 0)\r
497                         return;\r
498                                 \r
499                 safe_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)\r
500                 {\r
501                         av_free_packet(p);\r
502                         delete p;\r
503                 });\r
504                 av_init_packet(pkt.get());\r
505  \r
506                 if (c->coded_frame->pts != AV_NOPTS_VALUE)\r
507                         pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);\r
508 \r
509                 if(c->coded_frame->key_frame)\r
510                         pkt->flags |= AV_PKT_FLAG_KEY;\r
511 \r
512                 pkt->stream_index       = video_st_->index;\r
513                 pkt->data                       = video_outbuf_.data();\r
514                 pkt->size                       = out_size;\r
515                         \r
516                 av_interleaved_write_frame(oc_.get(), pkt.get());               \r
517         }\r
518                 \r
519         byte_vector convert_audio(core::read_frame& frame, AVCodecContext* c)\r
520         {\r
521                 if(!swr_)               \r
522                         swr_.reset(new audio_resampler(c->channels, format_desc_.audio_channels, \r
523                                                                                    c->sample_rate, format_desc_.audio_sample_rate,\r
524                                                                                    c->sample_fmt, AV_SAMPLE_FMT_S32));\r
525                 \r
526 \r
527                 auto audio_data = frame.audio_data();\r
528 \r
529                 std::vector<int8_t,  tbb::cache_aligned_allocator<int8_t>> audio_resample_buffer;\r
530                 std::copy(reinterpret_cast<const uint8_t*>(audio_data.begin()), \r
531                                   reinterpret_cast<const uint8_t*>(audio_data.begin()) + audio_data.size()*4, \r
532                                   std::back_inserter(audio_resample_buffer));\r
533                 \r
534                 audio_resample_buffer = swr_->resample(std::move(audio_resample_buffer));\r
535                 \r
536                 return byte_vector(audio_resample_buffer.begin(), audio_resample_buffer.end());\r
537         }\r
538 \r
539         void encode_audio_frame(core::read_frame& frame)\r
540         {                       \r
541                 auto c = audio_st_->codec;\r
542 \r
543                 boost::range::push_back(audio_buf_, convert_audio(frame, c));\r
544                 \r
545                 std::size_t frame_size = c->frame_size;\r
546                 auto input_audio_size = frame_size * av_get_bytes_per_sample(c->sample_fmt) * c->channels;\r
547                 \r
548                 while(audio_buf_.size() >= input_audio_size)\r
549                 {\r
550                         safe_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)\r
551                         {\r
552                                 av_free_packet(p);\r
553                                 delete p;\r
554                         });\r
555                         av_init_packet(pkt.get());\r
556 \r
557                         if(frame_size > 1)\r
558                         {                                                               \r
559                                 pkt->size = avcodec_encode_audio(c, audio_outbuf_.data(), audio_outbuf_.size(), reinterpret_cast<short*>(audio_buf_.data()));\r
560                                 audio_buf_.erase(audio_buf_.begin(), audio_buf_.begin() + input_audio_size);\r
561                         }\r
562                         else\r
563                         {\r
564                                 audio_outbuf_ = std::move(audio_buf_);          \r
565                                 audio_buf_.clear();\r
566                                 pkt->size = audio_outbuf_.size();\r
567                                 pkt->data = audio_outbuf_.data();\r
568                         }\r
569                 \r
570                         if(pkt->size == 0)\r
571                                 return;\r
572 \r
573                         if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)\r
574                                 pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);\r
575 \r
576                         pkt->flags               |= AV_PKT_FLAG_KEY;\r
577                         pkt->stream_index = audio_st_->index;\r
578                         pkt->data                 = reinterpret_cast<uint8_t*>(audio_outbuf_.data());\r
579                 \r
580                         av_interleaved_write_frame(oc_.get(), pkt.get());\r
581                 }\r
582         }\r
583                  \r
584         void send(const safe_ptr<core::read_frame>& frame)\r
585         {\r
586                 encode_executor_.begin_invoke([=]\r
587                 {               \r
588                         boost::timer frame_timer;\r
589 \r
590                         encode_video_frame(*frame);\r
591                         encode_audio_frame(*frame);\r
592 \r
593                         graph_->set_value("frame-time", frame_timer.elapsed()*format_desc_.fps*0.5);                    \r
594                 });\r
595         }\r
596 };\r
597 \r
598 struct ffmpeg_consumer_proxy : public core::frame_consumer\r
599 {\r
600         const std::wstring                              filename_;\r
601         const std::vector<option>                       options_;\r
602 \r
603         std::unique_ptr<ffmpeg_consumer> consumer_;\r
604 \r
605 public:\r
606 \r
607         ffmpeg_consumer_proxy(const std::wstring& filename, const std::vector<option>& options)\r
608                 : filename_(filename)\r
609                 , options_(options)\r
610         {\r
611         }\r
612         \r
613         virtual void initialize(const core::video_format_desc& format_desc, int)\r
614         {\r
615                 consumer_.reset();\r
616                 consumer_.reset(new ffmpeg_consumer(narrow(filename_), format_desc, options_));\r
617         }\r
618         \r
619         virtual boost::unique_future<bool> send(const safe_ptr<core::read_frame>& frame) override\r
620         {\r
621                 consumer_->send(frame);\r
622                 return caspar::wrap_as_future(true);\r
623         }\r
624         \r
625         virtual std::wstring print() const override\r
626         {\r
627                 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";\r
628         }\r
629 \r
630         virtual boost::property_tree::wptree info() const override\r
631         {\r
632                 boost::property_tree::wptree info;\r
633                 info.add(L"type", L"ffmpeg-consumer");\r
634                 info.add(L"filename", filename_);\r
635                 return info;\r
636         }\r
637                 \r
638         virtual bool has_synchronization_clock() const override\r
639         {\r
640                 return false;\r
641         }\r
642 \r
643         virtual size_t buffer_depth() const override\r
644         {\r
645                 return 1;\r
646         }\r
647 \r
648         virtual int index() const override\r
649         {\r
650                 return 200;\r
651         }\r
652 };      \r
653 \r
654 safe_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)\r
655 {\r
656         if(params.size() < 1 || params[0] != L"FILE")\r
657                 return core::frame_consumer::empty();\r
658         \r
659         auto filename   = (params.size() > 1 ? params[1] : L"");\r
660                         \r
661         std::vector<option> options;\r
662         \r
663         if(params.size() >= 3)\r
664         {\r
665                 for(auto opt_it = params.begin()+2; opt_it != params.end();)\r
666                 {\r
667                         auto name  = narrow(boost::trim_copy(boost::to_lower_copy(*opt_it++))).substr(1);\r
668                         auto value = narrow(boost::trim_copy(boost::to_lower_copy(*opt_it++)));\r
669                                 \r
670                         if(value == "h264")\r
671                                 value = "libx264";\r
672                         else if(value == "dvcpro")\r
673                                 value = "dvvideo";\r
674 \r
675                         options.push_back(option(name, value));\r
676                 }\r
677         }\r
678                 \r
679         return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);\r
680 }\r
681 \r
682 safe_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree)\r
683 {\r
684         auto filename   = ptree.get<std::wstring>(L"path");\r
685         auto codec              = ptree.get(L"vcodec", L"libx264");\r
686 \r
687         std::vector<option> options;\r
688         options.push_back(option("vcodec", narrow(codec)));\r
689         \r
690         return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);\r
691 }\r
692 \r
693 }}\r