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