]> git.sesse.net Git - casparcg/blobdiff - modules/ffmpeg/consumer/ffmpeg_consumer.cpp
#405 Fixed typo.
[casparcg] / modules / ffmpeg / consumer / ffmpeg_consumer.cpp
index 8689894ed5f763b5e5f8d8e6b855160d5af0abb9..fb2045b6f5cd65f3334e648b53dfae171c96a1f1 100644 (file)
@@ -28,6 +28,7 @@
 #include "../producer/tbb_avcodec.h"
 
 #include <core/frame/frame.h>
+#include <core/frame/audio_channel_layout.h>
 #include <core/mixer/audio/audio_util.h>
 #include <core/consumer/frame_consumer.h>
 #include <core/video_format.h>
@@ -47,6 +48,7 @@
 #include <common/assert.h>
 #include <common/memshfl.h>
 #include <common/timer.h>
+#include <common/ptree.h>
 
 #include <boost/algorithm/string.hpp>
 #include <boost/property_tree/ptree.hpp>
@@ -208,7 +210,7 @@ struct output_format
                        format = av_guess_format(value.c_str(), nullptr, nullptr);
 
                        if(format == nullptr)
-                               CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("f"));
+                               CASPAR_THROW_EXCEPTION(user_error() << msg_info("Unknown format " + value));
 
                        return true;
                }
@@ -216,7 +218,7 @@ struct output_format
                {
                        auto c = avcodec_find_encoder_by_name(value.c_str());
                        if(c == nullptr)
-                               CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("vcodec"));
+                               CASPAR_THROW_EXCEPTION(user_error() << msg_info("Unknown video codec " + value));
 
                        vcodec = avcodec_find_encoder_by_name(value.c_str())->id;
                        return true;
@@ -226,7 +228,7 @@ struct output_format
                {
                        auto c = avcodec_find_encoder_by_name(value.c_str());
                        if(c == nullptr)
-                               CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("acodec"));
+                               CASPAR_THROW_EXCEPTION(user_error() << msg_info("Unknown audio codec " + value));
 
                        acodec = avcodec_find_encoder_by_name(value.c_str())->id;
 
@@ -235,7 +237,7 @@ struct output_format
                else if(name == "s")
                {
                        if(av_parse_video_size(&width, &height, value.c_str()) < 0)
-                               CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("s"));
+                               CASPAR_THROW_EXCEPTION(user_error() << msg_info("Unknown video size " + value));
                        
                        return true;
                }
@@ -261,9 +263,11 @@ typedef cache_aligned_vector<uint8_t> byte_vector;
 struct ffmpeg_consumer : boost::noncopyable
 {              
        const spl::shared_ptr<diagnostics::graph>       graph_;
-       const std::string                                                       filename_;              
+       const std::string                                                       filename_;
+       const std::string                                                       full_filename_          = u8(env::media_folder()) + filename_;
        const std::shared_ptr<AVFormatContext>          oc_                                     { avformat_alloc_context(), avformat_free_context };
-       const core::video_format_desc                           format_desc_;   
+       const core::video_format_desc                           format_desc_;
+       const core::audio_channel_layout                        channel_layout_;
 
        core::monitor::subject                                          monitor_subject_;
        
@@ -287,10 +291,16 @@ struct ffmpeg_consumer : boost::noncopyable
 
        executor                                                                        executor_;
 public:
-       ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, std::vector<option> options, bool key_only)
+       ffmpeg_consumer(
+                       const std::string& filename,
+                       const core::video_format_desc& format_desc,
+                       const core::audio_channel_layout& channel_layout,
+                       std::vector<option> options,
+                       bool key_only)
                : filename_(filename)
                , format_desc_(format_desc)
-               , output_format_(format_desc, filename, options)
+               , channel_layout_(channel_layout)
+               , output_format_(format_desc, full_filename_, options)
                , key_only_(key_only)
                , executor_(print())
        {
@@ -298,7 +308,7 @@ public:
                check_space();
 
                // TODO: Ask stakeholders about case where file already exists.
-               boost::filesystem::remove(boost::filesystem::path(env::media_folder() + u16(filename))); // Delete the file if it exists
+               boost::filesystem::remove(boost::filesystem::path(full_filename_)); // Delete the file if it exists
 
                graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));
                graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
@@ -309,7 +319,7 @@ public:
 
                oc_->oformat = output_format_.format;
                                
-               std::strcpy(oc_->filename, filename_.c_str());
+               std::strcpy(oc_->filename, full_filename_.c_str());
                
                //  Add the audio and video streams using the default format codecs     and initialize the codecs.
                video_st_ = add_video_stream(options);
@@ -317,11 +327,11 @@ public:
                if (!key_only)
                        audio_st_ = add_audio_stream(options);
                                
-               av_dump_format(oc_.get(), 0, filename_.c_str(), 1);
+               av_dump_format(oc_.get(), 0, full_filename_.c_str(), 1);
                 
                // Open the output ffmpeg, if needed.
                if (!(oc_->oformat->flags & AVFMT_NOFILE)) 
-                       THROW_ON_ERROR2(avio_open(&oc_->pb, filename.c_str(), AVIO_FLAG_WRITE), "[ffmpeg_consumer]");
+                       THROW_ON_ERROR2(avio_open(&oc_->pb, full_filename_.c_str(), AVIO_FLAG_WRITE), "[ffmpeg_consumer]");
                                
                THROW_ON_ERROR2(avformat_write_header(oc_.get(), nullptr), "[ffmpeg_consumer]");
 
@@ -330,8 +340,6 @@ public:
                        for (auto& option : options)
                                CASPAR_LOG(warning) << L"Invalid option: -" << u16(option.name) << L" " << u16(option.value);
                }
-
-               CASPAR_LOG(info) << print() << L" Successfully Initialized.";   
        }
 
        ~ffmpeg_consumer()
@@ -354,8 +362,6 @@ public:
                          
                if (!(oc_->oformat->flags & AVFMT_NOFILE)) 
                        LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]");
-
-               CASPAR_LOG(info) << print() << L" Successfully Uninitialized."; 
        }
        
        // frame_consumer
@@ -384,7 +390,7 @@ public:
 
        void mark_dropped()
        {
-               graph_->set_tag("dropped-frame");
+               graph_->set_tag(diagnostics::tag_severity::WARNING, "dropped-frame");
        }
 
        std::wstring print() const
@@ -479,13 +485,11 @@ private:
                if(output_format_.format->flags & AVFMT_GLOBALHEADER)
                        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
                
-               THROW_ON_ERROR2(tbb_avcodec_open(c, encoder), "[ffmpeg_consumer]");
+               THROW_ON_ERROR2(tbb_avcodec_open(c, encoder, false), "[ffmpeg_consumer]");
 
                return std::shared_ptr<AVStream>(st, [](AVStream* st)
                {
                        LOG_ON_ERROR2(tbb_avcodec_close(st->codec), "[ffmpeg_consumer]");
-                       av_freep(&st->codec);
-                       av_freep(&st);
                });
        }
                
@@ -530,8 +534,6 @@ private:
                return std::shared_ptr<AVStream>(st, [](AVStream* st)
                {
                        LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");
-                       av_freep(&st->codec);
-                       av_freep(&st);
                });
        }
   
@@ -545,11 +547,12 @@ private:
                auto av_frame                           = convert_video(frame, enc);
                av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;
                av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper;
-               av_frame->pts                           = frame_number_++;
+               av_frame->pts = frame_number_++;
 
-               monitor_subject_ << core::monitor::message("/frame")
-                               % static_cast<int64_t>(frame_number_)
-                               % static_cast<int64_t>(std::numeric_limits<int64_t>::max());
+               monitor_subject_
+                       << core::monitor::message("/frame") % static_cast<int64_t>(frame_number_)
+                       << core::monitor::message("/path") % filename_
+                       << core::monitor::message("/fps") % format_desc_.fps;
 
                AVPacket pkt;
                av_init_packet(&pkt);
@@ -592,7 +595,7 @@ private:
                        
                while(audio_buffer_.size() >= frame_size)
                {                       
-                       std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
+                       std::shared_ptr<AVFrame> av_frame(av_frame_alloc(), [=](AVFrame* p) { av_frame_free(&p); });
                        avcodec_get_frame_defaults(av_frame.get());             
                        av_frame->nb_samples = frame_size / (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));
 
@@ -691,6 +694,10 @@ private:
                                  out_frame->data, 
                                  out_frame->linesize);
 
+               out_frame->format       = c->pix_fmt;
+               out_frame->width        = c->width;
+               out_frame->height       = c->height;
+
                return out_frame;
        }
        
@@ -700,7 +707,7 @@ private:
                {
                        swr_ = std::shared_ptr<SwrContext>(swr_alloc_set_opts(nullptr,
                                                                                get_channel_layout(c), c->sample_fmt, c->sample_rate,
-                                                                               av_get_default_channel_layout(format_desc_.audio_channels), AV_SAMPLE_FMT_S32, format_desc_.audio_sample_rate,
+                                                                               av_get_default_channel_layout(channel_layout_.num_channels), AV_SAMPLE_FMT_S32, format_desc_.audio_sample_rate,
                                                                                0, nullptr), [](SwrContext* p){swr_free(&p);});
 
                        if(!swr_)
@@ -716,7 +723,7 @@ private:
 
                auto channel_samples = swr_convert(swr_.get(), 
                                                                                   out, static_cast<int>(buffer.size()) / c->channels / av_get_bytes_per_sample(c->sample_fmt), 
-                                                                                  in, static_cast<int>(frame.audio_data().size()/format_desc_.audio_channels));
+                                                                                  in, static_cast<int>(frame.audio_data().size()/channel_layout_.num_channels));
 
                buffer.resize(channel_samples * c->channels * av_get_bytes_per_sample(c->sample_fmt));  
 
@@ -725,9 +732,9 @@ private:
 
        void check_space()
        {
-               auto space = boost::filesystem::space(boost::filesystem::path(filename_).parent_path());
+               auto space = boost::filesystem::space(boost::filesystem::path(full_filename_).parent_path());
                if(space.available < 512*1000000)
-                       BOOST_THROW_EXCEPTION(file_write_error() << msg_info("out of space"));
+                       CASPAR_THROW_EXCEPTION(file_write_error() << msg_info("out of space"));
        }
 
        void encode(const core::const_frame& frame)
@@ -768,24 +775,24 @@ public:
        ffmpeg_consumer_proxy(const std::wstring& filename, const std::vector<option>& options, bool separate_key)
                : filename_(filename)
                , options_(options)
-               , separate_key_(separate_key_)
+               , separate_key_(separate_key)
        {
        }
        
-       void initialize(const core::video_format_desc& format_desc, int) override
+       void initialize(const core::video_format_desc& format_desc, const core::audio_channel_layout& channel_layout, int) override
        {
                if(consumer_)
-                       BOOST_THROW_EXCEPTION(invalid_operation() << msg_info("Cannot reinitialize ffmpeg-consumer."));
+                       CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Cannot reinitialize ffmpeg-consumer."));
 
-               consumer_.reset(new ffmpeg_consumer(u8(filename_), format_desc, options_, false));
+               consumer_.reset(new ffmpeg_consumer(u8(filename_), format_desc, channel_layout, options_, false));
 
                if (separate_key_)
                {
                        boost::filesystem::path fill_file(filename_);
                        auto without_extension = u16(fill_file.stem().string());
-                       auto key_file = env::media_folder() + without_extension + L"_A" + u16(fill_file.extension().string());
+                       auto key_file = without_extension + L"_A" + u16(fill_file.extension().string());
 
-                       key_only_consumer_.reset(new ffmpeg_consumer(u8(key_file), format_desc, options_, true));
+                       key_only_consumer_.reset(new ffmpeg_consumer(u8(key_file), format_desc, channel_layout, options_, true));
                }
        }
 
@@ -861,19 +868,19 @@ public:
 
 void describe_consumer(core::help_sink& sink, const core::help_repository& repo)
 {
-       sink.short_description(L"Can record a channel to a file supported by FFMpeg.");
+       sink.short_description(L"Can record a channel to a file supported by FFmpeg.");
        sink.syntax(L"FILE [filename:string] {-[ffmpeg_param1:string] [value1:string] {-[ffmpeg_param2:string] [value2:string] {...}}} {[separate_key:SEPARATE_KEY]}");
-       sink.para()->text(L"Can record a channel to a file supported by FFMpeg.");
+       sink.para()->text(L"Can record a channel to a file supported by FFmpeg.");
        sink.definitions()
                ->item(L"filename", L"The filename under the media folder including the extension (decides which kind of container format that will be used).")
-               ->item(L"ffmpeg_paramX", L"A parameter supported by FFMpeg. For example vcodec or acodec etc.")
+               ->item(L"ffmpeg_paramX", L"A parameter supported by FFmpeg. For example vcodec or acodec etc.")
                ->item(L"separate_key", L"If defined will create two files simultaneously -- One for fill and one for key (_A will be appended).")
                ;
        sink.para()->text(L"Examples:");
        sink.example(L">> ADD 1 FILE output.mov -vcodec dnxhd");
        sink.example(L">> ADD 1 FILE output.mov -vcodec prores");
        sink.example(L">> ADD 1 FILE output.mov -vcodec dvvideo");
-       sink.example(L">> ADD 1 FILE output.mov - vcodec libx264 -preset ultrafast -tune fastdecode -crf 25");
+       sink.example(L">> ADD 1 FILE output.mov -vcodec libx264 -preset ultrafast -tune fastdecode -crf 25");
        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");
 }
 
@@ -914,20 +921,20 @@ spl::shared_ptr<core::frame_consumer> create_consumer(
                options.push_back(option(name, value));
        }
                                
-       return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + path["PATH"].str(), options, separate_key);
+       return spl::make_shared<ffmpeg_consumer_proxy>(path["PATH"].str(), options, separate_key);
 }
 
 spl::shared_ptr<core::frame_consumer> create_preconfigured_consumer(
                const boost::property_tree::wptree& ptree, core::interaction_sink*)
 {
-       auto filename           = ptree.get<std::wstring>(L"path");
+       auto filename           = ptree_get<std::wstring>(ptree, L"path");
        auto codec                      = ptree.get(L"vcodec", L"libx264");
        auto separate_key       = ptree.get(L"separate-key", false);
 
        std::vector<option> options;
        options.push_back(option("vcodec", u8(codec)));
        
-       return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options, separate_key);
+       return spl::make_shared<ffmpeg_consumer_proxy>(filename, options, separate_key);
 }
 
 }}