]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/util/util.cpp
* Reenabled unit-test project after move to CMake.
[casparcg] / modules / ffmpeg / producer / util / util.cpp
1 /*
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 */
21
22 #include "../../StdAfx.h"
23
24 #include "util.h"
25
26 #include "flv.h"
27
28 #include "../tbb_avcodec.h"
29 #include "../../ffmpeg_error.h"
30
31 #include <tbb/concurrent_unordered_map.h>
32 #include <tbb/concurrent_queue.h>
33
34 #include <core/frame/frame_transform.h>
35 #include <core/frame/frame_factory.h>
36 #include <core/frame/frame.h>
37 #include <core/frame/audio_channel_layout.h>
38 #include <core/producer/frame_producer.h>
39
40 #include <common/except.h>
41 #include <common/array.h>
42 #include <common/os/filesystem.h>
43
44 #include <tbb/parallel_for.h>
45
46 #include <common/assert.h>
47 #include <boost/filesystem.hpp>
48 #include <boost/lexical_cast.hpp>
49 #include <boost/rational.hpp>
50
51 #include <fstream>
52
53 #include <asmlib.h>
54
55 #if defined(_MSC_VER)
56 #pragma warning (push)
57 #pragma warning (disable : 4244)
58 #endif
59 extern "C" 
60 {
61         #include <libswscale/swscale.h>
62         #include <libavcodec/avcodec.h>
63         #include <libavformat/avformat.h>
64 }
65 #if defined(_MSC_VER)
66 #pragma warning (pop)
67 #endif
68
69 namespace caspar { namespace ffmpeg {
70                 
71 core::field_mode get_mode(const AVFrame& frame)
72 {
73         if(!frame.interlaced_frame)
74                 return core::field_mode::progressive;
75
76         return frame.top_field_first ? core::field_mode::upper : core::field_mode::lower;
77 }
78
79 core::pixel_format get_pixel_format(PixelFormat pix_fmt)
80 {
81         switch(pix_fmt)
82         {
83         case PIX_FMT_GRAY8:                     return core::pixel_format::gray;
84         case PIX_FMT_RGB24:                     return core::pixel_format::rgb;
85         case PIX_FMT_BGR24:                     return core::pixel_format::bgr;
86         case PIX_FMT_BGRA:                      return core::pixel_format::bgra;
87         case PIX_FMT_ARGB:                      return core::pixel_format::argb;
88         case PIX_FMT_RGBA:                      return core::pixel_format::rgba;
89         case PIX_FMT_ABGR:                      return core::pixel_format::abgr;
90         case PIX_FMT_YUV444P:           return core::pixel_format::ycbcr;
91         case PIX_FMT_YUV422P:           return core::pixel_format::ycbcr;
92         case PIX_FMT_YUV420P:           return core::pixel_format::ycbcr;
93         case PIX_FMT_YUV411P:           return core::pixel_format::ycbcr;
94         case PIX_FMT_YUV410P:           return core::pixel_format::ycbcr;
95         case PIX_FMT_YUVA420P:          return core::pixel_format::ycbcra;
96         default:                                        return core::pixel_format::invalid;
97         }
98 }
99
100 core::pixel_format_desc pixel_format_desc(PixelFormat pix_fmt, int width, int height)
101 {
102         // Get linesizes
103         AVPicture dummy_pict;   
104         avpicture_fill(&dummy_pict, nullptr, pix_fmt, width, height);
105
106         core::pixel_format_desc desc = get_pixel_format(pix_fmt);
107                 
108         switch(desc.format)
109         {
110         case core::pixel_format::gray:
111         case core::pixel_format::luma:
112                 {
113                         desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0], height, 1));                                               
114                         return desc;
115                 }
116         case core::pixel_format::bgr:
117         case core::pixel_format::rgb:
118                 {
119                         desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0]/3, height, 3));                                             
120                         return desc;
121                 }
122         case core::pixel_format::bgra:
123         case core::pixel_format::argb:
124         case core::pixel_format::rgba:
125         case core::pixel_format::abgr:
126                 {
127                         desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0]/4, height, 4));                                             
128                         return desc;
129                 }
130         case core::pixel_format::ycbcr:
131         case core::pixel_format::ycbcra:
132                 {               
133                         // Find chroma height
134                         int size2 = static_cast<int>(dummy_pict.data[2] - dummy_pict.data[1]);
135                         int h2 = size2/dummy_pict.linesize[1];                  
136
137                         desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0], height, 1));
138                         desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[1], h2, 1));
139                         desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[2], h2, 1));
140
141                         if(desc.format == core::pixel_format::ycbcra)                                           
142                                 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[3], height, 1));       
143                         return desc;
144                 }               
145         default:                
146                 desc.format = core::pixel_format::invalid;
147                 return desc;
148         }
149 }
150
151 core::mutable_frame make_frame(const void* tag, const spl::shared_ptr<AVFrame>& decoded_frame, double fps, core::frame_factory& frame_factory, const core::audio_channel_layout& channel_layout)
152 {                       
153         static tbb::concurrent_unordered_map<int64_t, tbb::concurrent_queue<std::shared_ptr<SwsContext>>> sws_contvalid_exts_;
154         
155         if(decoded_frame->width < 1 || decoded_frame->height < 1)
156                 return frame_factory.create_frame(tag, core::pixel_format_desc(core::pixel_format::invalid), core::audio_channel_layout::invalid());
157
158         const auto width  = decoded_frame->width;
159         const auto height = decoded_frame->height;
160         auto desc                 = pixel_format_desc(static_cast<PixelFormat>(decoded_frame->format), width, height);
161                 
162         if(desc.format == core::pixel_format::invalid)
163         {
164                 auto pix_fmt = static_cast<PixelFormat>(decoded_frame->format);
165                 auto target_pix_fmt = PIX_FMT_BGRA;
166
167                 if(pix_fmt == PIX_FMT_UYVY422)
168                         target_pix_fmt = PIX_FMT_YUV422P;
169                 else if(pix_fmt == PIX_FMT_YUYV422)
170                         target_pix_fmt = PIX_FMT_YUV422P;
171                 else if(pix_fmt == PIX_FMT_UYYVYY411)
172                         target_pix_fmt = PIX_FMT_YUV411P;
173                 else if(pix_fmt == PIX_FMT_YUV420P10)
174                         target_pix_fmt = PIX_FMT_YUV420P;
175                 else if(pix_fmt == PIX_FMT_YUV422P10)
176                         target_pix_fmt = PIX_FMT_YUV422P;
177                 else if(pix_fmt == PIX_FMT_YUV444P10)
178                         target_pix_fmt = PIX_FMT_YUV444P;
179                 
180                 auto target_desc = pixel_format_desc(target_pix_fmt, width, height);
181
182                 auto write = frame_factory.create_frame(tag, target_desc, channel_layout);
183
184                 std::shared_ptr<SwsContext> sws_context;
185
186                 //CASPAR_LOG(warning) << "Hardware accelerated color transform not supported.";
187                 
188                 int64_t key = ((static_cast<int64_t>(width)                      << 32) & 0xFFFF00000000) | 
189                                           ((static_cast<int64_t>(height)                 << 16) & 0xFFFF0000) | 
190                                           ((static_cast<int64_t>(pix_fmt)                <<  8) & 0xFF00) | 
191                                           ((static_cast<int64_t>(target_pix_fmt) <<  0) & 0xFF);
192                         
193                 auto& pool = sws_contvalid_exts_[key];
194                                                 
195                 if(!pool.try_pop(sws_context))
196                 {
197                         double param;
198                         sws_context.reset(sws_getContext(width, height, pix_fmt, width, height, target_pix_fmt, SWS_BILINEAR, nullptr, nullptr, &param), sws_freeContext);
199                 }
200                         
201                 if(!sws_context)
202                 {
203                         CASPAR_THROW_EXCEPTION(operation_failed() << msg_info("Could not create software scaling context.") << 
204                                                                         boost::errinfo_api_function("sws_getContext"));
205                 }       
206                 
207                 spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);      
208                 avcodec_get_frame_defaults(av_frame.get());                     
209                 if(target_pix_fmt == PIX_FMT_BGRA)
210                 {
211                         auto size = avpicture_fill(reinterpret_cast<AVPicture*>(av_frame.get()), write.image_data(0).begin(), PIX_FMT_BGRA, width, height);
212                         CASPAR_VERIFY(size == write.image_data(0).size()); 
213                 }
214                 else
215                 {
216                         av_frame->width  = width;
217                         av_frame->height = height;
218                         for(int n = 0; n < target_desc.planes.size(); ++n)
219                         {
220                                 av_frame->data[n]               = write.image_data(n).begin();
221                                 av_frame->linesize[n]   = target_desc.planes[n].linesize;
222                         }
223                 }
224
225                 sws_scale(sws_context.get(), decoded_frame->data, decoded_frame->linesize, 0, height, av_frame->data, av_frame->linesize);      
226                 pool.push(sws_context); 
227
228                 return std::move(write);
229         }
230         else
231         {
232                 auto write = frame_factory.create_frame(tag, desc, channel_layout);
233                 
234                 for(int n = 0; n < static_cast<int>(desc.planes.size()); ++n)
235                 {
236                         auto plane            = desc.planes[n];
237                         auto result           = write.image_data(n).begin();
238                         auto decoded          = decoded_frame->data[n];
239                         auto decoded_linesize = decoded_frame->linesize[n];
240                         
241                         CASPAR_ASSERT(decoded);
242                         CASPAR_ASSERT(write.image_data(n).begin());
243
244                         // Copy line by line since ffmpeg sometimes pads each line.
245                         tbb::affinity_partitioner ap;
246                         tbb::parallel_for(tbb::blocked_range<int>(0, desc.planes[n].height), [&](const tbb::blocked_range<int>& r)
247                         {
248                                 for(int y = r.begin(); y != r.end(); ++y)
249                                         A_memcpy(result + y*plane.linesize, decoded + y*decoded_linesize, plane.linesize);
250                         }, ap);
251                 }
252         
253                 return std::move(write);
254         }
255 }
256
257 spl::shared_ptr<AVFrame> make_av_frame(core::mutable_frame& frame)
258 {
259         std::array<uint8_t*, 4> data = {};
260         for(int n = 0; n < frame.pixel_format_desc().planes.size(); ++n)
261                 data[n] = frame.image_data(n).begin();
262
263         return make_av_frame(data, frame.pixel_format_desc());
264 }
265
266 spl::shared_ptr<AVFrame> make_av_frame(std::array<uint8_t*, 4> data, const core::pixel_format_desc& pix_desc)
267 {
268         spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);      
269         avcodec_get_frame_defaults(av_frame.get());
270         
271         auto planes              = pix_desc.planes;
272         auto format              = pix_desc.format;
273
274         av_frame->width  = planes[0].width;
275         av_frame->height = planes[0].height;
276         for(int n = 0; n < planes.size(); ++n)  
277         {
278                 av_frame->data[n]         = data[n];
279                 av_frame->linesize[n] = planes[n].linesize;     
280         }
281
282         switch(format)
283         {
284         case core::pixel_format::rgb:
285                 av_frame->format = PIX_FMT_RGB24;
286                 break;
287         case core::pixel_format::bgr:
288                 av_frame->format = PIX_FMT_BGR24;
289                 break;
290         case core::pixel_format::rgba:
291                 av_frame->format = PIX_FMT_RGBA; 
292                 break;
293         case core::pixel_format::argb:
294                 av_frame->format = PIX_FMT_ARGB; 
295                 break;
296         case core::pixel_format::bgra:
297                 av_frame->format = PIX_FMT_BGRA; 
298                 break;
299         case core::pixel_format::abgr:
300                 av_frame->format = PIX_FMT_ABGR; 
301                 break;
302         case core::pixel_format::gray:
303                 av_frame->format = PIX_FMT_GRAY8; 
304                 break;
305         case core::pixel_format::ycbcr:
306         {
307                 int y_w = planes[0].width;
308                 int y_h = planes[0].height;
309                 int c_w = planes[1].width;
310                 int c_h = planes[1].height;
311
312                 if(c_h == y_h && c_w == y_w)
313                         av_frame->format = PIX_FMT_YUV444P;
314                 else if(c_h == y_h && c_w*2 == y_w)
315                         av_frame->format = PIX_FMT_YUV422P;
316                 else if(c_h == y_h && c_w*4 == y_w)
317                         av_frame->format = PIX_FMT_YUV411P;
318                 else if(c_h*2 == y_h && c_w*2 == y_w)
319                         av_frame->format = PIX_FMT_YUV420P;
320                 else if(c_h*2 == y_h && c_w*4 == y_w)
321                         av_frame->format = PIX_FMT_YUV410P;
322
323                 break;
324         }
325         case core::pixel_format::ycbcra:
326                 av_frame->format = PIX_FMT_YUVA420P;
327                 break;
328         }
329         return av_frame;
330 }
331
332 bool is_sane_fps(AVRational time_base)
333 {
334         double fps = static_cast<double>(time_base.den) / static_cast<double>(time_base.num);
335         return fps > 20.0 && fps < 65.0;
336 }
337
338 AVRational fix_time_base(AVRational time_base)
339 {
340         if(time_base.num == 1)
341                 time_base.num = static_cast<int>(std::pow(10.0, static_cast<int>(std::log10(static_cast<float>(time_base.den)))-1));    
342                         
343         if(!is_sane_fps(time_base))
344         {
345                 auto tmp = time_base;
346                 tmp.den /= 2;
347                 if(is_sane_fps(tmp))
348                         time_base = tmp;
349         }
350
351         return time_base;
352 }
353
354 double read_fps(AVFormatContext& context, double fail_value)
355 {                                               
356         auto video_index = av_find_best_stream(&context, AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);
357         auto audio_index = av_find_best_stream(&context, AVMEDIA_TYPE_AUDIO, -1, -1, 0, 0);
358         
359         if(video_index > -1)
360         {
361                 const auto video_context = context.streams[video_index]->codec;
362                 const auto video_stream  = context.streams[video_index];
363
364                 auto frame_rate_time_base = video_stream->avg_frame_rate;
365                 std::swap(frame_rate_time_base.num, frame_rate_time_base.den);
366
367                 if (is_sane_fps(frame_rate_time_base))
368                 {
369                         return static_cast<double>(frame_rate_time_base.den) / static_cast<double>(frame_rate_time_base.num);
370                 }
371
372                 AVRational time_base = video_context->time_base;
373
374                 if(boost::filesystem::path(context.filename).extension().string() == ".flv")
375                 {
376                         try
377                         {
378                                 auto meta = read_flv_meta_info(context.filename);
379                                 return boost::lexical_cast<double>(meta["framerate"]);
380                         }
381                         catch(...)
382                         {
383                                 return 0.0;
384                         }
385                 }
386                 else
387                 {
388                         time_base.num *= video_context->ticks_per_frame;
389
390                         if(!is_sane_fps(time_base))
391                         {                       
392                                 time_base = fix_time_base(time_base);
393
394                                 if(!is_sane_fps(time_base) && audio_index > -1)
395                                 {
396                                         auto& audio_context = *context.streams[audio_index]->codec;
397                                         auto& audio_stream  = *context.streams[audio_index];
398
399                                         double duration_sec = audio_stream.duration / static_cast<double>(audio_context.sample_rate);
400                                                                 
401                                         time_base.num = static_cast<int>(duration_sec*100000.0);
402                                         time_base.den = static_cast<int>(video_stream->nb_frames*100000);
403                                 }
404                         }
405                 }
406                 
407                 double fps = static_cast<double>(time_base.den) / static_cast<double>(time_base.num);
408
409                 double closest_fps = 0.0;
410
411                 for (auto video_mode : enum_constants<core::video_format>())
412                 {
413                         auto format = core::video_format_desc(core::video_format(video_mode));
414
415                         double diff1 = std::abs(format.fps - fps);
416                         double diff2 = std::abs(closest_fps - fps);
417
418                         if(diff1 < diff2)
419                                 closest_fps = format.fps;
420                 }
421         
422                 return closest_fps;
423         }
424
425         return fail_value;      
426 }
427
428 void fix_meta_data(AVFormatContext& context)
429 {
430         auto video_index = av_find_best_stream(&context, AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);
431
432         if(video_index > -1)
433         {
434                 auto video_stream   = context.streams[video_index];
435                 auto video_context  = context.streams[video_index]->codec;
436                                                 
437                 if(boost::filesystem::path(context.filename).extension().string() == ".flv")
438                 {
439                         try
440                         {
441                                 auto meta = read_flv_meta_info(context.filename);
442                                 double fps = boost::lexical_cast<double>(meta["framerate"]);
443                                 video_stream->nb_frames = static_cast<int64_t>(boost::lexical_cast<double>(meta["duration"])*fps);
444                         }
445                         catch(...){}
446                 }
447                 else
448                 {
449                         auto stream_time = video_stream->time_base;
450                         auto duration    = video_stream->duration;
451                         auto codec_time  = video_context->time_base;
452                         auto ticks               = video_context->ticks_per_frame;
453
454                         if(video_stream->nb_frames == 0)
455                                 video_stream->nb_frames = (duration*stream_time.num*codec_time.den)/(stream_time.den*codec_time.num*ticks);     
456                 }
457         }
458 }
459
460 spl::shared_ptr<AVPacket> create_packet()
461 {
462         spl::shared_ptr<AVPacket> packet(new AVPacket(), [](AVPacket* p)
463         {
464                 av_free_packet(p);
465                 delete p;
466         });
467         
468         av_init_packet(packet.get());
469         return packet;
470 }
471
472 spl::shared_ptr<AVFrame> create_frame()
473 {       
474         spl::shared_ptr<AVFrame> frame(avcodec_alloc_frame(), av_free);
475         avcodec_get_frame_defaults(frame.get());
476         return frame;
477 }
478
479 spl::shared_ptr<AVCodecContext> open_codec(AVFormatContext& context, enum AVMediaType type, int& index)
480 {       
481         AVCodec* decoder;
482         index = THROW_ON_ERROR2(av_find_best_stream(&context, type, -1, -1, &decoder, 0), "");
483         //if(strcmp(decoder->name, "prores") == 0 && decoder->next && strcmp(decoder->next->name, "prores_lgpl") == 0)
484         //      decoder = decoder->next;
485
486         THROW_ON_ERROR2(tbb_avcodec_open(context.streams[index]->codec, decoder), "");
487         return spl::shared_ptr<AVCodecContext>(context.streams[index]->codec, tbb_avcodec_close);
488 }
489
490 spl::shared_ptr<AVFormatContext> open_input(const std::wstring& filename)
491 {
492         AVFormatContext* weak_context = nullptr;
493         THROW_ON_ERROR2(avformat_open_input(&weak_context, u8(filename).c_str(), nullptr, nullptr), filename);
494         spl::shared_ptr<AVFormatContext> context(weak_context, [](AVFormatContext* p)
495         {
496                 avformat_close_input(&p);
497         });
498         THROW_ON_ERROR2(avformat_find_stream_info(weak_context, nullptr), filename);
499         fix_meta_data(*context);
500         return context;
501 }
502
503 std::wstring print_mode(int width, int height, double fps, bool interlaced)
504 {
505         std::wostringstream fps_ss;
506         fps_ss << std::fixed << std::setprecision(2) << (!interlaced ? fps : 2.0 * fps);
507
508         return boost::lexical_cast<std::wstring>(width) + L"x" + boost::lexical_cast<std::wstring>(height) + (!interlaced ? L"p" : L"i") + fps_ss.str();
509 }
510
511 bool is_valid_file(const std::wstring& filename)
512 {                               
513         static const auto invalid_exts = {
514                 L".png",
515                 L".tga",
516                 L".bmp",
517                 L".jpg",
518                 L".jpeg",
519                 L".gif",
520                 L".tiff",
521                 L".tif",
522                 L".jp2",
523                 L".jpx",
524                 L".j2k",
525                 L".j2c",
526                 L".swf",
527                 L".ct"
528         };
529         static const auto valid_exts = {
530                 L".m2t",
531                 L".mov",
532                 L".mp4",
533                 L".dv",
534                 L".flv",
535                 L".mpg",
536                 L".wav",
537                 L".mp3",
538                 L".dnxhd",
539                 L".h264",
540                 L".prores"
541         };
542
543         auto ext = boost::to_lower_copy(boost::filesystem::path(filename).extension().wstring());
544                 
545         if(std::find(valid_exts.begin(), valid_exts.end(), ext) != valid_exts.end())
546                 return true;    
547         
548         if(std::find(invalid_exts.begin(), invalid_exts.end(), ext) != invalid_exts.end())
549                 return false;   
550
551         auto u8filename = u8(filename);
552         
553         int score = 0;
554         AVProbeData pb = {};
555         pb.filename = u8filename.c_str();
556
557         if(av_probe_input_format2(&pb, false, &score) != nullptr)
558                 return true;
559
560         std::ifstream file(u8filename);
561
562         std::vector<unsigned char> buf;
563         for(auto file_it = std::istreambuf_iterator<char>(file); file_it != std::istreambuf_iterator<char>() && buf.size() < 1024; ++file_it)
564                 buf.push_back(*file_it);
565
566         if(buf.empty())
567                 return nullptr;
568
569         pb.buf          = buf.data();
570         pb.buf_size = static_cast<int>(buf.size());
571
572         return av_probe_input_format2(&pb, true, &score) != nullptr;
573 }
574
575 bool try_get_duration(const std::wstring filename, std::int64_t& duration, boost::rational<std::int64_t>& time_base)
576 {
577         AVFormatContext* weak_context = nullptr;
578         if (avformat_open_input(&weak_context, u8(filename).c_str(), nullptr, nullptr) < 0)
579                 return false;
580
581         std::shared_ptr<AVFormatContext> context(weak_context, [](AVFormatContext* p)
582         {
583                 avformat_close_input(&p);
584         });
585
586         context->probesize = context->probesize / 10;
587         context->max_analyze_duration = context->probesize / 10;
588
589         if (avformat_find_stream_info(context.get(), nullptr) < 0)
590                 return false;
591
592         const auto fps = read_fps(*context, 1.0);
593
594         const auto rational_fps = boost::rational<std::int64_t>(static_cast<int>(fps * AV_TIME_BASE), AV_TIME_BASE);
595
596         duration = boost::rational_cast<std::int64_t>(context->duration * rational_fps / AV_TIME_BASE);
597
598         if (rational_fps == 0)
599                 return false;
600
601         time_base = 1 / rational_fps;
602
603         return true;
604 }
605
606 std::wstring probe_stem(const std::wstring& stem)
607 {
608         auto stem2 = boost::filesystem::path(stem);
609         auto parent = find_case_insensitive(stem2.parent_path().wstring());
610
611         if (!parent)
612                 return L"";
613
614         auto dir = boost::filesystem::path(*parent);
615
616         for(auto it = boost::filesystem::directory_iterator(dir); it != boost::filesystem::directory_iterator(); ++it)
617         {
618                 if(boost::iequals(it->path().stem().wstring(), stem2.filename().wstring()) && is_valid_file(it->path().wstring()))
619                         return it->path().wstring();
620         }
621         return L"";
622 }
623
624 core::audio_channel_layout get_audio_channel_layout(const AVCodecContext& codec_context, const std::wstring& channel_layout_spec)
625 {
626         auto num_channels = codec_context.channels;
627
628         if (!channel_layout_spec.empty())
629         {
630                 if (boost::contains(channel_layout_spec, L":")) // Custom on the fly layout specified.
631                 {
632                         std::vector<std::wstring> type_and_channel_order;
633                         boost::split(type_and_channel_order, channel_layout_spec, boost::is_any_of(L":"), boost::algorithm::token_compress_off);
634                         auto& type                      = type_and_channel_order.at(0);
635                         auto& order                     = type_and_channel_order.at(1);
636
637                         return core::audio_channel_layout(num_channels, std::move(type), order);
638                 }
639                 else // Preconfigured named channel layout selected.
640                 {
641                         auto layout = core::audio_channel_layout_repository::get_default()->get_layout(channel_layout_spec);
642
643                         if (!layout)
644                                 CASPAR_THROW_EXCEPTION(invalid_argument() << msg_info(L"No channel layout with name " + channel_layout_spec + L" registered"));
645
646                         layout->num_channels = num_channels;
647
648                         return *layout;
649                 }
650         }
651
652         if (!codec_context.channel_layout)
653         {
654                 if (num_channels == 1)
655                         return core::audio_channel_layout(num_channels, L"mono", L"FC");
656                 else if (num_channels == 2)
657                         return core::audio_channel_layout(num_channels, L"stereo", L"FL FR");
658                 else
659                         return core::audio_channel_layout(num_channels, L"", L""); // Passthru without named channels as is.
660         }
661
662         // What FFMpeg calls "channel layout" is only the "layout type" of a channel layout in
663         // CasparCG where the channel layout supports different orders as well.
664         // The user needs to provide additional mix-configs in casparcg.config to support more
665         // than the most common (5.1, mono and stereo) types.
666
667         // Based on information in https://ffmpeg.org/ffmpeg-utils.html#Channel-Layout
668         switch (codec_context.channel_layout)
669         {
670         case AV_CH_LAYOUT_MONO:
671                 return core::audio_channel_layout(num_channels, L"mono",                        L"FC");
672         case AV_CH_LAYOUT_STEREO:
673                 return core::audio_channel_layout(num_channels, L"stereo",                      L"FL FR");
674         case AV_CH_LAYOUT_2POINT1:
675                 return core::audio_channel_layout(num_channels, L"2.1",                         L"FL FR LFE");
676         case AV_CH_LAYOUT_SURROUND:
677                 return core::audio_channel_layout(num_channels, L"3.0",                         L"FL FR FC");
678         case AV_CH_LAYOUT_2_1:
679                 return core::audio_channel_layout(num_channels, L"3.0(back)",           L"FL FR BC");
680         case AV_CH_LAYOUT_4POINT0:
681                 return core::audio_channel_layout(num_channels, L"4.0",                         L"FL FR FC BC");
682         case AV_CH_LAYOUT_QUAD:
683                 return core::audio_channel_layout(num_channels, L"quad",                        L"FL FR BL BR");
684         case AV_CH_LAYOUT_2_2:
685                 return core::audio_channel_layout(num_channels, L"quad(side)",          L"FL FR SL SR");
686         case AV_CH_LAYOUT_3POINT1:
687                 return core::audio_channel_layout(num_channels, L"3.1",                         L"FL FR FC LFE");
688         case AV_CH_LAYOUT_5POINT0_BACK:
689                 return core::audio_channel_layout(num_channels, L"5.0",                         L"FL FR FC BL BR");
690         case AV_CH_LAYOUT_5POINT0:
691                 return core::audio_channel_layout(num_channels, L"5.0(side)",           L"FL FR FC SL SR");
692         case AV_CH_LAYOUT_4POINT1:
693                 return core::audio_channel_layout(num_channels, L"4.1",                         L"FL FR FC LFE BC");
694         case AV_CH_LAYOUT_5POINT1_BACK:
695                 return core::audio_channel_layout(num_channels, L"5.1",                         L"FL FR FC LFE BL BR");
696         case AV_CH_LAYOUT_5POINT1:
697                 return core::audio_channel_layout(num_channels, L"5.1(side)",           L"FL FR FC LFE SL SR");
698         case AV_CH_LAYOUT_6POINT0:
699                 return core::audio_channel_layout(num_channels, L"6.0",                         L"FL FR FC BC SL SR");
700         case AV_CH_LAYOUT_6POINT0_FRONT:
701                 return core::audio_channel_layout(num_channels, L"6.0(front)",          L"FL FR FLC FRC SL SR");
702         case AV_CH_LAYOUT_HEXAGONAL:
703                 return core::audio_channel_layout(num_channels, L"hexagonal",           L"FL FR FC BL BR BC");
704         case AV_CH_LAYOUT_6POINT1:
705                 return core::audio_channel_layout(num_channels, L"6.1",                         L"FL FR FC LFE BC SL SR");
706         case AV_CH_LAYOUT_6POINT1_BACK:
707                 return core::audio_channel_layout(num_channels, L"6.1(back)",           L"FL FR FC LFE BL BR BC");
708         case AV_CH_LAYOUT_6POINT1_FRONT:
709                 return core::audio_channel_layout(num_channels, L"6.1(front)",          L"FL FR LFE FLC FRC SL SR");
710         case AV_CH_LAYOUT_7POINT0:
711                 return core::audio_channel_layout(num_channels, L"7.0",                         L"FL FR FC BL BR SL SR");
712         case AV_CH_LAYOUT_7POINT0_FRONT:
713                 return core::audio_channel_layout(num_channels, L"7.0(front)",          L"FL FR FC FLC FRC SL SR");
714         case AV_CH_LAYOUT_7POINT1:
715                 return core::audio_channel_layout(num_channels, L"7.1",                         L"FL FR FC LFE BL BR SL SR");
716         case AV_CH_LAYOUT_7POINT1_WIDE_BACK:
717                 return core::audio_channel_layout(num_channels, L"7.1(wide)",           L"FL FR FC LFE BL BR FLC FRC");
718         case AV_CH_LAYOUT_7POINT1_WIDE:
719                 return core::audio_channel_layout(num_channels, L"7.1(wide-side)",      L"FL FR FC LFE FLC FRC SL SR");
720         case AV_CH_LAYOUT_STEREO_DOWNMIX:
721                 return core::audio_channel_layout(num_channels, L"downmix",                     L"DL DR");
722         default:
723                 // Passthru
724                 return core::audio_channel_layout(num_channels, L"", L"");
725         }
726 }
727
728 // av_get_default_channel_layout does not work for layouts not predefined in ffmpeg. This is needed to support > 8 channels.
729 std::int64_t create_channel_layout_bitmask(int num_channels)
730 {
731         if (num_channels > 63)
732                 CASPAR_THROW_EXCEPTION(invalid_argument() << msg_info(L"FFMpeg cannot handle more than 63 audio channels"));
733
734         const auto ALL_63_CHANNELS = 0x7FFFFFFFFFFFFFFFULL;
735
736         auto to_shift = 63 - num_channels;
737         auto result = ALL_63_CHANNELS >> to_shift;
738
739         return static_cast<std::int64_t>(result);
740 }
741
742 //
743 //void av_dup_frame(AVFrame* frame)
744 //{
745 //      AVFrame* new_frame = avcodec_alloc_frame();
746 //
747 //
748 //      const uint8_t *src_data[4] = {0};
749 //      memcpy(const_cast<uint8_t**>(&src_data[0]), frame->data, 4);
750 //      const int src_linesizes[4] = {0};
751 //      memcpy(const_cast<int*>(&src_linesizes[0]), frame->linesize, 4);
752 //
753 //      av_image_alloc(new_frame->data, new_frame->linesize, new_frame->width, new_frame->height, frame->format, 16);
754 //
755 //      av_image_copy(new_frame->data, new_frame->linesize, src_data, src_linesizes, frame->format, new_frame->width, new_frame->height);
756 //
757 //      frame =
758 //}
759
760 }}