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