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