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