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