]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/consumer/streaming_consumer.cpp
Merged INFO DELAY from 2.0
[casparcg] / modules / ffmpeg / consumer / streaming_consumer.cpp
1 #include "../StdAfx.h"
2
3 #include "ffmpeg_consumer.h"
4
5 #include "../ffmpeg_error.h"
6
7 #include <common/except.h>
8 #include <common/executor.h>
9 #include <common/assert.h>
10 #include <common/utf.h>
11 #include <common/future.h>
12 #include <common/env.h>
13 #include <common/scope_exit.h>
14
15 #include <core/consumer/frame_consumer.h>
16 #include <core/frame/frame.h>
17 #include <core/video_format.h>
18 #include <core/monitor/monitor.h>
19 #include <core/help/help_repository.h>
20 #include <core/help/help_sink.h>
21
22 #include <boost/noncopyable.hpp>
23 #include <boost/rational.hpp>
24 #include <boost/format.hpp>
25 #include <boost/algorithm/string/predicate.hpp>
26 #include <boost/property_tree/ptree.hpp>
27
28 #pragma warning(push)
29 #pragma warning(disable: 4244)
30 #pragma warning(disable: 4245)
31 #include <boost/crc.hpp>
32 #pragma warning(pop)
33
34 #include <tbb/atomic.h>
35 #include <tbb/concurrent_queue.h>
36 #include <tbb/parallel_invoke.h>
37 #include <tbb/parallel_for.h>
38
39 #include <numeric>
40
41 #pragma warning(push)
42 #pragma warning(disable: 4244)
43
44 extern "C" 
45 {
46         #define __STDC_CONSTANT_MACROS
47         #define __STDC_LIMIT_MACROS
48         #include <libavformat/avformat.h>
49         #include <libavcodec/avcodec.h>
50         #include <libavutil/avutil.h>
51         #include <libavutil/frame.h>
52         #include <libavutil/opt.h>
53         #include <libavutil/imgutils.h>
54         #include <libavutil/parseutils.h>
55         #include <libavfilter/avfilter.h>
56         #include <libavfilter/buffersink.h>
57         #include <libavfilter/buffersrc.h>
58 }
59
60 #pragma warning(pop)
61
62 namespace caspar { namespace ffmpeg {
63
64 int crc16(const std::string& str)
65 {
66         boost::crc_16_type result;
67
68         result.process_bytes(str.data(), str.length());
69
70         return result.checksum();
71 }
72
73 class streaming_consumer final : public core::frame_consumer
74 {
75 public:
76         // Static Members
77                 
78 private:
79         core::monitor::subject                                          subject_;
80         boost::filesystem::path                                         path_;
81         int                                                                                     consumer_index_offset_;
82
83         std::map<std::string, std::string>                      options_;
84                                                                                                 
85         core::video_format_desc                                         in_video_format_;
86
87         std::shared_ptr<AVFormatContext>                        oc_;
88         tbb::atomic<bool>                                                       abort_request_;
89                                                                                                 
90         std::shared_ptr<AVStream>                                       video_st_;
91         std::shared_ptr<AVStream>                                       audio_st_;
92
93         std::int64_t                                                            video_pts_;
94         std::int64_t                                                            audio_pts_;
95                                                                                                                                                                         
96     AVFilterContext*                                                    audio_graph_in_;  
97     AVFilterContext*                                                    audio_graph_out_; 
98     std::shared_ptr<AVFilterGraph>                              audio_graph_;    
99         std::shared_ptr<AVBitStreamFilterContext>       audio_bitstream_filter_;       
100
101     AVFilterContext*                                                    video_graph_in_;  
102     AVFilterContext*                                                    video_graph_out_; 
103     std::shared_ptr<AVFilterGraph>                              video_graph_;  
104         std::shared_ptr<AVBitStreamFilterContext>       video_bitstream_filter_;
105         
106         executor                                                                        executor_;
107
108         executor                                                                        video_encoder_executor_;
109         executor                                                                        audio_encoder_executor_;
110
111         tbb::atomic<int>                                                        tokens_;
112         boost::mutex                                                            tokens_mutex_;
113         boost::condition_variable                                       tokens_cond_;
114         tbb::atomic<int64_t>                                            current_encoding_delay_;
115
116         executor                                                                        write_executor_;
117         
118 public:
119
120         streaming_consumer(
121                         std::string path, 
122                         std::string options)
123                 : path_(path)
124                 , consumer_index_offset_(crc16(path))
125                 , video_pts_(0)
126                 , audio_pts_(0)
127                 , executor_(print())
128                 , audio_encoder_executor_(print() + L" audio_encoder")
129                 , video_encoder_executor_(print() + L" video_encoder")
130                 , write_executor_(print() + L" io")
131         {               
132                 abort_request_ = false;
133                 current_encoding_delay_ = 0;
134
135                 for(auto it = 
136                                 boost::sregex_iterator(
137                                         options.begin(), 
138                                         options.end(), 
139                                         boost::regex("-(?<NAME>[^-\\s]+)(\\s+(?<VALUE>[^\\s]+))?")); 
140                         it != boost::sregex_iterator(); 
141                         ++it)
142                 {                               
143                         options_[(*it)["NAME"].str()] = (*it)["VALUE"].matched ? (*it)["VALUE"].str() : "";
144                 }
145                                                                                 
146         if (options_.find("threads") == options_.end())
147             options_["threads"] = "auto";
148
149                 tokens_ = 
150                         std::max(
151                                 1, 
152                                 try_remove_arg<int>(
153                                         options_, 
154                                         boost::regex("tokens")).get_value_or(2));               
155         }
156                 
157         ~streaming_consumer()
158         {
159                 if(oc_)
160                 {
161                         video_encoder_executor_.begin_invoke([&] { encode_video(core::const_frame::empty(), nullptr); });
162                         audio_encoder_executor_.begin_invoke([&] { encode_audio(core::const_frame::empty(), nullptr); });
163
164                         video_encoder_executor_.stop();
165                         audio_encoder_executor_.stop();
166                         video_encoder_executor_.join();
167                         audio_encoder_executor_.join();
168
169                         video_graph_.reset();
170                         audio_graph_.reset();
171                         video_st_.reset();
172                         audio_st_.reset();
173
174                         write_packet(nullptr, nullptr);
175
176                         write_executor_.stop();
177                         write_executor_.join();
178
179                         FF(av_write_trailer(oc_.get()));
180
181                         if (!(oc_->oformat->flags & AVFMT_NOFILE) && oc_->pb)
182                                 avio_close(oc_->pb);
183
184                         oc_.reset();
185                 }
186         }
187
188         void initialize(
189                         const core::video_format_desc& format_desc,
190                         int channel_index) override
191         {
192                 try
193                 {                               
194                         static boost::regex prot_exp("^.+:.*" );
195                         
196                         const auto overwrite = 
197                                 try_remove_arg<std::string>(
198                                         options_,
199                                         boost::regex("y")) != nullptr;
200
201                         if(!boost::regex_match(
202                                         path_.string(), 
203                                         prot_exp))
204                         {
205                                 if(!path_.is_complete())
206                                 {
207                                         path_ = 
208                                                 u8(
209                                                         env::media_folder()) + 
210                                                         path_.string();
211                                 }
212                         
213                                 if(boost::filesystem::exists(path_))
214                                 {
215                                         if(!overwrite)
216                                                 BOOST_THROW_EXCEPTION(invalid_argument() << msg_info("File exists"));
217                                                 
218                                         boost::filesystem::remove(path_);
219                                 }
220                         }
221                                                         
222                         const auto oformat_name = 
223                                 try_remove_arg<std::string>(
224                                         options_, 
225                                         boost::regex("^f|format$"));
226                         
227                         AVFormatContext* oc;
228
229                         FF(avformat_alloc_output_context2(
230                                 &oc, 
231                                 nullptr, 
232                                 oformat_name && !oformat_name->empty() ? oformat_name->c_str() : nullptr, 
233                                 path_.string().c_str()));
234
235                         oc_.reset(
236                                 oc, 
237                                 avformat_free_context);
238                                         
239                         CASPAR_VERIFY(oc_->oformat);
240
241                         oc_->interrupt_callback.callback = streaming_consumer::interrupt_cb;
242                         oc_->interrupt_callback.opaque   = this;        
243
244                         CASPAR_VERIFY(format_desc.format != core::video_format::invalid);
245
246                         in_video_format_ = format_desc;
247                                                         
248                         CASPAR_VERIFY(oc_->oformat);
249                         
250                         const auto video_codec_name = 
251                                 try_remove_arg<std::string>(
252                                         options_, 
253                                         boost::regex("^c:v|codec:v|vcodec$"));
254
255                         const auto video_codec = 
256                                 video_codec_name 
257                                         ? avcodec_find_encoder_by_name(video_codec_name->c_str())
258                                         : avcodec_find_encoder(oc_->oformat->video_codec);
259                                                 
260                         const auto audio_codec_name = 
261                                 try_remove_arg<std::string>(
262                                         options_, 
263                                          boost::regex("^c:a|codec:a|acodec$"));
264                         
265                         const auto audio_codec = 
266                                 audio_codec_name 
267                                         ? avcodec_find_encoder_by_name(audio_codec_name->c_str())
268                                         : avcodec_find_encoder(oc_->oformat->audio_codec);
269                         
270                         if (!video_codec)
271                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(
272                                                 "Failed to find video codec " + (video_codec_name
273                                                                 ? *video_codec_name
274                                                                 : "with id " + boost::lexical_cast<std::string>(
275                                                                                 oc_->oformat->video_codec))));
276                         if (!audio_codec)
277                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info(
278                                                 "Failed to find audio codec " + (audio_codec_name
279                                                                 ? *audio_codec_name
280                                                                 : "with id " + boost::lexical_cast<std::string>(
281                                                                                 oc_->oformat->audio_codec))));
282                         
283                         // Filters
284
285                         {
286                                 configure_video_filters(
287                                         *video_codec, 
288                                         try_remove_arg<std::string>(options_, 
289                                         boost::regex("vf|f:v|filter:v")).get_value_or(""));
290
291                                 configure_audio_filters(
292                                         *audio_codec, 
293                                         try_remove_arg<std::string>(options_,
294                                         boost::regex("af|f:a|filter:a")).get_value_or(""));
295                         }
296
297                         // Bistream Filters
298                         {
299                                 configue_audio_bistream_filters(options_);
300                                 configue_video_bistream_filters(options_);
301                         }
302
303                         // Encoders
304
305                         {
306                                 auto video_options = options_;
307                                 auto audio_options = options_;
308
309                                 video_st_ = open_encoder(
310                                         *video_codec, 
311                                         video_options);
312
313                                 audio_st_ = open_encoder(
314                                         *audio_codec, 
315                                         audio_options);
316
317                                 auto it = options_.begin();
318                                 while(it != options_.end())
319                                 {
320                                         if(video_options.find(it->first) == video_options.end() || audio_options.find(it->first) == audio_options.end())
321                                                 it = options_.erase(it);
322                                         else
323                                                 ++it;
324                                 }
325                         }
326
327                         // Output
328                         {
329                                 AVDictionary* av_opts = nullptr;
330
331                                 to_dict(
332                                         &av_opts, 
333                                         std::move(options_));
334
335                                 CASPAR_SCOPE_EXIT
336                                 {
337                                         av_dict_free(&av_opts);
338                                 };
339
340                                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) 
341                                 {
342                                         FF(avio_open2(
343                                                 &oc_->pb, 
344                                                 path_.string().c_str(), 
345                                                 AVIO_FLAG_WRITE, 
346                                                 &oc_->interrupt_callback, 
347                                                 &av_opts));
348                                 }
349                                 
350                                 FF(avformat_write_header(
351                                         oc_.get(), 
352                                         &av_opts));
353                                 
354                                 options_ = to_map(av_opts);
355                         }
356
357                         // Dump Info
358                         
359                         av_dump_format(
360                                 oc_.get(), 
361                                 0, 
362                                 oc_->filename, 
363                                 1);             
364
365                         for (const auto& option : options_)
366                         {
367                                 CASPAR_LOG(warning) 
368                                         << L"Invalid option: -" 
369                                         << u16(option.first) 
370                                         << L" " 
371                                         << u16(option.second);
372                         }
373                 }
374                 catch(...)
375                 {
376                         video_st_.reset();
377                         audio_st_.reset();
378                         oc_.reset();
379                         throw;
380                 }
381         }
382
383         core::monitor::subject& monitor_output() override
384         {
385                 return subject_;
386         }
387
388         std::wstring name() const override
389         {
390                 return L"streaming";
391         }
392
393         std::future<bool> send(core::const_frame frame) override
394         {               
395                 CASPAR_VERIFY(in_video_format_.format != core::video_format::invalid);
396                 
397                 --tokens_;
398                 std::shared_ptr<void> token(
399                         nullptr, 
400                         [this, frame](void*)
401                         {
402                                 ++tokens_;
403                                 tokens_cond_.notify_one();
404                                 current_encoding_delay_ = frame.get_age_millis();
405                         });
406
407                 return executor_.begin_invoke([=]() -> bool
408                 {
409                         boost::unique_lock<boost::mutex> tokens_lock(tokens_mutex_);
410
411                         while(tokens_ < 0)
412                                 tokens_cond_.wait(tokens_lock);
413
414                         video_encoder_executor_.begin_invoke([=]() mutable
415                         {
416                                 encode_video(
417                                         frame, 
418                                         token);
419                         });
420                 
421                         audio_encoder_executor_.begin_invoke([=]() mutable
422                         {
423                                 encode_audio(
424                                         frame, 
425                                         token);
426                         });
427                                 
428                         return true;
429                 });
430         }
431
432         std::wstring print() const override
433         {
434                 return L"streaming_consumer[" + u16(path_.string()) + L"]";
435         }
436         
437         virtual boost::property_tree::wptree info() const override
438         {
439                 return boost::property_tree::wptree();
440         }
441
442         bool has_synchronization_clock() const override
443         {
444                 return false;
445         }
446
447         int buffer_depth() const override
448         {
449                 return -1;
450         }
451
452         int index() const override
453         {
454                 return 100000 + consumer_index_offset_;
455         }
456
457         int64_t presentation_frame_age_millis() const override
458         {
459                 return current_encoding_delay_;
460         }
461
462 private:
463
464         static int interrupt_cb(void* ctx)
465         {
466                 CASPAR_ASSERT(ctx);
467                 return reinterpret_cast<streaming_consumer*>(ctx)->abort_request_;              
468         }
469                 
470         std::shared_ptr<AVStream> open_encoder(
471                         const AVCodec& codec,
472                         std::map<std::string,
473                         std::string>& options)
474         {                       
475                 auto st = 
476                         avformat_new_stream(
477                                 oc_.get(), 
478                                 &codec);
479
480                 if (!st)                
481                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("av_new_stream"));      
482
483                 auto enc = st->codec;
484                                 
485                 CASPAR_VERIFY(enc);
486                                                 
487                 switch(enc->codec_type)
488                 {
489                         case AVMEDIA_TYPE_VIDEO:
490                         {                               
491                                 enc->time_base                    = video_graph_out_->inputs[0]->time_base;
492                                 enc->pix_fmt                      = static_cast<AVPixelFormat>(video_graph_out_->inputs[0]->format);
493                                 enc->sample_aspect_ratio  = st->sample_aspect_ratio = video_graph_out_->inputs[0]->sample_aspect_ratio;
494                                 enc->width                                = video_graph_out_->inputs[0]->w;
495                                 enc->height                               = video_graph_out_->inputs[0]->h;
496                         
497                                 break;
498                         }
499                         case AVMEDIA_TYPE_AUDIO:
500                         {
501                                 enc->time_base                    = audio_graph_out_->inputs[0]->time_base;
502                                 enc->sample_fmt                   = static_cast<AVSampleFormat>(audio_graph_out_->inputs[0]->format);
503                                 enc->sample_rate                  = audio_graph_out_->inputs[0]->sample_rate;
504                                 enc->channel_layout               = audio_graph_out_->inputs[0]->channel_layout;
505                                 enc->channels                     = audio_graph_out_->inputs[0]->channels;
506                         
507                                 break;
508                         }
509                 }
510                                                                                 
511                 if(oc_->oformat->flags & AVFMT_GLOBALHEADER)
512                         enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
513                 
514                 static const std::array<std::string, 4> char_id_map = {{"v", "a", "d", "s"}};
515
516                 const auto char_id = char_id_map.at(enc->codec_type);
517                                                                 
518                 const auto codec_opts = 
519                         remove_options(
520                                 options, 
521                                 boost::regex("^(" + char_id + "?[^:]+):" + char_id + "$"));
522                 
523                 AVDictionary* av_codec_opts = nullptr;
524
525                 to_dict(
526                         &av_codec_opts, 
527                         options);
528
529                 to_dict(
530                         &av_codec_opts,
531                         codec_opts);
532
533                 options.clear();
534                 
535                 FF(avcodec_open2(
536                         enc,            
537                         &codec, 
538                         av_codec_opts ? &av_codec_opts : nullptr));             
539
540                 if(av_codec_opts)
541                 {
542                         auto t = 
543                                 av_dict_get(
544                                         av_codec_opts, 
545                                         "", 
546                                          nullptr, 
547                                         AV_DICT_IGNORE_SUFFIX);
548
549                         while(t)
550                         {
551                                 options[t->key + (codec_opts.find(t->key) != codec_opts.end() ? ":" + char_id : "")] = t->value;
552
553                                 t = av_dict_get(
554                                                 av_codec_opts, 
555                                                 "", 
556                                                 t, 
557                                                 AV_DICT_IGNORE_SUFFIX);
558                         }
559
560                         av_dict_free(&av_codec_opts);
561                 }
562                                 
563                 if(enc->codec_type == AVMEDIA_TYPE_AUDIO && !(codec.capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
564                 {
565                         CASPAR_ASSERT(enc->frame_size > 0);
566                         av_buffersink_set_frame_size(audio_graph_out_, 
567                                                                                  enc->frame_size);
568                 }
569                 
570                 return std::shared_ptr<AVStream>(st, [this](AVStream* st)
571                 {
572                         avcodec_close(st->codec);
573                 });
574         }
575
576         void configue_audio_bistream_filters(
577                         std::map<std::string, std::string>& options)
578         {
579                 const auto audio_bitstream_filter_str = 
580                         try_remove_arg<std::string>(
581                                 options, 
582                                 boost::regex("^bsf:a|absf$"));
583
584                 const auto audio_bitstream_filter = 
585                         audio_bitstream_filter_str 
586                                 ? av_bitstream_filter_init(audio_bitstream_filter_str->c_str()) 
587                                 : nullptr;
588
589                 CASPAR_VERIFY(!audio_bitstream_filter_str || audio_bitstream_filter);
590
591                 if(audio_bitstream_filter)
592                 {
593                         audio_bitstream_filter_.reset(
594                                 audio_bitstream_filter, 
595                                 av_bitstream_filter_close);
596                 }
597                 
598                 if(audio_bitstream_filter_str && !audio_bitstream_filter_)
599                         options["bsf:a"] = *audio_bitstream_filter_str;
600         }
601         
602         void configue_video_bistream_filters(
603                         std::map<std::string, std::string>& options)
604         {
605                 const auto video_bitstream_filter_str = 
606                                 try_remove_arg<std::string>(
607                                         options, 
608                                         boost::regex("^bsf:v|vbsf$"));
609
610                 const auto video_bitstream_filter = 
611                         video_bitstream_filter_str 
612                                 ? av_bitstream_filter_init(video_bitstream_filter_str->c_str()) 
613                                 : nullptr;
614
615                 CASPAR_VERIFY(!video_bitstream_filter_str || video_bitstream_filter);
616
617                 if(video_bitstream_filter)
618                 {
619                         video_bitstream_filter_.reset(
620                                 video_bitstream_filter, 
621                                 av_bitstream_filter_close);
622                 }
623                 
624                 if(video_bitstream_filter_str && !video_bitstream_filter_)
625                         options["bsf:v"] = *video_bitstream_filter_str;
626         }
627         
628         void configure_video_filters(
629                         const AVCodec& codec,
630                         const std::string& filtergraph)
631         {
632                 video_graph_.reset(
633                                 avfilter_graph_alloc(), 
634                                 [](AVFilterGraph* p)
635                                 {
636                                         avfilter_graph_free(&p);
637                                 });
638                 
639                 video_graph_->nb_threads  = boost::thread::hardware_concurrency()/2;
640                 video_graph_->thread_type = AVFILTER_THREAD_SLICE;
641
642                 const auto sample_aspect_ratio =
643                         boost::rational<int>(
644                                         in_video_format_.square_width,
645                                         in_video_format_.square_height) /
646                         boost::rational<int>(
647                                         in_video_format_.width,
648                                         in_video_format_.height);
649                 
650                 const auto vsrc_options = (boost::format("video_size=%1%x%2%:pix_fmt=%3%:time_base=%4%/%5%:pixel_aspect=%6%/%7%:frame_rate=%8%/%9%")
651                         % in_video_format_.width % in_video_format_.height
652                         % AV_PIX_FMT_BGRA
653                         % in_video_format_.duration     % in_video_format_.time_scale
654                         % sample_aspect_ratio.numerator() % sample_aspect_ratio.denominator()
655                         % in_video_format_.time_scale % in_video_format_.duration).str();
656                                         
657                 AVFilterContext* filt_vsrc = nullptr;                   
658                 FF(avfilter_graph_create_filter(
659                                 &filt_vsrc,
660                                 avfilter_get_by_name("buffer"), 
661                                 "ffmpeg_consumer_buffer",
662                                 vsrc_options.c_str(), 
663                                 nullptr, 
664                                 video_graph_.get()));
665                                 
666                 AVFilterContext* filt_vsink = nullptr;
667                 FF(avfilter_graph_create_filter(
668                                 &filt_vsink,
669                                 avfilter_get_by_name("buffersink"), 
670                                 "ffmpeg_consumer_buffersink",
671                                 nullptr, 
672                                 nullptr, 
673                                 video_graph_.get()));
674                 
675 #pragma warning (push)
676 #pragma warning (disable : 4245)
677
678                 FF(av_opt_set_int_list(
679                                 filt_vsink, 
680                                 "pix_fmts", 
681                                 codec.pix_fmts, 
682                                 -1,
683                                 AV_OPT_SEARCH_CHILDREN));
684
685 #pragma warning (pop)
686                         
687                 configure_filtergraph(
688                                 *video_graph_, 
689                                 filtergraph,
690                                 *filt_vsrc,
691                                 *filt_vsink);
692
693                 video_graph_in_  = filt_vsrc;
694                 video_graph_out_ = filt_vsink;
695                 
696                 CASPAR_LOG(info)
697                         <<      u16(std::string("\n") 
698                                 + avfilter_graph_dump(
699                                                 video_graph_.get(), 
700                                                 nullptr));
701         }
702
703         void configure_audio_filters(
704                         const AVCodec& codec,
705                         const std::string& filtergraph)
706         {
707                 audio_graph_.reset(
708                         avfilter_graph_alloc(), 
709                         [](AVFilterGraph* p)
710                         {
711                                 avfilter_graph_free(&p);
712                         });
713                 
714                 audio_graph_->nb_threads  = boost::thread::hardware_concurrency()/2;
715                 audio_graph_->thread_type = AVFILTER_THREAD_SLICE;
716                 
717                 const auto asrc_options = (boost::format("sample_rate=%1%:sample_fmt=%2%:channels=%3%:time_base=%4%/%5%:channel_layout=%6%")
718                         % in_video_format_.audio_sample_rate
719                         % av_get_sample_fmt_name(AV_SAMPLE_FMT_S32)
720                         % in_video_format_.audio_channels
721                         % 1     % in_video_format_.audio_sample_rate
722                         % boost::io::group(
723                                 std::hex, 
724                                 std::showbase, 
725                                 av_get_default_channel_layout(in_video_format_.audio_channels))).str();
726
727                 AVFilterContext* filt_asrc = nullptr;
728                 FF(avfilter_graph_create_filter(
729                         &filt_asrc,
730                         avfilter_get_by_name("abuffer"), 
731                         "ffmpeg_consumer_abuffer",
732                         asrc_options.c_str(), 
733                         nullptr, 
734                         audio_graph_.get()));
735                                 
736                 AVFilterContext* filt_asink = nullptr;
737                 FF(avfilter_graph_create_filter(
738                         &filt_asink,
739                         avfilter_get_by_name("abuffersink"), 
740                         "ffmpeg_consumer_abuffersink",
741                         nullptr, 
742                         nullptr, 
743                         audio_graph_.get()));
744                 
745 #pragma warning (push)
746 #pragma warning (disable : 4245)
747
748                 FF(av_opt_set_int(
749                         filt_asink,        
750                         "all_channel_counts",
751                         1,      
752                         AV_OPT_SEARCH_CHILDREN));
753
754                 FF(av_opt_set_int_list(
755                         filt_asink, 
756                         "sample_fmts",           
757                         codec.sample_fmts,                              
758                         -1, 
759                         AV_OPT_SEARCH_CHILDREN));
760
761                 FF(av_opt_set_int_list(
762                         filt_asink,
763                         "channel_layouts",       
764                         codec.channel_layouts,                  
765                         -1, 
766                         AV_OPT_SEARCH_CHILDREN));
767
768                 FF(av_opt_set_int_list(
769                         filt_asink, 
770                         "sample_rates" ,         
771                         codec.supported_samplerates,    
772                         -1, 
773                         AV_OPT_SEARCH_CHILDREN));
774
775 #pragma warning (pop)
776                         
777                 configure_filtergraph(
778                         *audio_graph_, 
779                         filtergraph, 
780                         *filt_asrc, 
781                         *filt_asink);
782
783                 audio_graph_in_  = filt_asrc;
784                 audio_graph_out_ = filt_asink;
785
786                 CASPAR_LOG(info) 
787                         <<      u16(std::string("\n") 
788                                 + avfilter_graph_dump(
789                                         audio_graph_.get(), 
790                                         nullptr));
791         }
792
793         void configure_filtergraph(
794                         AVFilterGraph& graph,
795                         const std::string& filtergraph,
796                         AVFilterContext& source_ctx,
797                         AVFilterContext& sink_ctx)
798         {
799                 AVFilterInOut* outputs = nullptr;
800                 AVFilterInOut* inputs = nullptr;
801
802                 try
803                 {
804                         if(!filtergraph.empty())
805                         {
806                                 outputs = avfilter_inout_alloc();
807                                 inputs  = avfilter_inout_alloc();
808
809                                 CASPAR_VERIFY(outputs && inputs);
810
811                                 outputs->name       = av_strdup("in");
812                                 outputs->filter_ctx = &source_ctx;
813                                 outputs->pad_idx    = 0;
814                                 outputs->next       = nullptr;
815
816                                 inputs->name        = av_strdup("out");
817                                 inputs->filter_ctx  = &sink_ctx;
818                                 inputs->pad_idx     = 0;
819                                 inputs->next        = nullptr;
820
821                                 FF(avfilter_graph_parse(
822                                         &graph, 
823                                         filtergraph.c_str(), 
824                                         &inputs, 
825                                         &outputs, 
826                                         nullptr));
827                         } 
828                         else 
829                         {
830                                 FF(avfilter_link(
831                                         &source_ctx, 
832                                         0, 
833                                         &sink_ctx, 
834                                         0));
835                         }
836
837                         FF(avfilter_graph_config(
838                                 &graph, 
839                                 nullptr));
840                 }
841                 catch(...)
842                 {
843                         avfilter_inout_free(&outputs);
844                         avfilter_inout_free(&inputs);
845                         throw;
846                 }
847         }
848         
849         void encode_video(core::const_frame frame_ptr, std::shared_ptr<void> token)
850         {               
851                 if(!video_st_)
852                         return;
853
854                 auto enc = video_st_->codec;
855                         
856                 std::shared_ptr<AVFrame> src_av_frame;
857
858                 if(frame_ptr != core::const_frame::empty())
859                 {
860                         src_av_frame.reset(
861                                 av_frame_alloc(),
862                                 [frame_ptr](AVFrame* frame)
863                                 {
864                                         av_frame_free(&frame);
865                                 });
866
867                         avcodec_get_frame_defaults(src_av_frame.get());         
868                         
869                         const auto sample_aspect_ratio = 
870                                 boost::rational<int>(
871                                         in_video_format_.square_width, 
872                                         in_video_format_.square_height) /
873                                 boost::rational<int>(
874                                         in_video_format_.width, 
875                                         in_video_format_.height);
876
877                         src_av_frame->format                              = AV_PIX_FMT_BGRA;
878                         src_av_frame->width                                       = in_video_format_.width;
879                         src_av_frame->height                              = in_video_format_.height;
880                         src_av_frame->sample_aspect_ratio.num = sample_aspect_ratio.numerator();
881                         src_av_frame->sample_aspect_ratio.den = sample_aspect_ratio.denominator();
882                         src_av_frame->pts                                         = video_pts_;
883
884                         video_pts_ += 1;
885
886                         FF(av_image_fill_arrays(
887                                 src_av_frame->data,
888                                 src_av_frame->linesize,
889                                 frame_ptr.image_data().begin(),
890                                 static_cast<AVPixelFormat>(src_av_frame->format), 
891                                 in_video_format_.width, 
892                                 in_video_format_.height, 
893                                 1));
894
895                         FF(av_buffersrc_add_frame(
896                                 video_graph_in_, 
897                                 src_av_frame.get()));
898                 }               
899
900                 int ret = 0;
901
902                 while(ret >= 0)
903                 {
904                         std::shared_ptr<AVFrame> filt_frame(
905                                 av_frame_alloc(), 
906                                 [](AVFrame* p)
907                                 {
908                                         av_frame_free(&p);
909                                 });
910
911                         ret = av_buffersink_get_frame(
912                                 video_graph_out_, 
913                                 filt_frame.get());
914                                                 
915                         video_encoder_executor_.begin_invoke([=]
916                         {
917                                 if(ret == AVERROR_EOF)
918                                 {
919                                         if(enc->codec->capabilities & CODEC_CAP_DELAY)
920                                         {
921                                                 while(encode_av_frame(
922                                                                 *video_st_, 
923                                                                 video_bitstream_filter_.get(),
924                                                                 avcodec_encode_video2, 
925                                                                 nullptr, token))
926                                                 {
927                                                         boost::this_thread::yield(); // TODO:
928                                                 }
929                                         }               
930                                 }
931                                 else if(ret != AVERROR(EAGAIN))
932                                 {
933                                         FF_RET(ret, "av_buffersink_get_frame");
934                                         
935                                         if (filt_frame->interlaced_frame) 
936                                         {
937                                                 if (enc->codec->id == AV_CODEC_ID_MJPEG)
938                                                         enc->field_order = filt_frame->top_field_first ? AV_FIELD_TT : AV_FIELD_BB;
939                                                 else
940                                                         enc->field_order = filt_frame->top_field_first ? AV_FIELD_TB : AV_FIELD_BT;
941                                         } 
942                                         else
943                                                 enc->field_order = AV_FIELD_PROGRESSIVE;
944
945                                         filt_frame->quality = enc->global_quality;
946
947                                         if (!enc->me_threshold)
948                                                 filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
949                         
950                                         encode_av_frame(
951                                                 *video_st_,
952                                                 video_bitstream_filter_.get(),
953                                                 avcodec_encode_video2,
954                                                 filt_frame, 
955                                                 token);
956
957                                         boost::this_thread::yield(); // TODO:
958                                 }
959                         });
960                 }
961         }
962                                         
963         void encode_audio(core::const_frame frame_ptr, std::shared_ptr<void> token)
964         {               
965                 if(!audio_st_)
966                         return;
967                 
968                 auto enc = audio_st_->codec;
969                         
970                 std::shared_ptr<AVFrame> src_av_frame;
971
972                 if(frame_ptr != core::const_frame::empty())
973                 {
974                         src_av_frame.reset(
975                                 av_frame_alloc(), 
976                                 [](AVFrame* p)
977                                 {
978                                         av_frame_free(&p);
979                                 });
980                 
981                         src_av_frame->channels           = in_video_format_.audio_channels;
982                         src_av_frame->channel_layout = av_get_default_channel_layout(in_video_format_.audio_channels);
983                         src_av_frame->sample_rate        = in_video_format_.audio_sample_rate;
984                         src_av_frame->nb_samples         = static_cast<int>(frame_ptr.audio_data().size()) / src_av_frame->channels;
985                         src_av_frame->format             = AV_SAMPLE_FMT_S32;
986                         src_av_frame->pts                        = audio_pts_;
987
988                         audio_pts_ += src_av_frame->nb_samples;
989
990                         FF(av_samples_fill_arrays(
991                                         src_av_frame->extended_data,
992                                         src_av_frame->linesize,
993                                         reinterpret_cast<const std::uint8_t*>(&*frame_ptr.audio_data().begin()),
994                                         src_av_frame->channels,
995                                         src_av_frame->nb_samples,
996                                         static_cast<AVSampleFormat>(src_av_frame->format),
997                                         16));
998                 
999                         FF(av_buffersrc_add_frame(
1000                                         audio_graph_in_, 
1001                                         src_av_frame.get()));
1002                 }
1003
1004                 int ret = 0;
1005
1006                 while(ret >= 0)
1007                 {
1008                         std::shared_ptr<AVFrame> filt_frame(
1009                                 av_frame_alloc(), 
1010                                 [](AVFrame* p)
1011                                 {
1012                                         av_frame_free(&p);
1013                                 });
1014
1015                         ret = av_buffersink_get_frame(
1016                                 audio_graph_out_, 
1017                                 filt_frame.get());
1018                                         
1019                         audio_encoder_executor_.begin_invoke([=]
1020                         {       
1021                                 if(ret == AVERROR_EOF)
1022                                 {
1023                                         if(enc->codec->capabilities & CODEC_CAP_DELAY)
1024                                         {
1025                                                 while(encode_av_frame(
1026                                                                 *audio_st_, 
1027                                                                 audio_bitstream_filter_.get(), 
1028                                                                 avcodec_encode_audio2, 
1029                                                                 nullptr, 
1030                                                                 token))
1031                                                 {
1032                                                         boost::this_thread::yield(); // TODO:
1033                                                 }
1034                                         }
1035                                 }
1036                                 else if(ret != AVERROR(EAGAIN))
1037                                 {
1038                                         FF_RET(
1039                                                 ret, 
1040                                                 "av_buffersink_get_frame");
1041
1042                                         encode_av_frame(
1043                                                 *audio_st_, 
1044                                                 audio_bitstream_filter_.get(), 
1045                                                 avcodec_encode_audio2, 
1046                                                 filt_frame, 
1047                                                 token);
1048
1049                                         boost::this_thread::yield(); // TODO:
1050                                 }
1051                         });
1052                 }
1053         }
1054         
1055         template<typename F>
1056         bool encode_av_frame(
1057                         AVStream& st,
1058                         AVBitStreamFilterContext* bsfc, 
1059                         const F& func, 
1060                         const std::shared_ptr<AVFrame>& src_av_frame, 
1061                         std::shared_ptr<void> token)
1062         {
1063                 AVPacket pkt = {};
1064                 av_init_packet(&pkt);
1065
1066                 int got_packet = 0;
1067
1068                 FF(func(
1069                         st.codec, 
1070                         &pkt, 
1071                         src_av_frame.get(), 
1072                         &got_packet));
1073                                         
1074                 if(!got_packet || pkt.size <= 0)
1075                         return false;
1076                                 
1077                 pkt.stream_index = st.index;
1078                 
1079                 if(bsfc)
1080                 {
1081                         auto new_pkt = pkt;
1082
1083                         auto a = av_bitstream_filter_filter(
1084                                         bsfc,
1085                                         st.codec,
1086                                         nullptr,
1087                                         &new_pkt.data,
1088                                         &new_pkt.size,
1089                                         pkt.data,
1090                                         pkt.size,
1091                                         pkt.flags & AV_PKT_FLAG_KEY);
1092
1093                         if(a == 0 && new_pkt.data != pkt.data && new_pkt.destruct) 
1094                         {
1095                                 auto t = reinterpret_cast<std::uint8_t*>(av_malloc(new_pkt.size + FF_INPUT_BUFFER_PADDING_SIZE));
1096
1097                                 if(t) 
1098                                 {
1099                                         memcpy(
1100                                                 t, 
1101                                                 new_pkt.data,
1102                                                 new_pkt.size);
1103
1104                                         memset(
1105                                                 t + new_pkt.size, 
1106                                                 0, 
1107                                                 FF_INPUT_BUFFER_PADDING_SIZE);
1108
1109                                         new_pkt.data = t;
1110                                         new_pkt.buf  = nullptr;
1111                                 } 
1112                                 else
1113                                         a = AVERROR(ENOMEM);
1114                         }
1115
1116                         av_free_packet(&pkt);
1117
1118                         FF_RET(
1119                                 a, 
1120                                 "av_bitstream_filter_filter");
1121
1122                         new_pkt.buf =
1123                                 av_buffer_create(
1124                                         new_pkt.data, 
1125                                         new_pkt.size,
1126                                         av_buffer_default_free, 
1127                                         nullptr, 
1128                                         0);
1129
1130                         CASPAR_VERIFY(new_pkt.buf);
1131
1132                         pkt = new_pkt;
1133                 }
1134                 
1135                 if (pkt.pts != AV_NOPTS_VALUE)
1136                 {
1137                         pkt.pts = 
1138                                 av_rescale_q(
1139                                         pkt.pts,
1140                                         st.codec->time_base, 
1141                                         st.time_base);
1142                 }
1143
1144                 if (pkt.dts != AV_NOPTS_VALUE)
1145                 {
1146                         pkt.dts = 
1147                                 av_rescale_q(
1148                                         pkt.dts, 
1149                                         st.codec->time_base, 
1150                                         st.time_base);
1151                 }
1152                                 
1153                 pkt.duration = 
1154                         static_cast<int>(
1155                                 av_rescale_q(
1156                                         pkt.duration, 
1157                                         st.codec->time_base, st.time_base));
1158
1159                 write_packet(
1160                         std::shared_ptr<AVPacket>(
1161                                 new AVPacket(pkt), 
1162                                 [](AVPacket* p)
1163                                 {
1164                                         av_free_packet(p); 
1165                                         delete p;
1166                                 }), token);
1167
1168                 return true;
1169         }
1170
1171         void write_packet(
1172                         const std::shared_ptr<AVPacket>& pkt_ptr,
1173                         std::shared_ptr<void> token)
1174         {               
1175                 write_executor_.begin_invoke([this, pkt_ptr, token]() mutable
1176                 {
1177                         FF(av_interleaved_write_frame(
1178                                 oc_.get(), 
1179                                 pkt_ptr.get()));
1180                 });     
1181         }       
1182         
1183         template<typename T>
1184         static boost::optional<T> try_remove_arg(
1185                         std::map<std::string, std::string>& options, 
1186                         const boost::regex& expr)
1187         {
1188                 for(auto it = options.begin(); it != options.end(); ++it)
1189                 {                       
1190                         if(boost::regex_search(it->first, expr))
1191                         {
1192                                 auto arg = it->second;
1193                                 options.erase(it);
1194                                 return boost::lexical_cast<T>(arg);
1195                         }
1196                 }
1197
1198                 return boost::optional<T>();
1199         }
1200                 
1201         static std::map<std::string, std::string> remove_options(
1202                         std::map<std::string, std::string>& options, 
1203                         const boost::regex& expr)
1204         {
1205                 std::map<std::string, std::string> result;
1206                         
1207                 auto it = options.begin();
1208                 while(it != options.end())
1209                 {                       
1210                         boost::smatch what;
1211                         if(boost::regex_search(it->first, what, expr))
1212                         {
1213                                 result[
1214                                         what.size() > 0 && what[1].matched 
1215                                                 ? what[1].str() 
1216                                                 : it->first] = it->second;
1217                                 it = options.erase(it);
1218                         }
1219                         else
1220                                 ++it;
1221                 }
1222
1223                 return result;
1224         }
1225                 
1226         static void to_dict(AVDictionary** dest, const std::map<std::string, std::string>& c)
1227         {               
1228                 for (const auto& entry : c)
1229                 {
1230                         av_dict_set(
1231                                 dest, 
1232                                 entry.first.c_str(), 
1233                                 entry.second.c_str(), 0);
1234                 }
1235         }
1236
1237         static std::map<std::string, std::string> to_map(AVDictionary* dict)
1238         {
1239                 std::map<std::string, std::string> result;
1240                 
1241                 for(auto t = dict 
1242                                 ? av_dict_get(
1243                                         dict, 
1244                                         "", 
1245                                         nullptr, 
1246                                         AV_DICT_IGNORE_SUFFIX) 
1247                                 : nullptr;
1248                         t; 
1249                         t = av_dict_get(
1250                                 dict, 
1251                                 "", 
1252                                 t,
1253                                 AV_DICT_IGNORE_SUFFIX))
1254                 {
1255                         result[t->key] = t->value;
1256                 }
1257
1258                 return result;
1259         }
1260 };
1261
1262 void describe_streaming_consumer(core::help_sink& sink, const core::help_repository& repo)
1263 {
1264         sink.short_description(L"For streaming the contents of a channel using FFMpeg.");
1265         sink.syntax(L"STREAM [url:string] {-[ffmpeg_param1:string] [value1:string] {-[ffmpeg_param2:string] [value2:string] {...}}}");
1266         sink.para()->text(L"For streaming the contents of a channel using FFMpeg");
1267         sink.definitions()
1268                 ->item(L"url", L"The stream URL to create/stream to.")
1269                 ->item(L"ffmpeg_paramX", L"A parameter supported by FFMpeg. For example vcodec or acodec etc.");
1270         sink.para()->text(L"Examples:");
1271         sink.example(L">> ADD 1 STREAM udp://<client_ip_address>:9250 -format mpegts -vcodec libx264 -crf 25 -tune zerolatency -preset ultrafast");
1272 }
1273
1274 spl::shared_ptr<core::frame_consumer> create_streaming_consumer(
1275                 const std::vector<std::wstring>& params, core::interaction_sink*)
1276 {       
1277         if (params.size() < 1 || params.at(0) != L"STREAM")
1278                 return core::frame_consumer::empty();
1279
1280         auto path = u8(params.at(1));
1281         auto args = u8(boost::join(params, L" "));
1282
1283         return spl::make_shared<streaming_consumer>(path, args);
1284 }
1285
1286 spl::shared_ptr<core::frame_consumer> create_preconfigured_streaming_consumer(
1287                 const boost::property_tree::wptree& ptree, core::interaction_sink*)
1288 {               
1289         return spl::make_shared<streaming_consumer>(
1290                         u8(ptree.get<std::wstring>(L"path")), 
1291                         u8(ptree.get<std::wstring>(L"args", L"")));
1292 }
1293
1294 }}