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