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