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"
31 #include <tbb/concurrent_unordered_map.h>
32 #include <tbb/concurrent_queue.h>
34 #include <core/frame/frame_transform.h>
35 #include <core/frame/frame_factory.h>
36 #include <core/frame/frame.h>
37 #include <core/producer/frame_producer.h>
39 #include <common/except.h>
40 #include <common/array.h>
42 #include <tbb/parallel_for.h>
44 #include <common/assert.h>
45 #include <boost/filesystem.hpp>
46 #include <boost/lexical_cast.hpp>
53 #pragma warning (push)
54 #pragma warning (disable : 4244)
58 #include <libswscale/swscale.h>
59 #include <libavcodec/avcodec.h>
60 #include <libavformat/avformat.h>
66 namespace caspar { namespace ffmpeg {
68 core::field_mode get_mode(const AVFrame& frame)
70 if(!frame.interlaced_frame)
71 return core::field_mode::progressive;
73 return frame.top_field_first ? core::field_mode::upper : core::field_mode::lower;
76 core::pixel_format get_pixel_format(PixelFormat pix_fmt)
80 case PIX_FMT_GRAY8: return core::pixel_format::gray;
81 case PIX_FMT_RGB24: return core::pixel_format::rgb;
82 case PIX_FMT_BGR24: return core::pixel_format::bgr;
83 case PIX_FMT_BGRA: return core::pixel_format::bgra;
84 case PIX_FMT_ARGB: return core::pixel_format::argb;
85 case PIX_FMT_RGBA: return core::pixel_format::rgba;
86 case PIX_FMT_ABGR: return core::pixel_format::abgr;
87 case PIX_FMT_YUV444P: return core::pixel_format::ycbcr;
88 case PIX_FMT_YUV422P: return core::pixel_format::ycbcr;
89 case PIX_FMT_YUV420P: return core::pixel_format::ycbcr;
90 case PIX_FMT_YUV411P: return core::pixel_format::ycbcr;
91 case PIX_FMT_YUV410P: return core::pixel_format::ycbcr;
92 case PIX_FMT_YUVA420P: return core::pixel_format::ycbcra;
93 default: return core::pixel_format::invalid;
97 core::pixel_format_desc pixel_format_desc(PixelFormat pix_fmt, int width, int height)
100 AVPicture dummy_pict;
101 avpicture_fill(&dummy_pict, nullptr, pix_fmt, width, height);
103 core::pixel_format_desc desc = get_pixel_format(pix_fmt);
107 case core::pixel_format::gray:
108 case core::pixel_format::luma:
110 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0], height, 1));
113 case core::pixel_format::bgr:
114 case core::pixel_format::rgb:
116 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0]/3, height, 3));
119 case core::pixel_format::bgra:
120 case core::pixel_format::argb:
121 case core::pixel_format::rgba:
122 case core::pixel_format::abgr:
124 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0]/4, height, 4));
127 case core::pixel_format::ycbcr:
128 case core::pixel_format::ycbcra:
130 // Find chroma height
131 int size2 = static_cast<int>(dummy_pict.data[2] - dummy_pict.data[1]);
132 int h2 = size2/dummy_pict.linesize[1];
134 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[0], height, 1));
135 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[1], h2, 1));
136 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[2], h2, 1));
138 if(desc.format == core::pixel_format::ycbcra)
139 desc.planes.push_back(core::pixel_format_desc::plane(dummy_pict.linesize[3], height, 1));
143 desc.format = core::pixel_format::invalid;
148 core::mutable_frame make_frame(const void* tag, const spl::shared_ptr<AVFrame>& decoded_frame, double fps, core::frame_factory& frame_factory)
150 static tbb::concurrent_unordered_map<int64_t, tbb::concurrent_queue<std::shared_ptr<SwsContext>>> sws_contvalid_exts_;
152 if(decoded_frame->width < 1 || decoded_frame->height < 1)
153 return frame_factory.create_frame(tag, core::pixel_format_desc(core::pixel_format::invalid));
155 const auto width = decoded_frame->width;
156 const auto height = decoded_frame->height;
157 auto desc = pixel_format_desc(static_cast<PixelFormat>(decoded_frame->format), width, height);
159 if(desc.format == core::pixel_format::invalid)
161 auto pix_fmt = static_cast<PixelFormat>(decoded_frame->format);
162 auto target_pix_fmt = PIX_FMT_BGRA;
164 if(pix_fmt == PIX_FMT_UYVY422)
165 target_pix_fmt = PIX_FMT_YUV422P;
166 else if(pix_fmt == PIX_FMT_YUYV422)
167 target_pix_fmt = PIX_FMT_YUV422P;
168 else if(pix_fmt == PIX_FMT_UYYVYY411)
169 target_pix_fmt = PIX_FMT_YUV411P;
170 else if(pix_fmt == PIX_FMT_YUV420P10)
171 target_pix_fmt = PIX_FMT_YUV420P;
172 else if(pix_fmt == PIX_FMT_YUV422P10)
173 target_pix_fmt = PIX_FMT_YUV422P;
174 else if(pix_fmt == PIX_FMT_YUV444P10)
175 target_pix_fmt = PIX_FMT_YUV444P;
177 auto target_desc = pixel_format_desc(target_pix_fmt, width, height);
179 auto write = frame_factory.create_frame(tag, target_desc);
181 std::shared_ptr<SwsContext> sws_context;
183 //CASPAR_LOG(warning) << "Hardware accelerated color transform not supported.";
185 int64_t key = ((static_cast<int64_t>(width) << 32) & 0xFFFF00000000) |
186 ((static_cast<int64_t>(height) << 16) & 0xFFFF0000) |
187 ((static_cast<int64_t>(pix_fmt) << 8) & 0xFF00) |
188 ((static_cast<int64_t>(target_pix_fmt) << 0) & 0xFF);
190 auto& pool = sws_contvalid_exts_[key];
192 if(!pool.try_pop(sws_context))
195 sws_context.reset(sws_getContext(width, height, pix_fmt, width, height, target_pix_fmt, SWS_BILINEAR, nullptr, nullptr, ¶m), sws_freeContext);
200 CASPAR_THROW_EXCEPTION(operation_failed() << msg_info("Could not create software scaling context.") <<
201 boost::errinfo_api_function("sws_getContext"));
204 spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
205 avcodec_get_frame_defaults(av_frame.get());
206 if(target_pix_fmt == PIX_FMT_BGRA)
208 auto size = avpicture_fill(reinterpret_cast<AVPicture*>(av_frame.get()), write.image_data(0).begin(), PIX_FMT_BGRA, width, height);
209 CASPAR_VERIFY(size == write.image_data(0).size());
213 av_frame->width = width;
214 av_frame->height = height;
215 for(int n = 0; n < target_desc.planes.size(); ++n)
217 av_frame->data[n] = write.image_data(n).begin();
218 av_frame->linesize[n] = target_desc.planes[n].linesize;
222 sws_scale(sws_context.get(), decoded_frame->data, decoded_frame->linesize, 0, height, av_frame->data, av_frame->linesize);
223 pool.push(sws_context);
225 return std::move(write);
229 auto write = frame_factory.create_frame(tag, desc);
231 for(int n = 0; n < static_cast<int>(desc.planes.size()); ++n)
233 auto plane = desc.planes[n];
234 auto result = write.image_data(n).begin();
235 auto decoded = decoded_frame->data[n];
236 auto decoded_linesize = decoded_frame->linesize[n];
238 CASPAR_ASSERT(decoded);
239 CASPAR_ASSERT(write.image_data(n).begin());
241 // Copy line by line since ffmpeg sometimes pads each line.
242 tbb::affinity_partitioner ap;
243 tbb::parallel_for(tbb::blocked_range<int>(0, desc.planes[n].height), [&](const tbb::blocked_range<int>& r)
245 for(int y = r.begin(); y != r.end(); ++y)
246 A_memcpy(result + y*plane.linesize, decoded + y*decoded_linesize, plane.linesize);
250 return std::move(write);
254 spl::shared_ptr<AVFrame> make_av_frame(core::mutable_frame& frame)
256 std::array<uint8_t*, 4> data = {};
257 for(int n = 0; n < frame.pixel_format_desc().planes.size(); ++n)
258 data[n] = frame.image_data(n).begin();
260 return make_av_frame(data, frame.pixel_format_desc());
263 spl::shared_ptr<AVFrame> make_av_frame(std::array<uint8_t*, 4> data, const core::pixel_format_desc& pix_desc)
265 spl::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);
266 avcodec_get_frame_defaults(av_frame.get());
268 auto planes = pix_desc.planes;
269 auto format = pix_desc.format;
271 av_frame->width = planes[0].width;
272 av_frame->height = planes[0].height;
273 for(int n = 0; n < planes.size(); ++n)
275 av_frame->data[n] = data[n];
276 av_frame->linesize[n] = planes[n].linesize;
281 case core::pixel_format::rgb:
282 av_frame->format = PIX_FMT_RGB24;
284 case core::pixel_format::bgr:
285 av_frame->format = PIX_FMT_BGR24;
287 case core::pixel_format::rgba:
288 av_frame->format = PIX_FMT_RGBA;
290 case core::pixel_format::argb:
291 av_frame->format = PIX_FMT_ARGB;
293 case core::pixel_format::bgra:
294 av_frame->format = PIX_FMT_BGRA;
296 case core::pixel_format::abgr:
297 av_frame->format = PIX_FMT_ABGR;
299 case core::pixel_format::gray:
300 av_frame->format = PIX_FMT_GRAY8;
302 case core::pixel_format::ycbcr:
304 int y_w = planes[0].width;
305 int y_h = planes[0].height;
306 int c_w = planes[1].width;
307 int c_h = planes[1].height;
309 if(c_h == y_h && c_w == y_w)
310 av_frame->format = PIX_FMT_YUV444P;
311 else if(c_h == y_h && c_w*2 == y_w)
312 av_frame->format = PIX_FMT_YUV422P;
313 else if(c_h == y_h && c_w*4 == y_w)
314 av_frame->format = PIX_FMT_YUV411P;
315 else if(c_h*2 == y_h && c_w*2 == y_w)
316 av_frame->format = PIX_FMT_YUV420P;
317 else if(c_h*2 == y_h && c_w*4 == y_w)
318 av_frame->format = PIX_FMT_YUV410P;
322 case core::pixel_format::ycbcra:
323 av_frame->format = PIX_FMT_YUVA420P;
329 bool is_sane_fps(AVRational time_base)
331 double fps = static_cast<double>(time_base.den) / static_cast<double>(time_base.num);
332 return fps > 20.0 && fps < 65.0;
335 AVRational fix_time_base(AVRational time_base)
337 if(time_base.num == 1)
338 time_base.num = static_cast<int>(std::pow(10.0, static_cast<int>(std::log10(static_cast<float>(time_base.den)))-1));
340 if(!is_sane_fps(time_base))
342 auto tmp = time_base;
351 double read_fps(AVFormatContext& context, double fail_value)
353 auto video_index = av_find_best_stream(&context, AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);
354 auto audio_index = av_find_best_stream(&context, AVMEDIA_TYPE_AUDIO, -1, -1, 0, 0);
358 const auto video_context = context.streams[video_index]->codec;
359 const auto video_stream = context.streams[video_index];
361 AVRational time_base = video_context->time_base;
363 if(boost::filesystem::path(context.filename).extension().string() == ".flv")
367 auto meta = read_flv_meta_info(context.filename);
368 return boost::lexical_cast<double>(meta["framerate"]);
377 time_base.num *= video_context->ticks_per_frame;
379 if(!is_sane_fps(time_base))
381 time_base = fix_time_base(time_base);
383 if(!is_sane_fps(time_base) && audio_index > -1)
385 auto& audio_context = *context.streams[audio_index]->codec;
386 auto& audio_stream = *context.streams[audio_index];
388 double duration_sec = audio_stream.duration / static_cast<double>(audio_context.sample_rate);
390 time_base.num = static_cast<int>(duration_sec*100000.0);
391 time_base.den = static_cast<int>(video_stream->nb_frames*100000);
396 double fps = static_cast<double>(time_base.den) / static_cast<double>(time_base.num);
398 double closest_fps = 0.0;
400 for (auto video_mode : enum_constants<core::video_format>())
402 auto format = core::video_format_desc(core::video_format(video_mode));
404 double diff1 = std::abs(format.fps - fps);
405 double diff2 = std::abs(closest_fps - fps);
408 closest_fps = format.fps;
417 void fix_meta_data(AVFormatContext& context)
419 auto video_index = av_find_best_stream(&context, AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);
423 auto video_stream = context.streams[video_index];
424 auto video_context = context.streams[video_index]->codec;
426 if(boost::filesystem::path(context.filename).extension().string() == ".flv")
430 auto meta = read_flv_meta_info(context.filename);
431 double fps = boost::lexical_cast<double>(meta["framerate"]);
432 video_stream->nb_frames = static_cast<int64_t>(boost::lexical_cast<double>(meta["duration"])*fps);
438 auto stream_time = video_stream->time_base;
439 auto duration = video_stream->duration;
440 auto codec_time = video_context->time_base;
441 auto ticks = video_context->ticks_per_frame;
443 if(video_stream->nb_frames == 0)
444 video_stream->nb_frames = (duration*stream_time.num*codec_time.den)/(stream_time.den*codec_time.num*ticks);
449 spl::shared_ptr<AVPacket> create_packet()
451 spl::shared_ptr<AVPacket> packet(new AVPacket(), [](AVPacket* p)
457 av_init_packet(packet.get());
461 spl::shared_ptr<AVFrame> create_frame()
463 spl::shared_ptr<AVFrame> frame(avcodec_alloc_frame(), av_free);
464 avcodec_get_frame_defaults(frame.get());
468 spl::shared_ptr<AVCodecContext> open_codec(AVFormatContext& context, enum AVMediaType type, int& index)
471 index = THROW_ON_ERROR2(av_find_best_stream(&context, type, -1, -1, &decoder, 0), "");
472 //if(strcmp(decoder->name, "prores") == 0 && decoder->next && strcmp(decoder->next->name, "prores_lgpl") == 0)
473 // decoder = decoder->next;
475 THROW_ON_ERROR2(tbb_avcodec_open(context.streams[index]->codec, decoder), "");
476 return spl::shared_ptr<AVCodecContext>(context.streams[index]->codec, tbb_avcodec_close);
479 spl::shared_ptr<AVFormatContext> open_input(const std::wstring& filename)
481 AVFormatContext* weak_context = nullptr;
482 THROW_ON_ERROR2(avformat_open_input(&weak_context, u8(filename).c_str(), nullptr, nullptr), filename);
483 spl::shared_ptr<AVFormatContext> context(weak_context, av_close_input_file);
484 THROW_ON_ERROR2(avformat_find_stream_info(weak_context, nullptr), filename);
485 fix_meta_data(*context);
489 std::wstring print_mode(int width, int height, double fps, bool interlaced)
491 std::wostringstream fps_ss;
492 fps_ss << std::fixed << std::setprecision(2) << (!interlaced ? fps : 2.0 * fps);
494 return boost::lexical_cast<std::wstring>(width) + L"x" + boost::lexical_cast<std::wstring>(height) + (!interlaced ? L"p" : L"i") + fps_ss.str();
497 bool is_valid_file(const std::wstring& filename)
499 static const auto invalid_exts = {
515 static const auto valid_exts = {
529 auto ext = boost::to_lower_copy(boost::filesystem::path(filename).extension().wstring());
531 if(std::find(valid_exts.begin(), valid_exts.end(), ext) != valid_exts.end())
534 if(std::find(invalid_exts.begin(), invalid_exts.end(), ext) != invalid_exts.end())
537 auto u8filename = u8(filename);
541 pb.filename = u8filename.c_str();
543 if(av_probe_input_format2(&pb, false, &score) != nullptr)
546 std::ifstream file(u8filename);
548 std::vector<unsigned char> buf;
549 for(auto file_it = std::istreambuf_iterator<char>(file); file_it != std::istreambuf_iterator<char>() && buf.size() < 1024; ++file_it)
550 buf.push_back(*file_it);
556 pb.buf_size = static_cast<int>(buf.size());
558 return av_probe_input_format2(&pb, true, &score) != nullptr;
561 std::wstring probe_stem(const std::wstring& stem)
563 auto stem2 = boost::filesystem::path(stem);
564 auto dir = stem2.parent_path();
565 for(auto it = boost::filesystem::directory_iterator(dir); it != boost::filesystem::directory_iterator(); ++it)
567 if(boost::iequals(it->path().stem().wstring(), stem2.filename().wstring()) && is_valid_file(it->path().wstring()))
568 return it->path().wstring();
573 //void av_dup_frame(AVFrame* frame)
575 // AVFrame* new_frame = avcodec_alloc_frame();
578 // const uint8_t *src_data[4] = {0};
579 // memcpy(const_cast<uint8_t**>(&src_data[0]), frame->data, 4);
580 // const int src_linesizes[4] = {0};
581 // memcpy(const_cast<int*>(&src_linesizes[0]), frame->linesize, 4);
583 // av_image_alloc(new_frame->data, new_frame->linesize, new_frame->width, new_frame->height, frame->format, 16);
585 // av_image_copy(new_frame->data, new_frame->linesize, src_data, src_linesizes, frame->format, new_frame->width, new_frame->height);