2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
4 * This file is part of CasparCG (www.casparcg.com).
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
19 * Author: Robert Nagy, ronag89@gmail.com
22 #include "../../StdAfx.h"
28 #include "../tbb_avcodec.h"
29 #include "../../ffmpeg_error.h"
30 #include "../../ffmpeg.h"
32 #include <tbb/concurrent_unordered_map.h>
33 #include <tbb/concurrent_queue.h>
35 #include <core/frame/frame_transform.h>
36 #include <core/frame/frame_factory.h>
37 #include <core/frame/frame.h>
38 #include <core/frame/audio_channel_layout.h>
39 #include <core/producer/frame_producer.h>
41 #include <common/except.h>
42 #include <common/array.h>
43 #include <common/os/filesystem.h>
44 #include <common/memcpy.h>
46 #include <tbb/parallel_for.h>
48 #include <common/assert.h>
49 #include <boost/filesystem.hpp>
50 #include <boost/lexical_cast.hpp>
51 #include <boost/rational.hpp>
58 #pragma warning (push)
59 #pragma warning (disable : 4244)
63 #include <libswscale/swscale.h>
64 #include <libavcodec/avcodec.h>
65 #include <libavformat/avformat.h>
71 namespace caspar { namespace ffmpeg {
73 core::field_mode get_mode(const AVFrame& frame)
75 if(!frame.interlaced_frame)
76 return core::field_mode::progressive;
78 return frame.top_field_first ? core::field_mode::upper : core::field_mode::lower;
81 core::pixel_format get_pixel_format(PixelFormat pix_fmt)
85 case PIX_FMT_GRAY8: return core::pixel_format::gray;
86 case PIX_FMT_RGB24: return core::pixel_format::rgb;
87 case PIX_FMT_BGR24: return core::pixel_format::bgr;
88 case PIX_FMT_BGRA: return core::pixel_format::bgra;
89 case PIX_FMT_ARGB: return core::pixel_format::argb;
90 case PIX_FMT_RGBA: return core::pixel_format::rgba;
91 case PIX_FMT_ABGR: return core::pixel_format::abgr;
92 case PIX_FMT_YUV444P: return core::pixel_format::ycbcr;
93 case PIX_FMT_YUV422P: return core::pixel_format::ycbcr;
94 case PIX_FMT_YUV420P: return core::pixel_format::ycbcr;
95 case PIX_FMT_YUV411P: return core::pixel_format::ycbcr;
96 case PIX_FMT_YUV410P: return core::pixel_format::ycbcr;
97 case PIX_FMT_YUVA420P: return core::pixel_format::ycbcra;
98 default: return core::pixel_format::invalid;
102 core::pixel_format_desc pixel_format_desc(PixelFormat pix_fmt, int width, int height)
105 AVPicture dummy_pict;
106 avpicture_fill(&dummy_pict, nullptr, pix_fmt, width, height);
108 core::pixel_format_desc desc = get_pixel_format(pix_fmt);
112 case core::pixel_format::gray:
113 case core::pixel_format::luma:
115 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0], height, 1));
118 case core::pixel_format::bgr:
119 case core::pixel_format::rgb:
121 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0]/3, height, 3));
124 case core::pixel_format::bgra:
125 case core::pixel_format::argb:
126 case core::pixel_format::rgba:
127 case core::pixel_format::abgr:
129 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0]/4, height, 4));
132 case core::pixel_format::ycbcr:
133 case core::pixel_format::ycbcra:
135 // Find chroma height
136 int size2 = static_cast<int>(dummy_pict.data[2] - dummy_pict.data[1]);
137 int h2 = size2/dummy_pict.linesize[1];
139 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0], height, 1));
140 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[1], h2, 1));
141 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[2], h2, 1));
143 if(desc.format == core::pixel_format::ycbcra)
144 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[3], height, 1));
148 desc.format = core::pixel_format::invalid;
153 core::mutable_frame make_frame(const void* tag, const spl::shared_ptr<AVFrame>& decoded_frame, core::frame_factory& frame_factory, const core::audio_channel_layout& channel_layout)
155 static tbb::concurrent_unordered_map<int64_t, tbb::concurrent_queue<std::shared_ptr<SwsContext>>> sws_contvalid_exts_;
157 if(decoded_frame->width < 1 || decoded_frame->height < 1)
158 return frame_factory.create_frame(tag, core::pixel_format_desc(core::pixel_format::invalid), core::audio_channel_layout::invalid());
160 const auto width = decoded_frame->width;
161 const auto height = decoded_frame->height;
162 auto desc = pixel_format_desc(static_cast<PixelFormat>(decoded_frame->format), width, height);
164 if(desc.format == core::pixel_format::invalid)
166 auto pix_fmt = static_cast<PixelFormat>(decoded_frame->format);
167 auto target_pix_fmt = PIX_FMT_BGRA;
169 if(pix_fmt == PIX_FMT_UYVY422)
170 target_pix_fmt = PIX_FMT_YUV422P;
171 else if(pix_fmt == PIX_FMT_YUYV422)
172 target_pix_fmt = PIX_FMT_YUV422P;
173 else if(pix_fmt == PIX_FMT_UYYVYY411)
174 target_pix_fmt = PIX_FMT_YUV411P;
175 else if(pix_fmt == PIX_FMT_YUV420P10)
176 target_pix_fmt = PIX_FMT_YUV420P;
177 else if(pix_fmt == PIX_FMT_YUV422P10)
178 target_pix_fmt = PIX_FMT_YUV422P;
179 else if(pix_fmt == PIX_FMT_YUV444P10)
180 target_pix_fmt = PIX_FMT_YUV444P;
182 auto target_desc = pixel_format_desc(target_pix_fmt, width, height);
184 auto write = frame_factory.create_frame(tag, target_desc, channel_layout);
186 std::shared_ptr<SwsContext> sws_context;
188 //CASPAR_LOG(warning) << "Hardware accelerated color transform not supported.";
190 int64_t key = ((static_cast<int64_t>(width) << 32) & 0xFFFF00000000) |
191 ((static_cast<int64_t>(height) << 16) & 0xFFFF0000) |
192 ((static_cast<int64_t>(pix_fmt) << 8) & 0xFF00) |
193 ((static_cast<int64_t>(target_pix_fmt) << 0) & 0xFF);
195 auto& pool = sws_contvalid_exts_[key];
197 if(!pool.try_pop(sws_context))
200 sws_context.reset(sws_getContext(width, height, pix_fmt, width, height, target_pix_fmt, SWS_BILINEAR, nullptr, nullptr, ¶m), sws_freeContext);
205 CASPAR_THROW_EXCEPTION(operation_failed() << msg_info("Could not create software scaling context.") <<
206 boost::errinfo_api_function("sws_getContext"));
209 auto av_frame = create_frame();
210 if(target_pix_fmt == PIX_FMT_BGRA)
212 auto size = avpicture_fill(reinterpret_cast<AVPicture*>(av_frame.get()), write.image_data(0).begin(), PIX_FMT_BGRA, width, height);
213 CASPAR_VERIFY(size == write.image_data(0).size());
217 av_frame->width = width;
218 av_frame->height = height;
219 for(int n = 0; n < target_desc.planes.size(); ++n)
221 av_frame->data[n] = write.image_data(n).begin();
222 av_frame->linesize[n] = target_desc.planes[n].linesize;
226 sws_scale(sws_context.get(), decoded_frame->data, decoded_frame->linesize, 0, height, av_frame->data, av_frame->linesize);
227 pool.push(sws_context);
229 return std::move(write);
233 auto write = frame_factory.create_frame(tag, desc, channel_layout);
235 for(int n = 0; n < static_cast<int>(desc.planes.size()); ++n)
237 auto plane = desc.planes[n];
238 auto result = write.image_data(n).begin();
239 auto decoded = decoded_frame->data[n];
240 auto decoded_linesize = decoded_frame->linesize[n];
242 CASPAR_ASSERT(decoded);
243 CASPAR_ASSERT(write.image_data(n).begin());
245 if (decoded_linesize != plane.linesize)
247 // Copy line by line since ffmpeg sometimes pads each line.
248 tbb::affinity_partitioner ap;
249 tbb::parallel_for(tbb::blocked_range<int>(0, desc.planes[n].height), [&](const tbb::blocked_range<int>& r)
251 for (int y = r.begin(); y != r.end(); ++y)
252 A_memcpy(result + y*plane.linesize, decoded + y*decoded_linesize, plane.linesize);
257 fast_memcpy(result, decoded, plane.size);
261 return std::move(write);
265 spl::shared_ptr<AVFrame> make_av_frame(core::mutable_frame& frame)
267 std::array<uint8_t*, 4> data = {};
268 for(int n = 0; n < frame.pixel_format_desc().planes.size(); ++n)
269 data[n] = frame.image_data(n).begin();
271 return make_av_frame(data, frame.pixel_format_desc());
274 spl::shared_ptr<AVFrame> make_av_frame(std::array<uint8_t*, 4> data, const core::pixel_format_desc& pix_desc)
276 auto av_frame = create_frame();
278 auto planes = pix_desc.planes;
279 auto format = pix_desc.format;
281 av_frame->width = planes[0].width;
282 av_frame->height = planes[0].height;
283 for(int n = 0; n < planes.size(); ++n)
285 av_frame->data[n] = data[n];
286 av_frame->linesize[n] = planes[n].linesize;
291 case core::pixel_format::rgb:
292 av_frame->format = PIX_FMT_RGB24;
294 case core::pixel_format::bgr:
295 av_frame->format = PIX_FMT_BGR24;
297 case core::pixel_format::rgba:
298 av_frame->format = PIX_FMT_RGBA;
300 case core::pixel_format::argb:
301 av_frame->format = PIX_FMT_ARGB;
303 case core::pixel_format::bgra:
304 av_frame->format = PIX_FMT_BGRA;
306 case core::pixel_format::abgr:
307 av_frame->format = PIX_FMT_ABGR;
309 case core::pixel_format::gray:
310 av_frame->format = PIX_FMT_GRAY8;
312 case core::pixel_format::ycbcr:
314 int y_w = planes[0].width;
315 int y_h = planes[0].height;
316 int c_w = planes[1].width;
317 int c_h = planes[1].height;
319 if(c_h == y_h && c_w == y_w)
320 av_frame->format = PIX_FMT_YUV444P;
321 else if(c_h == y_h && c_w*2 == y_w)
322 av_frame->format = PIX_FMT_YUV422P;
323 else if(c_h == y_h && c_w*4 == y_w)
324 av_frame->format = PIX_FMT_YUV411P;
325 else if(c_h*2 == y_h && c_w*2 == y_w)
326 av_frame->format = PIX_FMT_YUV420P;
327 else if(c_h*2 == y_h && c_w*4 == y_w)
328 av_frame->format = PIX_FMT_YUV410P;
332 case core::pixel_format::ycbcra:
333 av_frame->format = PIX_FMT_YUVA420P;
339 bool is_sane_fps(AVRational time_base)
341 double fps = static_cast<double>(time_base.den) / static_cast<double>(time_base.num);
342 return fps > 20.0 && fps < 65.0;
345 AVRational fix_time_base(AVRational time_base)
347 if(time_base.num == 1)
348 time_base.num = static_cast<int>(std::pow(10.0, static_cast<int>(std::log10(static_cast<float>(time_base.den)))-1));
350 if(!is_sane_fps(time_base))
352 auto tmp = time_base;
361 double read_fps(AVFormatContext& context, double fail_value)
363 auto framerate = read_framerate(context, boost::rational<int>(static_cast<int>(fail_value * 1000000.0), 1000000));
365 return static_cast<double>(framerate.numerator()) / static_cast<double>(framerate.denominator());
368 boost::rational<int> read_framerate(AVFormatContext& context, const boost::rational<int>& fail_value)
370 auto video_index = av_find_best_stream(&context, AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);
371 auto audio_index = av_find_best_stream(&context, AVMEDIA_TYPE_AUDIO, -1, -1, 0, 0);
373 if (video_index > -1)
375 const auto video_context = context.streams[video_index]->codec;
376 const auto video_stream = context.streams[video_index];
378 auto frame_rate_time_base = video_stream->avg_frame_rate;
379 std::swap(frame_rate_time_base.num, frame_rate_time_base.den);
381 if (is_sane_fps(frame_rate_time_base))
383 return boost::rational<int>(frame_rate_time_base.den, frame_rate_time_base.num);
386 AVRational time_base = video_context->time_base;
388 if (boost::filesystem::path(context.filename).extension().string() == ".flv")
392 auto meta = read_flv_meta_info(context.filename);
393 return boost::rational<int>(static_cast<int>(boost::lexical_cast<double>(meta["framerate"]) * 1000000.0), 1000000);
402 time_base.num *= video_context->ticks_per_frame;
404 if (!is_sane_fps(time_base))
406 time_base = fix_time_base(time_base);
408 if (!is_sane_fps(time_base) && audio_index > -1)
410 auto& audio_context = *context.streams[audio_index]->codec;
411 auto& audio_stream = *context.streams[audio_index];
413 double duration_sec = audio_stream.duration / static_cast<double>(audio_context.sample_rate);
415 time_base.num = static_cast<int>(duration_sec*100000.0);
416 time_base.den = static_cast<int>(video_stream->nb_frames * 100000);
421 boost::rational<int> fps(time_base.den, time_base.num);
422 boost::rational<int> closest_fps(0);
424 for (auto video_mode : enum_constants<core::video_format>())
426 auto format = core::video_format_desc(core::video_format(video_mode));
428 auto diff1 = boost::abs(boost::rational<int>(format.time_scale, format.duration) - fps);
429 auto diff2 = boost::abs(closest_fps - fps);
432 closest_fps = boost::rational<int>(format.time_scale, format.duration);
441 void fix_meta_data(AVFormatContext& context)
443 auto video_index = av_find_best_stream(&context, AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);
447 auto video_stream = context.streams[video_index];
448 auto video_context = context.streams[video_index]->codec;
450 if(boost::filesystem::path(context.filename).extension().string() == ".flv")
454 auto meta = read_flv_meta_info(context.filename);
455 double fps = boost::lexical_cast<double>(meta["framerate"]);
456 video_stream->nb_frames = static_cast<int64_t>(boost::lexical_cast<double>(meta["duration"])*fps);
462 auto stream_time = video_stream->time_base;
463 auto duration = video_stream->duration;
464 auto codec_time = video_context->time_base;
465 auto ticks = video_context->ticks_per_frame;
467 if(video_stream->nb_frames == 0)
468 video_stream->nb_frames = (duration*stream_time.num*codec_time.den)/(stream_time.den*codec_time.num*ticks);
473 spl::shared_ptr<AVPacket> create_packet()
475 spl::shared_ptr<AVPacket> packet(new AVPacket(), [](AVPacket* p)
481 av_init_packet(packet.get());
485 spl::shared_ptr<AVFrame> create_frame()
487 spl::shared_ptr<AVFrame> frame(av_frame_alloc(), [](AVFrame* p)
494 std::shared_ptr<core::mutable_audio_buffer> flush_audio()
496 static std::shared_ptr<core::mutable_audio_buffer> audio(new core::mutable_audio_buffer());
500 std::shared_ptr<core::mutable_audio_buffer> empty_audio()
502 static std::shared_ptr<core::mutable_audio_buffer> audio(new core::mutable_audio_buffer());
506 std::shared_ptr<AVFrame> flush_video()
508 static auto video = create_frame();
512 std::shared_ptr<AVFrame> empty_video()
514 static auto video = create_frame();
518 spl::shared_ptr<AVCodecContext> open_codec(AVFormatContext& context, enum AVMediaType type, int& index, bool single_threaded)
521 index = THROW_ON_ERROR2(av_find_best_stream(&context, type, index, -1, &decoder, 0), "");
522 //if(strcmp(decoder->name, "prores") == 0 && decoder->next && strcmp(decoder->next->name, "prores_lgpl") == 0)
523 // decoder = decoder->next;
525 THROW_ON_ERROR2(tbb_avcodec_open(context.streams[index]->codec, decoder, single_threaded), "");
526 return spl::shared_ptr<AVCodecContext>(context.streams[index]->codec, tbb_avcodec_close);
529 spl::shared_ptr<AVFormatContext> open_input(const std::wstring& filename)
531 AVFormatContext* weak_context = nullptr;
532 THROW_ON_ERROR2(avformat_open_input(&weak_context, u8(filename).c_str(), nullptr, nullptr), filename);
533 spl::shared_ptr<AVFormatContext> context(weak_context, [](AVFormatContext* p)
535 avformat_close_input(&p);
537 THROW_ON_ERROR2(avformat_find_stream_info(weak_context, nullptr), filename);
538 fix_meta_data(*context);
542 std::wstring print_mode(int width, int height, double fps, bool interlaced)
544 std::wostringstream fps_ss;
545 fps_ss << std::fixed << std::setprecision(2) << (!interlaced ? fps : 2.0 * fps);
547 return boost::lexical_cast<std::wstring>(width) + L"x" + boost::lexical_cast<std::wstring>(height) + (!interlaced ? L"p" : L"i") + fps_ss.str();
550 bool is_valid_file(const std::wstring& filename, bool only_video)
552 static const auto invalid_exts = {
568 static const auto only_audio = {
573 static const auto valid_exts = {
585 auto ext = boost::to_lower_copy(boost::filesystem::path(filename).extension().wstring());
587 if(std::find(valid_exts.begin(), valid_exts.end(), ext) != valid_exts.end())
590 if (!only_video && std::find(only_audio.begin(), only_audio.end(), ext) != only_audio.end())
593 if(std::find(invalid_exts.begin(), invalid_exts.end(), ext) != invalid_exts.end())
596 if (only_video && std::find(only_audio.begin(), only_audio.end(), ext) != only_audio.end())
599 auto u8filename = u8(filename);
603 pb.filename = u8filename.c_str();
605 if(av_probe_input_format2(&pb, false, &score) != nullptr)
608 std::ifstream file(u8filename);
610 std::vector<unsigned char> buf;
611 for(auto file_it = std::istreambuf_iterator<char>(file); file_it != std::istreambuf_iterator<char>() && buf.size() < 1024; ++file_it)
612 buf.push_back(*file_it);
618 pb.buf_size = static_cast<int>(buf.size());
620 return av_probe_input_format2(&pb, true, &score) != nullptr;
623 bool try_get_duration(const std::wstring filename, std::int64_t& duration, boost::rational<std::int64_t>& time_base)
625 AVFormatContext* weak_context = nullptr;
626 if (avformat_open_input(&weak_context, u8(filename).c_str(), nullptr, nullptr) < 0)
629 std::shared_ptr<AVFormatContext> context(weak_context, [](AVFormatContext* p)
631 avformat_close_input(&p);
634 context->probesize = context->probesize / 10;
635 context->max_analyze_duration = context->probesize / 10;
637 if (avformat_find_stream_info(context.get(), nullptr) < 0)
640 const auto fps = read_fps(*context, 1.0);
642 const auto rational_fps = boost::rational<std::int64_t>(static_cast<int>(fps * AV_TIME_BASE), AV_TIME_BASE);
644 duration = boost::rational_cast<std::int64_t>(context->duration * rational_fps / AV_TIME_BASE);
646 if (rational_fps == 0)
649 time_base = 1 / rational_fps;
654 std::wstring probe_stem(const std::wstring& stem, bool only_video)
656 auto stem2 = boost::filesystem::path(stem);
657 auto parent = find_case_insensitive(stem2.parent_path().wstring());
662 auto dir = boost::filesystem::path(*parent);
664 for(auto it = boost::filesystem::directory_iterator(dir); it != boost::filesystem::directory_iterator(); ++it)
666 if(boost::iequals(it->path().stem().wstring(), stem2.filename().wstring()) && is_valid_file(it->path().wstring(), only_video))
667 return it->path().wstring();
672 core::audio_channel_layout get_audio_channel_layout(int num_channels, std::uint64_t layout, const std::wstring& channel_layout_spec)
674 if (!channel_layout_spec.empty())
676 if (boost::contains(channel_layout_spec, L":")) // Custom on the fly layout specified.
678 std::vector<std::wstring> type_and_channel_order;
679 boost::split(type_and_channel_order, channel_layout_spec, boost::is_any_of(L":"), boost::algorithm::token_compress_off);
680 auto& type = type_and_channel_order.at(0);
681 auto& order = type_and_channel_order.at(1);
683 return core::audio_channel_layout(num_channels, std::move(type), order);
685 else // Preconfigured named channel layout selected.
687 auto channel_layout = core::audio_channel_layout_repository::get_default()->get_layout(channel_layout_spec);
690 CASPAR_THROW_EXCEPTION(user_error() << msg_info(L"No channel layout with name " + channel_layout_spec + L" registered"));
692 channel_layout->num_channels = num_channels;
694 return *channel_layout;
700 if (num_channels == 1)
701 return core::audio_channel_layout(num_channels, L"mono", L"FC");
702 else if (num_channels == 2)
703 return core::audio_channel_layout(num_channels, L"stereo", L"FL FR");
705 return core::audio_channel_layout(num_channels, L"", L""); // Passthru without named channels as is.
708 // What FFmpeg calls "channel layout" is only the "layout type" of a channel layout in
709 // CasparCG where the channel layout supports different orders as well.
710 // The user needs to provide additional mix-configs in casparcg.config to support more
711 // than the most common (5.1, mono and stereo) types.
713 // Based on information in https://ffmpeg.org/ffmpeg-utils.html#Channel-Layout
716 case AV_CH_LAYOUT_MONO:
717 return core::audio_channel_layout(num_channels, L"mono", L"FC");
718 case AV_CH_LAYOUT_STEREO:
719 return core::audio_channel_layout(num_channels, L"stereo", L"FL FR");
720 case AV_CH_LAYOUT_2POINT1:
721 return core::audio_channel_layout(num_channels, L"2.1", L"FL FR LFE");
722 case AV_CH_LAYOUT_SURROUND:
723 return core::audio_channel_layout(num_channels, L"3.0", L"FL FR FC");
724 case AV_CH_LAYOUT_2_1:
725 return core::audio_channel_layout(num_channels, L"3.0(back)", L"FL FR BC");
726 case AV_CH_LAYOUT_4POINT0:
727 return core::audio_channel_layout(num_channels, L"4.0", L"FL FR FC BC");
728 case AV_CH_LAYOUT_QUAD:
729 return core::audio_channel_layout(num_channels, L"quad", L"FL FR BL BR");
730 case AV_CH_LAYOUT_2_2:
731 return core::audio_channel_layout(num_channels, L"quad(side)", L"FL FR SL SR");
732 case AV_CH_LAYOUT_3POINT1:
733 return core::audio_channel_layout(num_channels, L"3.1", L"FL FR FC LFE");
734 case AV_CH_LAYOUT_5POINT0_BACK:
735 return core::audio_channel_layout(num_channels, L"5.0", L"FL FR FC BL BR");
736 case AV_CH_LAYOUT_5POINT0:
737 return core::audio_channel_layout(num_channels, L"5.0(side)", L"FL FR FC SL SR");
738 case AV_CH_LAYOUT_4POINT1:
739 return core::audio_channel_layout(num_channels, L"4.1", L"FL FR FC LFE BC");
740 case AV_CH_LAYOUT_5POINT1_BACK:
741 return core::audio_channel_layout(num_channels, L"5.1", L"FL FR FC LFE BL BR");
742 case AV_CH_LAYOUT_5POINT1:
743 return core::audio_channel_layout(num_channels, L"5.1(side)", L"FL FR FC LFE SL SR");
744 case AV_CH_LAYOUT_6POINT0:
745 return core::audio_channel_layout(num_channels, L"6.0", L"FL FR FC BC SL SR");
746 case AV_CH_LAYOUT_6POINT0_FRONT:
747 return core::audio_channel_layout(num_channels, L"6.0(front)", L"FL FR FLC FRC SL SR");
748 case AV_CH_LAYOUT_HEXAGONAL:
749 return core::audio_channel_layout(num_channels, L"hexagonal", L"FL FR FC BL BR BC");
750 case AV_CH_LAYOUT_6POINT1:
751 return core::audio_channel_layout(num_channels, L"6.1", L"FL FR FC LFE BC SL SR");
752 case AV_CH_LAYOUT_6POINT1_BACK:
753 return core::audio_channel_layout(num_channels, L"6.1(back)", L"FL FR FC LFE BL BR BC");
754 case AV_CH_LAYOUT_6POINT1_FRONT:
755 return core::audio_channel_layout(num_channels, L"6.1(front)", L"FL FR LFE FLC FRC SL SR");
756 case AV_CH_LAYOUT_7POINT0:
757 return core::audio_channel_layout(num_channels, L"7.0", L"FL FR FC BL BR SL SR");
758 case AV_CH_LAYOUT_7POINT0_FRONT:
759 return core::audio_channel_layout(num_channels, L"7.0(front)", L"FL FR FC FLC FRC SL SR");
760 case AV_CH_LAYOUT_7POINT1:
761 return core::audio_channel_layout(num_channels, L"7.1", L"FL FR FC LFE BL BR SL SR");
762 case AV_CH_LAYOUT_7POINT1_WIDE_BACK:
763 return core::audio_channel_layout(num_channels, L"7.1(wide)", L"FL FR FC LFE BL BR FLC FRC");
764 case AV_CH_LAYOUT_7POINT1_WIDE:
765 return core::audio_channel_layout(num_channels, L"7.1(wide-side)", L"FL FR FC LFE FLC FRC SL SR");
766 case AV_CH_LAYOUT_STEREO_DOWNMIX:
767 return core::audio_channel_layout(num_channels, L"downmix", L"DL DR");
770 return core::audio_channel_layout(num_channels, L"", L"");
774 // av_get_default_channel_layout does not work for layouts not predefined in ffmpeg. This is needed to support > 8 channels.
775 std::int64_t create_channel_layout_bitmask(int num_channels)
777 if (num_channels > 63)
778 CASPAR_THROW_EXCEPTION(invalid_argument() << msg_info(L"FFmpeg cannot handle more than 63 audio channels"));
780 const auto ALL_63_CHANNELS = 0x7FFFFFFFFFFFFFFFULL;
782 auto to_shift = 63 - num_channels;
783 auto result = ALL_63_CHANNELS >> to_shift;
785 return static_cast<std::int64_t>(result);
788 std::string to_string(const boost::rational<int>& framerate)
790 return boost::lexical_cast<std::string>(framerate.numerator())
791 + "/" + boost::lexical_cast<std::string>(framerate.denominator()) + " (" + boost::lexical_cast<std::string>(static_cast<double>(framerate.numerator()) / static_cast<double>(framerate.denominator())) + ") fps";
794 std::vector<int> find_audio_cadence(const boost::rational<int>& framerate)
796 static std::map<boost::rational<int>, std::vector<int>> CADENCES_BY_FRAMERATE = []
798 std::map<boost::rational<int>, std::vector<int>> result;
800 for (core::video_format format : enum_constants<core::video_format>())
802 core::video_format_desc desc(format);
803 boost::rational<int> format_rate(desc.time_scale, desc.duration);
805 result.insert(std::make_pair(format_rate, desc.audio_cadence));
811 auto exact_match = CADENCES_BY_FRAMERATE.find(framerate);
813 if (exact_match != CADENCES_BY_FRAMERATE.end())
814 return exact_match->second;
816 boost::rational<int> closest_framerate_diff = std::numeric_limits<int>::max();
817 boost::rational<int> closest_framerate = 0;
819 for (auto format_framerate : CADENCES_BY_FRAMERATE | boost::adaptors::map_keys)
821 auto diff = boost::abs(framerate - format_framerate);
823 if (diff < closest_framerate_diff)
825 closest_framerate_diff = diff;
826 closest_framerate = format_framerate;
830 if (is_logging_quiet_for_thread())
831 CASPAR_LOG(debug) << "No exact audio cadence match found for framerate " << to_string(framerate)
832 << "\nClosest match is " << to_string(closest_framerate)
833 << "\nwhich is a " << to_string(closest_framerate_diff) << " difference.";
835 CASPAR_LOG(warning) << "No exact audio cadence match found for framerate " << to_string(framerate)
836 << "\nClosest match is " << to_string(closest_framerate)
837 << "\nwhich is a " << to_string(closest_framerate_diff) << " difference.";
839 return CADENCES_BY_FRAMERATE[closest_framerate];
843 //void av_dup_frame(AVFrame* frame)
845 // AVFrame* new_frame = avcodec_alloc_frame();
848 // const uint8_t *src_data[4] = {0};
849 // memcpy(const_cast<uint8_t**>(&src_data[0]), frame->data, 4);
850 // const int src_linesizes[4] = {0};
851 // memcpy(const_cast<int*>(&src_linesizes[0]), frame->linesize, 4);
853 // av_image_alloc(new_frame->data, new_frame->linesize, new_frame->width, new_frame->height, frame->format, 16);
855 // av_image_copy(new_frame->data, new_frame->linesize, src_data, src_linesizes, frame->format, new_frame->width, new_frame->height);