]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/consumer/ffmpeg_consumer.cpp
git-svn-id: https://casparcg.svn.sourceforge.net/svnroot/casparcg/server/branches...
[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                 //              BOOST_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                                 BOOST_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                                 BOOST_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                                 BOOST_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                                 BOOST_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 std::string                                               filename_;\r
240                 \r
241         const std::shared_ptr<AVFormatContext>  oc_;\r
242         const core::video_format_desc                   format_desc_;\r
243         \r
244         const spl::shared_ptr<diagnostics::graph>               graph_;\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                 // TODO: Ask stakeholders about case where file already exists.\r
272                 boost::filesystem::remove(boost::filesystem::path(env::media_folder() + u16(filename))); // Delete the file if it exists\r
273 \r
274                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
275                 graph_->set_text(print());\r
276                 diagnostics::register_graph(graph_);\r
277 \r
278                 executor_.set_capacity(8);\r
279 \r
280                 oc_->oformat = output_format_.format;\r
281                                 \r
282                 strcpy_s(oc_->filename, filename_.c_str());\r
283                 \r
284                 //  Add the audio and video streams using the default format codecs     and initialize the codecs.\r
285                 video_st_ = add_video_stream(options);\r
286                 audio_st_ = add_audio_stream(options);\r
287                                 \r
288                 av_dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
289                  \r
290                 // Open the output ffmpeg, if needed.\r
291                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
292                         THROW_ON_ERROR2(avio_open(&oc_->pb, filename.c_str(), AVIO_FLAG_WRITE), "[ffmpeg_consumer]");\r
293                                 \r
294                 THROW_ON_ERROR2(avformat_write_header(oc_.get(), nullptr), "[ffmpeg_consumer]");\r
295 \r
296                 if(options.size() > 0)\r
297                 {\r
298                         BOOST_FOREACH(auto& option, options)\r
299                                 CASPAR_LOG(warning) << L"Invalid option: -" << u16(option.name) << L" " << u16(option.value);\r
300                 }\r
301 \r
302                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";   \r
303         }\r
304 \r
305         ~ffmpeg_consumer()\r
306         {    \r
307                 executor_.wait();\r
308                 \r
309                 LOG_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");\r
310                 \r
311                 audio_st_.reset();\r
312                 video_st_.reset();\r
313                           \r
314                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
315                         LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]"); // Close the output ffmpeg.\r
316 \r
317                 CASPAR_LOG(info) << print() << L" Successfully Uninitialized."; \r
318         }\r
319                         \r
320         std::wstring print() const\r
321         {\r
322                 return L"ffmpeg[" + u16(filename_) + L"]";\r
323         }\r
324 \r
325         std::shared_ptr<AVStream> add_video_stream(std::vector<option>& options)\r
326         { \r
327                 if(output_format_.vcodec == CODEC_ID_NONE)\r
328                         return nullptr;\r
329 \r
330                 auto st = av_new_stream(oc_.get(), 0);\r
331                 if (!st)                \r
332                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("av_new_stream"));              \r
333 \r
334                 auto encoder = avcodec_find_encoder(output_format_.vcodec);\r
335                 if (!encoder)\r
336                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Codec not found."));\r
337 \r
338                 auto c = st->codec;\r
339 \r
340                 avcodec_get_context_defaults3(c, encoder);\r
341                                 \r
342                 c->codec_id                     = output_format_.vcodec;\r
343                 c->codec_type           = AVMEDIA_TYPE_VIDEO;\r
344                 c->width                        = output_format_.width;\r
345                 c->height                       = output_format_.height - output_format_.croptop - output_format_.cropbot;\r
346                 c->time_base.den        = format_desc_.time_scale;\r
347                 c->time_base.num        = format_desc_.duration;\r
348                 c->gop_size                     = 25;\r
349                 c->flags                   |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);\r
350                 c->pix_fmt                      = c->pix_fmt != PIX_FMT_NONE ? c->pix_fmt : PIX_FMT_YUV420P;\r
351 \r
352                 if(c->codec_id == CODEC_ID_PRORES)\r
353                 {                       \r
354                         c->bit_rate     = c->width < 1280 ? 63*1000000 : 220*1000000;\r
355                         c->pix_fmt      = PIX_FMT_YUV422P10;\r
356                 }\r
357                 else if(c->codec_id == CODEC_ID_DNXHD)\r
358                 {\r
359                         if(c->width < 1280 || c->height < 720)\r
360                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Unsupported video dimensions."));\r
361 \r
362                         c->bit_rate     = 220*1000000;\r
363                         c->pix_fmt      = PIX_FMT_YUV422P;\r
364                 }\r
365                 else if(c->codec_id == CODEC_ID_DVVIDEO)\r
366                 {\r
367                         c->width = c->height == 1280 ? 960  : c->width;\r
368                         \r
369                         if(format_desc_.format == core::video_format::ntsc)\r
370                                 c->pix_fmt = PIX_FMT_YUV411P;\r
371                         else if(format_desc_.format == core::video_format::pal)\r
372                                 c->pix_fmt = PIX_FMT_YUV420P;\r
373                         else // dv50\r
374                                 c->pix_fmt = PIX_FMT_YUV422P;\r
375                         \r
376                         if(format_desc_.duration == 1001)                       \r
377                                 c->width = c->height == 1080 ? 1280 : c->width;                 \r
378                         else\r
379                                 c->width = c->height == 1080 ? 1440 : c->width;                 \r
380                 }\r
381                 else if(c->codec_id == CODEC_ID_H264)\r
382                 {                          \r
383                         c->pix_fmt = PIX_FMT_YUV420P;    \r
384                         av_opt_set(c->priv_data, "preset", "ultrafast", 0);\r
385                         av_opt_set(c->priv_data, "tune",   "fastdecode",   0);\r
386                         av_opt_set(c->priv_data, "crf",    "5",     0);\r
387                 }\r
388                 else if(c->codec_id == CODEC_ID_QTRLE)\r
389                 {\r
390                         c->pix_fmt = PIX_FMT_ARGB;\r
391                 }\r
392                                                                 \r
393                 boost::range::remove_erase_if(options, [&](const option& o)\r
394                 {\r
395                         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
396                 });\r
397                                 \r
398                 if(output_format_.format->flags & AVFMT_GLOBALHEADER)\r
399                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
400                 \r
401                 THROW_ON_ERROR2(tbb_avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
402 \r
403                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
404                 {\r
405                         LOG_ON_ERROR2(tbb_avcodec_close(st->codec), "[ffmpeg_consumer]");\r
406                         av_freep(&st->codec);\r
407                         av_freep(&st);\r
408                 });\r
409         }\r
410                 \r
411         std::shared_ptr<AVStream> add_audio_stream(std::vector<option>& options)\r
412         {\r
413                 if(output_format_.acodec == CODEC_ID_NONE)\r
414                         return nullptr;\r
415 \r
416                 auto st = av_new_stream(oc_.get(), 1);\r
417                 if(!st)\r
418                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate audio-stream") << boost::errinfo_api_function("av_new_stream"));               \r
419                 \r
420                 auto encoder = avcodec_find_encoder(output_format_.acodec);\r
421                 if (!encoder)\r
422                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
423                 \r
424                 auto c = st->codec;\r
425 \r
426                 avcodec_get_context_defaults3(c, encoder);\r
427 \r
428                 c->codec_id                     = output_format_.acodec;\r
429                 c->codec_type           = AVMEDIA_TYPE_AUDIO;\r
430                 c->sample_rate          = 48000;\r
431                 c->channels                     = 2;\r
432                 c->sample_fmt           = AV_SAMPLE_FMT_S16;\r
433                 c->time_base.num        = 1;\r
434                 c->time_base.den        = c->sample_rate;\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         void encode_video_frame(core::const_frame frame)\r
458         { \r
459                 if(!video_st_)\r
460                         return;\r
461                 \r
462                 auto enc = video_st_->codec;\r
463          \r
464                 auto av_frame                           = convert_video(frame, enc);\r
465                 av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
466                 av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper;\r
467                 av_frame->pts                           = frame_number_++;\r
468 \r
469                 AVPacket pkt;\r
470                 av_init_packet(&pkt);\r
471                 pkt.data = nullptr;\r
472                 pkt.size = 0;\r
473 \r
474                 int got_packet = 0;\r
475                 THROW_ON_ERROR2(avcodec_encode_video2(enc, &pkt, av_frame.get(), &got_packet), "[ffmpeg_consumer]");\r
476                 std::shared_ptr<AVPacket> guard(&pkt, av_free_packet);\r
477 \r
478                 if(!got_packet)\r
479                         return;\r
480                  \r
481                 if (pkt.pts != AV_NOPTS_VALUE)\r
482                         pkt.pts = av_rescale_q(pkt.pts, enc->time_base, video_st_->time_base);\r
483                 if (pkt.dts != AV_NOPTS_VALUE)\r
484                         pkt.dts = av_rescale_q(pkt.dts, enc->time_base, video_st_->time_base);\r
485                  \r
486                 pkt.stream_index = video_st_->index;\r
487                         \r
488                 THROW_ON_ERROR2(av_interleaved_write_frame(oc_.get(), &pkt), "[ffmpeg_consumer]");\r
489         }\r
490                 \r
491         uint64_t get_channel_layout(AVCodecContext* dec)\r
492         {\r
493                 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
494                 return layout;\r
495         }\r
496                 \r
497         void encode_audio_frame(core::const_frame frame)\r
498         {               \r
499                 if(!audio_st_)\r
500                         return;\r
501                 \r
502                 auto enc = audio_st_->codec;\r
503 \r
504                 boost::push_back(audio_buffer_, convert_audio(frame, enc));\r
505                         \r
506                 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
507                         \r
508                 while(audio_buffer_.size() >= frame_size)\r
509                 {                       \r
510                         std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);\r
511                         avcodec_get_frame_defaults(av_frame.get());             \r
512                         av_frame->nb_samples = frame_size / (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));\r
513 \r
514                         AVPacket pkt;\r
515                         av_init_packet(&pkt);\r
516                         pkt.data = nullptr;\r
517                         pkt.size = 0;                           \r
518                         \r
519                         THROW_ON_ERROR2(avcodec_fill_audio_frame(av_frame.get(), enc->channels, enc->sample_fmt, audio_buffer_.data(), frame_size, 1), "[ffmpeg_consumer]");\r
520 \r
521                         int got_packet = 0;\r
522                         THROW_ON_ERROR2(avcodec_encode_audio2(enc, &pkt, av_frame.get(), &got_packet), "[ffmpeg_consumer]");\r
523                         std::shared_ptr<AVPacket> guard(&pkt, av_free_packet);\r
524                                 \r
525                         audio_buffer_.erase(audio_buffer_.begin(), audio_buffer_.begin() + frame_size);\r
526 \r
527                         if(!got_packet)\r
528                                 return;\r
529                 \r
530                         if (pkt.pts != AV_NOPTS_VALUE)\r
531                                 pkt.pts      = av_rescale_q(pkt.pts, enc->time_base, audio_st_->time_base);\r
532                         if (pkt.dts != AV_NOPTS_VALUE)\r
533                                 pkt.dts      = av_rescale_q(pkt.dts, enc->time_base, audio_st_->time_base);\r
534                         if (pkt.duration > 0)\r
535                                 pkt.duration = static_cast<int>(av_rescale_q(pkt.duration, enc->time_base, audio_st_->time_base));\r
536                 \r
537                         pkt.stream_index = audio_st_->index;\r
538                                                 \r
539                         THROW_ON_ERROR2(av_interleaved_write_frame(oc_.get(), &pkt), "[ffmpeg_consumer]");\r
540                 }\r
541         }                \r
542         \r
543         std::shared_ptr<AVFrame> convert_video(core::const_frame frame, AVCodecContext* c)\r
544         {\r
545                 if(!sws_) \r
546                 {\r
547                         sws_.reset(sws_getContext(format_desc_.width, \r
548                                                                           format_desc_.height - output_format_.croptop  - output_format_.cropbot, \r
549                                                                           PIX_FMT_BGRA,\r
550                                                                           c->width,\r
551                                                                           c->height, \r
552                                                                           c->pix_fmt, \r
553                                                                           SWS_BICUBIC, nullptr, nullptr, nullptr), \r
554                                                 sws_freeContext);\r
555                         if (sws_ == nullptr) \r
556                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));\r
557                 }\r
558 \r
559                 std::shared_ptr<AVFrame> in_frame(avcodec_alloc_frame(), av_free);\r
560 \r
561                 avpicture_fill(reinterpret_cast<AVPicture*>(in_frame.get()), \r
562                                            const_cast<uint8_t*>(frame.image_data().begin()),\r
563                                            PIX_FMT_BGRA, \r
564                                            format_desc_.width,\r
565                                            format_desc_.height - output_format_.croptop  - output_format_.cropbot);\r
566 \r
567                 for(int n = 0; n < 4; ++n)              \r
568                         in_frame->data[n] += in_frame->linesize[n] * output_format_.croptop;            \r
569                                         \r
570                 picture_buffer_.resize(avpicture_get_size(c->pix_fmt, c->width, c->height));\r
571 \r
572                 std::shared_ptr<AVFrame> out_frame(avcodec_alloc_frame(), av_free);\r
573                 \r
574                 avpicture_fill(reinterpret_cast<AVPicture*>(out_frame.get()),\r
575                                            picture_buffer_.data(), \r
576                                            c->pix_fmt, \r
577                                            c->width, \r
578                                            c->height);\r
579 \r
580                 sws_scale(sws_.get(), \r
581                                   in_frame->data, \r
582                                   in_frame->linesize,\r
583                                   0, \r
584                                   format_desc_.height - output_format_.cropbot - output_format_.croptop, \r
585                                   out_frame->data, \r
586                                   out_frame->linesize);\r
587 \r
588                 return out_frame;\r
589         }\r
590         \r
591         byte_vector convert_audio(core::const_frame& frame, AVCodecContext* c)\r
592         {\r
593                 if(!swr_) \r
594                 {\r
595                         swr_ = std::shared_ptr<SwrContext>(swr_alloc_set_opts(nullptr,\r
596                                                                                 get_channel_layout(c), c->sample_fmt, c->sample_rate,\r
597                                                                                 av_get_default_channel_layout(format_desc_.audio_channels), AV_SAMPLE_FMT_S32, format_desc_.audio_sample_rate,\r
598                                                                                 0, nullptr), [](SwrContext* p){swr_free(&p);});\r
599 \r
600                         if(!swr_)\r
601                                 BOOST_THROW_EXCEPTION(std::bad_alloc("swr_"));\r
602 \r
603                         THROW_ON_ERROR2(swr_init(swr_.get()), "[audio_decoder]");\r
604                 }\r
605                                 \r
606                 byte_vector buffer(48000);\r
607 \r
608                 const uint8_t* in[]  = {reinterpret_cast<const uint8_t*>(frame.audio_data().data())};\r
609                 uint8_t*       out[] = {buffer.data()};\r
610 \r
611                 auto channel_samples = swr_convert(swr_.get(), \r
612                                                                                    out, static_cast<int>(buffer.size()) / c->channels / av_get_bytes_per_sample(c->sample_fmt), \r
613                                                                                    in, static_cast<int>(frame.audio_data().size()/format_desc_.audio_channels));\r
614 \r
615                 buffer.resize(channel_samples * c->channels * av_get_bytes_per_sample(c->sample_fmt));  \r
616 \r
617                 return buffer;\r
618         }\r
619 \r
620         void encode(const core::const_frame& frame)\r
621         {\r
622                 try\r
623                 {\r
624                         boost::timer frame_timer;\r
625 \r
626                         encode_video_frame(frame);\r
627                         encode_audio_frame(frame);\r
628 \r
629                         graph_->set_value("frame-time", frame_timer.elapsed()*format_desc_.fps*0.5);\r
630                 }\r
631                 catch(...)\r
632                 {                       \r
633                         lock(exception_mutex_, [&]\r
634                         {\r
635                                 exception_ = std::current_exception();\r
636                         });\r
637                         executor_.stop();\r
638                 }\r
639         }\r
640 \r
641         bool send(core::const_frame& frame)\r
642         {\r
643                 auto exception = lock(exception_mutex_, [&]\r
644                 {\r
645                         return exception_;\r
646                 });\r
647 \r
648                 if(exception != nullptr)\r
649                         std::rethrow_exception(exception);\r
650                         \r
651                 executor_.begin_invoke([=]\r
652                 {               \r
653                         encode(frame);\r
654                 });\r
655                 \r
656                 return true;\r
657         }\r
658 };\r
659 \r
660 struct ffmpeg_consumer_proxy : public core::frame_consumer\r
661 {\r
662         const std::wstring                              filename_;\r
663         const std::vector<option>               options_;\r
664 \r
665         std::unique_ptr<ffmpeg_consumer> consumer_;\r
666 \r
667 public:\r
668 \r
669         ffmpeg_consumer_proxy(const std::wstring& filename, const std::vector<option>& options)\r
670                 : filename_(filename)\r
671                 , options_(options)\r
672         {\r
673         }\r
674         \r
675         virtual void initialize(const core::video_format_desc& format_desc, int)\r
676         {\r
677                 consumer_.reset();\r
678                 consumer_.reset(new ffmpeg_consumer(u8(filename_), format_desc, options_));\r
679         }\r
680         \r
681         bool send(core::const_frame frame) override\r
682         {\r
683                 return consumer_->send(frame);\r
684         }\r
685         \r
686         std::wstring print() const override\r
687         {\r
688                 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";\r
689         }\r
690 \r
691         std::wstring name() const override\r
692         {\r
693                 return L"file";\r
694         }\r
695 \r
696         boost::property_tree::wptree info() const override\r
697         {\r
698                 boost::property_tree::wptree info;\r
699                 info.add(L"type", L"file");\r
700                 info.add(L"filename", filename_);\r
701                 return info;\r
702         }\r
703                 \r
704         bool has_synchronization_clock() const override\r
705         {\r
706                 return false;\r
707         }\r
708 \r
709         int buffer_depth() const override\r
710         {\r
711                 return 1;\r
712         }\r
713 \r
714         int index() const override\r
715         {\r
716                 return 200;\r
717         }\r
718 };      \r
719 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)\r
720 {\r
721         if(params.size() < 1 || params[0] != L"FILE")\r
722                 return core::frame_consumer::empty();\r
723         \r
724         auto filename   = (params.size() > 1 ? params[1] : L"");\r
725                         \r
726         std::vector<option> options;\r
727         \r
728         if(params.size() >= 3)\r
729         {\r
730                 for(auto opt_it = params.begin()+2; opt_it != params.end();)\r
731                 {\r
732                         auto name  = u8(boost::trim_copy(boost::to_lower_copy(*opt_it++))).substr(1);\r
733                         auto value = u8(boost::trim_copy(boost::to_lower_copy(*opt_it++)));\r
734                                 \r
735                         if(value == "h264")\r
736                                 value = "libx264";\r
737                         else if(value == "dvcpro")\r
738                                 value = "dvvideo";\r
739 \r
740                         options.push_back(option(name, value));\r
741                 }\r
742         }\r
743                 \r
744         return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);\r
745 }\r
746 \r
747 spl::shared_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree)\r
748 {\r
749         auto filename   = ptree.get<std::wstring>(L"path");\r
750         auto codec              = ptree.get(L"vcodec", L"libx264");\r
751 \r
752         std::vector<option> options;\r
753         options.push_back(option("vcodec", u8(codec)));\r
754         \r
755         return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);\r
756 }\r
757 \r
758 }}\r