]> git.sesse.net Git - casparcg/blobdiff - modules/ffmpeg/producer/util/util.cpp
Updated CHANGES.txt and fixed minor problems
[casparcg] / modules / ffmpeg / producer / util / util.cpp
index ee97d9b5cb55870df59085b1a994b81f87e12b13..92fd8c7f0e29ed4e5aac086782acf16d9e5dea14 100644 (file)
@@ -1,3 +1,24 @@
+/*\r
+* Copyright 2013 Sveriges Television AB http://casparcg.com/\r
+*\r
+* This file is part of CasparCG (www.casparcg.com).\r
+*\r
+* CasparCG is free software: you can redistribute it and/or modify\r
+* it under the terms of the GNU General Public License as published by\r
+* the Free Software Foundation, either version 3 of the License, or\r
+* (at your option) any later version.\r
+*\r
+* CasparCG is distributed in the hope that it will be useful,\r
+* but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+* GNU General Public License for more details.\r
+*\r
+* You should have received a copy of the GNU General Public License\r
+* along with CasparCG. If not, see <http://www.gnu.org/licenses/>.\r
+*\r
+* Author: Robert Nagy, ronag89@gmail.com\r
+*/\r
+\r
 #include "../../stdafx.h"\r
 \r
 #include "util.h"\r
@@ -14,6 +35,7 @@
 #include <core/producer/frame/frame_factory.h>\r
 #include <core/producer/frame_producer.h>\r
 #include <core/mixer/write_frame.h>\r
+#include <core/mixer/audio/audio_util.h>\r
 \r
 #include <common/exception/exceptions.h>\r
 #include <common/utility/assert.h>\r
@@ -23,6 +45,7 @@
 \r
 #include <boost/filesystem.hpp>\r
 #include <boost/lexical_cast.hpp>\r
+#include <boost/algorithm/string.hpp>\r
 \r
 #if defined(_MSC_VER)\r
 #pragma warning (push)\r
@@ -150,12 +173,12 @@ int make_alpha_format(int format)
        }\r
 }\r
 \r
-safe_ptr<core::write_frame> make_write_frame(const void* tag, const safe_ptr<AVFrame>& decoded_frame, const safe_ptr<core::frame_factory>& frame_factory, int hints)\r
+safe_ptr<core::write_frame> make_write_frame(const void* tag, const safe_ptr<AVFrame>& decoded_frame, const safe_ptr<core::frame_factory>& frame_factory, int hints, const core::channel_layout& audio_channel_layout)\r
 {                      \r
-       static tbb::concurrent_unordered_map<size_t, tbb::concurrent_queue<std::shared_ptr<SwsContext>>> sws_contexts_;\r
+       static tbb::concurrent_unordered_map<int64_t, tbb::concurrent_queue<std::shared_ptr<SwsContext>>> sws_contexts_;\r
        \r
        if(decoded_frame->width < 1 || decoded_frame->height < 1)\r
-               return make_safe<core::write_frame>(tag);\r
+               return make_safe<core::write_frame>(tag, audio_channel_layout);\r
 \r
        const auto width  = decoded_frame->width;\r
        const auto height = decoded_frame->height;\r
@@ -169,22 +192,41 @@ safe_ptr<core::write_frame> make_write_frame(const void* tag, const safe_ptr<AVF
        if(desc.pix_fmt == core::pixel_format::invalid)\r
        {\r
                auto pix_fmt = static_cast<PixelFormat>(decoded_frame->format);\r
+               auto target_pix_fmt = PIX_FMT_BGRA;\r
+\r
+               if(pix_fmt == PIX_FMT_UYVY422)\r
+                       target_pix_fmt = PIX_FMT_YUV422P;\r
+               else if(pix_fmt == PIX_FMT_YUYV422)\r
+                       target_pix_fmt = PIX_FMT_YUV422P;\r
+               else if(pix_fmt == PIX_FMT_UYYVYY411)\r
+                       target_pix_fmt = PIX_FMT_YUV411P;\r
+               else if(pix_fmt == PIX_FMT_YUV420P10)\r
+                       target_pix_fmt = PIX_FMT_YUV420P;\r
+               else if(pix_fmt == PIX_FMT_YUV422P10)\r
+                       target_pix_fmt = PIX_FMT_YUV422P;\r
+               else if(pix_fmt == PIX_FMT_YUV444P10)\r
+                       target_pix_fmt = PIX_FMT_YUV444P;\r
+               \r
+               auto target_desc = get_pixel_format_desc(target_pix_fmt, width, height);\r
 \r
-               write = frame_factory->create_frame(tag, get_pixel_format_desc(PIX_FMT_BGRA, width, height));\r
+               write = frame_factory->create_frame(tag, target_desc, audio_channel_layout);\r
                write->set_type(get_mode(*decoded_frame));\r
 \r
                std::shared_ptr<SwsContext> sws_context;\r
 \r
                //CASPAR_LOG(warning) << "Hardware accelerated color transform not supported.";\r
-\r
-               size_t key = width << 20 | height << 8 | pix_fmt;\r
+               \r
+               int64_t key = ((static_cast<int64_t>(width)                      << 32) & 0xFFFF00000000) | \r
+                                         ((static_cast<int64_t>(height)                 << 16) & 0xFFFF0000) | \r
+                                         ((static_cast<int64_t>(pix_fmt)                <<  8) & 0xFF00) | \r
+                                         ((static_cast<int64_t>(target_pix_fmt) <<  0) & 0xFF);\r
                        \r
                auto& pool = sws_contexts_[key];\r
                                                \r
                if(!pool.try_pop(sws_context))\r
                {\r
                        double param;\r
-                       sws_context.reset(sws_getContext(width, height, pix_fmt, width, height, PIX_FMT_BGRA, SWS_BILINEAR, nullptr, nullptr, &param), sws_freeContext);\r
+                       sws_context.reset(sws_getContext(width, height, pix_fmt, width, height, target_pix_fmt, SWS_BILINEAR, nullptr, nullptr, &param), sws_freeContext);\r
                }\r
                        \r
                if(!sws_context)\r
@@ -192,21 +234,33 @@ safe_ptr<core::write_frame> make_write_frame(const void* tag, const safe_ptr<AVF
                        BOOST_THROW_EXCEPTION(operation_failed() << msg_info("Could not create software scaling context.") << \r
                                                                        boost::errinfo_api_function("sws_getContext"));\r
                }       \r
-\r
-               // Use sws_scale when provided colorspace has no hw-accel.\r
+               \r
                safe_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);     \r
                avcodec_get_frame_defaults(av_frame.get());                     \r
-               auto size = avpicture_fill(reinterpret_cast<AVPicture*>(av_frame.get()), write->image_data().begin(), PIX_FMT_BGRA, width, height);\r
-               CASPAR_VERIFY(size == write->image_data().size()); \r
+               if(target_pix_fmt == PIX_FMT_BGRA)\r
+               {\r
+                       auto size = avpicture_fill(reinterpret_cast<AVPicture*>(av_frame.get()), write->image_data().begin(), PIX_FMT_BGRA, width, height);\r
+                       CASPAR_VERIFY(size == write->image_data().size()); \r
+               }\r
+               else\r
+               {\r
+                       av_frame->width  = width;\r
+                       av_frame->height = height;\r
+                       for(size_t n = 0; n < target_desc.planes.size(); ++n)\r
+                       {\r
+                               av_frame->data[n]               = write->image_data(n).begin();\r
+                               av_frame->linesize[n]   = target_desc.planes[n].linesize;\r
+                       }\r
+               }\r
 \r
                sws_scale(sws_context.get(), decoded_frame->data, decoded_frame->linesize, 0, height, av_frame->data, av_frame->linesize);      \r
                pool.push(sws_context);\r
 \r
-               write->commit();\r
+               write->commit();                \r
        }\r
        else\r
        {\r
-               write = frame_factory->create_frame(tag, desc);\r
+               write = frame_factory->create_frame(tag, desc, audio_channel_layout);\r
                write->set_type(get_mode(*decoded_frame));\r
 \r
                for(int n = 0; n < static_cast<int>(desc.planes.size()); ++n)\r
@@ -219,7 +273,7 @@ safe_ptr<core::write_frame> make_write_frame(const void* tag, const safe_ptr<AVF
                        CASPAR_ASSERT(decoded);\r
                        CASPAR_ASSERT(write->image_data(n).begin());\r
 \r
-                       if(decoded_linesize != static_cast<int>(plane.width))\r
+                       if(decoded_linesize != static_cast<int>(plane.linesize))\r
                        {\r
                                // Copy line by line since ffmpeg sometimes pads each line.\r
                                tbb::parallel_for<size_t>(0, desc.planes[n].height, [&](size_t y)\r
@@ -282,7 +336,15 @@ double read_fps(AVFormatContext& context, double fail_value)
        {\r
                const auto video_context = context.streams[video_index]->codec;\r
                const auto video_stream  = context.streams[video_index];\r
-                                               \r
+                               \r
+               auto frame_rate_time_base = video_stream->avg_frame_rate;\r
+               std::swap(frame_rate_time_base.num, frame_rate_time_base.den);\r
+\r
+               if(is_sane_fps(frame_rate_time_base))\r
+               {\r
+                       return static_cast<double>(frame_rate_time_base.den) / static_cast<double>(frame_rate_time_base.num);\r
+               }\r
+\r
                AVRational time_base = video_context->time_base;\r
 \r
                if(boost::filesystem2::path(context.filename).extension() == ".flv")\r
@@ -338,31 +400,6 @@ double read_fps(AVFormatContext& context, double fail_value)
        return fail_value;      \r
 }\r
 \r
-void fix_meta_data(AVFormatContext& context)\r
-{\r
-       auto video_index = av_find_best_stream(&context, AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);\r
-\r
-       if(video_index > -1)\r
-       {\r
-               auto video_stream   = context.streams[video_index];\r
-               auto video_context  = context.streams[video_index]->codec;\r
-                                               \r
-               if(boost::filesystem2::path(context.filename).extension() == ".flv")\r
-               {\r
-                       try\r
-                       {\r
-                               auto meta = read_flv_meta_info(context.filename);\r
-                               double fps = boost::lexical_cast<double>(meta["framerate"]);\r
-                               video_stream->nb_frames = static_cast<int64_t>(boost::lexical_cast<double>(meta["duration"])*fps);\r
-                       }\r
-                       catch(...){}\r
-               }\r
-               else\r
-               {\r
-                       video_stream->nb_frames = (video_stream->duration*video_stream->time_base.num*video_context->time_base.den)/(video_stream->time_base.den*video_context->time_base.num*video_context->ticks_per_frame);          }\r
-       }\r
-}\r
-\r
 safe_ptr<AVPacket> create_packet()\r
 {\r
        safe_ptr<AVPacket> packet(new AVPacket, [](AVPacket* p)\r
@@ -386,16 +423,6 @@ safe_ptr<AVCodecContext> open_codec(AVFormatContext& context, enum AVMediaType t
        return safe_ptr<AVCodecContext>(context.streams[index]->codec, tbb_avcodec_close);\r
 }\r
 \r
-safe_ptr<AVFormatContext> open_input(const std::wstring& filename)\r
-{\r
-       AVFormatContext* weak_context = nullptr;\r
-       THROW_ON_ERROR2(avformat_open_input(&weak_context, narrow(filename).c_str(), nullptr, nullptr), filename);\r
-       safe_ptr<AVFormatContext> context(weak_context, av_close_input_file);                   \r
-       THROW_ON_ERROR2(avformat_find_stream_info(weak_context, nullptr), filename);\r
-       fix_meta_data(*context);\r
-       return context;\r
-}\r
-\r
 std::wstring print_mode(size_t width, size_t height, double fps, bool interlaced)\r
 {\r
        std::wostringstream fps_ss;\r
@@ -403,6 +430,136 @@ std::wstring print_mode(size_t width, size_t height, double fps, bool interlaced
 \r
        return boost::lexical_cast<std::wstring>(width) + L"x" + boost::lexical_cast<std::wstring>(height) + (!interlaced ? L"p" : L"i") + fps_ss.str();\r
 }\r
+\r
+bool is_valid_file(const std::wstring filename, const std::vector<std::wstring>& invalid_exts)\r
+{\r
+       static std::vector<std::wstring> valid_exts = boost::assign::list_of(L".m2t")(L".mov")(L".mp4")(L".dv")(L".flv")(L".mpg")(L".wav")(L".mp3")(L".dnxhd")(L".h264")(L".prores");\r
+\r
+       auto ext = boost::to_lower_copy(boost::filesystem::wpath(filename).extension());\r
+               \r
+       if(std::find(invalid_exts.begin(), invalid_exts.end(), ext) != invalid_exts.end())\r
+               return false;   \r
+\r
+       if(std::find(valid_exts.begin(), valid_exts.end(), ext) != valid_exts.end())\r
+               return true;    \r
+\r
+       auto filename2 = narrow(filename);\r
+\r
+       if(boost::filesystem::path(filename2).extension() == ".m2t")\r
+               return true;\r
+\r
+       std::ifstream file(filename);\r
+\r
+       std::vector<unsigned char> buf;\r
+       for(auto file_it = std::istreambuf_iterator<char>(file); file_it != std::istreambuf_iterator<char>() && buf.size() < 2048; ++file_it)\r
+               buf.push_back(*file_it);\r
+\r
+       if(buf.empty())\r
+               return nullptr;\r
+\r
+       AVProbeData pb;\r
+       pb.filename = filename2.c_str();\r
+       pb.buf          = buf.data();\r
+       pb.buf_size = buf.size();\r
+\r
+       int score = 0;\r
+       return av_probe_input_format2(&pb, true, &score) != nullptr;\r
+}\r
+\r
+bool is_valid_file(const std::wstring filename)\r
+{\r
+       static const std::vector<std::wstring> invalid_exts = boost::assign::list_of(L".png")(L".tga")(L".bmp")(L".jpg")(L".jpeg")(L".gif")(L".tiff")(L".tif")(L".jp2")(L".jpx")(L".j2k")(L".j2c")(L".swf")(L".ct");\r
+       \r
+       return is_valid_file(filename, invalid_exts);\r
+}\r
+\r
+bool try_get_duration(const std::wstring filename, std::int64_t& duration, boost::rational<std::int64_t>& time_base)\r
+{              \r
+       AVFormatContext* weak_context = nullptr;\r
+       if(avformat_open_input(&weak_context, narrow(filename).c_str(), nullptr, nullptr) < 0)\r
+               return false;\r
+\r
+       std::shared_ptr<AVFormatContext> context(weak_context, av_close_input_file);\r
+       \r
+       context->probesize = context->probesize / 10;\r
+       context->max_analyze_duration = context->probesize / 10;\r
+\r
+       if(avformat_find_stream_info(context.get(), nullptr) < 0)\r
+               return false;\r
+\r
+       const auto fps = read_fps(*context, 1.0);\r
+               \r
+       const auto rational_fps = boost::rational<std::int64_t>(static_cast<int>(fps * AV_TIME_BASE), AV_TIME_BASE);\r
+       \r
+       duration = boost::rational_cast<std::int64_t>(context->duration * rational_fps / AV_TIME_BASE);\r
+\r
+       if (rational_fps == 0)\r
+               return false;\r
+\r
+       time_base = 1/rational_fps;\r
+\r
+       return true;\r
+}\r
+\r
+std::wstring probe_stem(const std::wstring stem, const std::vector<std::wstring>& invalid_exts)\r
+{\r
+       auto stem2 = boost::filesystem2::wpath(stem);\r
+       auto dir = stem2.parent_path();\r
+       for(auto it = boost::filesystem2::wdirectory_iterator(dir); it != boost::filesystem2::wdirectory_iterator(); ++it)\r
+       {\r
+               if(boost::iequals(it->path().stem(), stem2.filename()) && is_valid_file(it->path().file_string(), invalid_exts))\r
+                       return it->path().file_string();\r
+       }\r
+       return L"";\r
+}\r
+\r
+std::wstring probe_stem(const std::wstring stem)\r
+{\r
+       auto stem2 = boost::filesystem2::wpath(stem);\r
+       auto dir = stem2.parent_path();\r
+       for(auto it = boost::filesystem2::wdirectory_iterator(dir); it != boost::filesystem2::wdirectory_iterator(); ++it)\r
+       {\r
+               if(boost::iequals(it->path().stem(), stem2.filename()) && is_valid_file(it->path().file_string()))\r
+                       return it->path().file_string();\r
+       }\r
+       return L"";\r
+}\r
+\r
+core::channel_layout get_audio_channel_layout(\r
+               const AVCodecContext& context, const std::wstring& custom_channel_order)\r
+{\r
+       if (!custom_channel_order.empty())\r
+       {\r
+               auto layout = core::create_custom_channel_layout(\r
+                               custom_channel_order,\r
+                               core::default_channel_layout_repository());\r
+\r
+               layout.num_channels = context.channels;\r
+\r
+               return layout;\r
+       }\r
+\r
+       int64_t ch_layout = context.channel_layout;\r
+\r
+       if (ch_layout == 0)\r
+               ch_layout = av_get_default_channel_layout(context.channels);\r
+\r
+       switch (ch_layout) // TODO: refine this auto-detection\r
+       {\r
+       case AV_CH_LAYOUT_MONO:\r
+               return core::default_channel_layout_repository().get_by_name(L"MONO");\r
+       case AV_CH_LAYOUT_STEREO:\r
+               return core::default_channel_layout_repository().get_by_name(L"STEREO");\r
+       case AV_CH_LAYOUT_5POINT1:\r
+       case AV_CH_LAYOUT_5POINT1_BACK:\r
+               return core::default_channel_layout_repository().get_by_name(L"SMPTE");\r
+       case AV_CH_LAYOUT_7POINT1:\r
+               return core::default_channel_layout_repository().get_by_name(L"DOLBYE");\r
+       }\r
+\r
+       return core::create_unspecified_layout(context.channels);\r
+}\r
+\r
 //\r
 //void av_dup_frame(AVFrame* frame)\r
 //{\r