2 * Copyright 2013 Sveriges Television AB http://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"
26 #include "../util/util.h"
27 #include "../util/flv.h"
28 #include "../../ffmpeg_error.h"
29 #include "../../ffmpeg.h"
31 #include <core/video_format.h>
33 #include <common/diagnostics/graph.h>
34 #include <common/executor.h>
35 #include <common/except.h>
36 #include <common/os/general_protection_fault.h>
37 #include <common/param.h>
38 #include <common/scope_exit.h>
40 #include <tbb/concurrent_queue.h>
41 #include <tbb/atomic.h>
42 #include <tbb/recursive_mutex.h>
45 #pragma warning (push)
46 #pragma warning (disable : 4244)
50 #define __STDC_CONSTANT_MACROS
51 #define __STDC_LIMIT_MACROS
52 #include <libavformat/avformat.h>
58 static const size_t MAX_BUFFER_COUNT = 100;
59 static const size_t MAX_BUFFER_COUNT_RT = 3;
60 static const size_t MIN_BUFFER_COUNT = 50;
61 static const size_t MAX_BUFFER_SIZE = 64 * 1000000;
63 namespace caspar { namespace ffmpeg {
64 struct input::impl : boost::noncopyable
66 const spl::shared_ptr<diagnostics::graph> graph_;
68 const spl::shared_ptr<AVFormatContext> format_context_; // Destroy this last
69 const int default_stream_index_ = av_find_default_stream_index(format_context_.get());
71 const std::wstring filename_;
72 tbb::atomic<uint32_t> in_;
73 tbb::atomic<uint32_t> out_;
74 const bool thumbnail_mode_;
75 tbb::atomic<bool> loop_;
76 uint32_t file_frame_number_ = 0;
78 tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>> buffer_;
79 tbb::atomic<size_t> buffer_size_;
83 explicit impl(const spl::shared_ptr<diagnostics::graph> graph, const std::wstring& url_or_file, bool loop, uint32_t in, uint32_t out, bool thumbnail_mode, const ffmpeg_options& vid_params)
85 , format_context_(open_input(url_or_file, vid_params))
86 , filename_(url_or_file)
87 , thumbnail_mode_(thumbnail_mode)
93 enable_quiet_logging_for_thread();
104 graph_->set_color("seek", diagnostics::color(1.0f, 0.5f, 0.0f));
105 graph_->set_color("buffer-count", diagnostics::color(0.7f, 0.4f, 0.4f));
106 graph_->set_color("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f));
111 bool try_pop(std::shared_ptr<AVPacket>& packet)
113 auto result = buffer_.try_pop(packet);
118 buffer_size_ -= packet->size;
122 graph_->set_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);
123 graph_->set_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));
128 std::ptrdiff_t get_max_buffer_count() const
130 return thumbnail_mode_ ? 1 : MAX_BUFFER_COUNT;
133 std::ptrdiff_t get_min_buffer_count() const
135 return thumbnail_mode_ ? 0 : MIN_BUFFER_COUNT;
138 std::future<bool> seek(uint32_t target)
140 if (!executor_.is_running())
141 return make_ready_future(false);
143 return executor_.begin_invoke([=]() -> bool
145 std::shared_ptr<AVPacket> packet;
146 while(buffer_.try_pop(packet) && packet)
147 buffer_size_ -= packet->size;
154 }, task_priority::high_priority);
157 std::wstring print() const
159 return L"ffmpeg_input[" + filename_ + L")]";
164 return (buffer_size_ > MAX_BUFFER_SIZE || buffer_.size() > get_max_buffer_count()) && buffer_.size() > get_min_buffer_count();
169 if(!executor_.is_running())
172 executor_.begin_invoke([this]
179 auto packet = create_packet();
181 auto ret = av_read_frame(format_context_.get(), packet.get()); // packet is only valid until next call of av_read_frame. Use av_dup_packet to extend its life.
185 file_frame_number_ = 0;
190 graph_->set_tag(diagnostics::tag_severity::INFO, "seek");
191 CASPAR_LOG(trace) << print() << " Looping.";
195 // Needed by some decoders to decode remaining frames based on last packet.
196 auto flush_packet = create_packet();
197 flush_packet->data = nullptr;
198 flush_packet->size = 0;
199 flush_packet->pos = -1;
201 buffer_.push(flush_packet);
208 THROW_ON_ERROR(ret, "av_read_frame", print());
210 if(packet->stream_index == default_stream_index_)
211 ++file_frame_number_;
213 THROW_ON_ERROR2(av_dup_packet(packet.get()), print());
215 // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.
216 auto size = packet->size;
217 auto data = packet->data;
219 packet = spl::shared_ptr<AVPacket>(packet.get(), [packet, size, data](AVPacket*)
225 buffer_.try_push(packet);
226 buffer_size_ += packet->size;
228 graph_->set_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);
229 graph_->set_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));
236 if (!thumbnail_mode_)
237 CASPAR_LOG_CURRENT_EXCEPTION();
243 spl::shared_ptr<AVFormatContext> open_input(const std::wstring& url_or_file, const ffmpeg_options& vid_params)
245 AVDictionary* format_options = nullptr;
250 av_dict_free(&format_options);
253 for (auto& option : vid_params)
254 av_dict_set(&format_options, option.first.c_str(), option.second.c_str(), 0);
256 auto resource_name = std::wstring();
257 auto parts = caspar::protocol_split(url_or_file);
258 auto protocol = parts.at(0);
259 auto path = parts.at(1);
260 AVInputFormat* input_format = nullptr;
262 static const std::set<std::wstring> PROTOCOLS_TREATED_AS_FORMATS = { L"dshow", L"v4l2" };
264 if (protocol.empty())
265 resource_name = path;
266 else if (PROTOCOLS_TREATED_AS_FORMATS.find(protocol) != PROTOCOLS_TREATED_AS_FORMATS.end())
268 input_format = av_find_input_format(u8(protocol).c_str());
269 resource_name = path;
272 resource_name = protocol + L"://" + path;
274 AVFormatContext* weak_context = nullptr;
275 THROW_ON_ERROR2(avformat_open_input(&weak_context, u8(resource_name).c_str(), input_format, &format_options), resource_name);
277 spl::shared_ptr<AVFormatContext> context(weak_context, [](AVFormatContext* ptr)
279 avformat_close_input(&ptr);
284 std::string unsupported_tokens = "";
285 AVDictionaryEntry *t = NULL;
286 while ((t = av_dict_get(format_options, "", t, AV_DICT_IGNORE_SUFFIX)) != nullptr)
288 if (!unsupported_tokens.empty())
289 unsupported_tokens += ", ";
290 unsupported_tokens += t->key;
292 CASPAR_THROW_EXCEPTION(user_error() << msg_info(unsupported_tokens));
295 THROW_ON_ERROR2(avformat_find_stream_info(context.get(), nullptr), resource_name);
296 fix_meta_data(*context);
300 void fix_meta_data(AVFormatContext& context)
302 auto video_index = av_find_best_stream(&context, AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);
304 if (video_index > -1)
306 auto video_stream = context.streams[video_index];
307 auto video_context = context.streams[video_index]->codec;
309 if (boost::filesystem::path(context.filename).extension().string() == ".flv")
313 auto meta = read_flv_meta_info(context.filename);
314 double fps = boost::lexical_cast<double>(meta["framerate"]);
315 video_stream->nb_frames = static_cast<int64_t>(boost::lexical_cast<double>(meta["duration"])*fps);
321 auto stream_time = video_stream->time_base;
322 auto duration = video_stream->duration;
323 auto codec_time = video_context->time_base;
324 auto ticks = video_context->ticks_per_frame;
326 if (video_stream->nb_frames == 0)
327 video_stream->nb_frames = (duration*stream_time.num*codec_time.den) / (stream_time.den*codec_time.num*ticks);
332 void queued_seek(const uint32_t target)
334 if (!thumbnail_mode_)
335 CASPAR_LOG(debug) << print() << " Seeking: " << target;
337 auto stream = format_context_->streams[default_stream_index_];
339 auto fps = read_fps(*format_context_, 0.0);
341 THROW_ON_ERROR2(avformat_seek_file(
342 format_context_.get(),
343 default_stream_index_,
344 std::numeric_limits<int64_t>::min(),
345 static_cast<int64_t>((target / fps * stream->time_base.den) / stream->time_base.num),
346 std::numeric_limits<int64_t>::max(),
349 file_frame_number_ = target;
351 auto flush_packet = create_packet();
352 flush_packet->data = nullptr;
353 flush_packet->size = 0;
354 flush_packet->pos = target;
356 buffer_.push(flush_packet);
361 if(ret == AVERROR(EIO))
362 CASPAR_LOG(trace) << print() << " Received EIO, assuming EOF. ";
363 if(ret == AVERROR_EOF)
364 CASPAR_LOG(trace) << print() << " Received EOF. ";
366 return ret == AVERROR_EOF || ret == AVERROR(EIO) || file_frame_number_ >= out_; // av_read_frame doesn't always correctly return AVERROR_EOF;
369 int num_audio_streams() const
375 input::input(const spl::shared_ptr<diagnostics::graph>& graph, const std::wstring& url_or_file, bool loop, uint32_t in, uint32_t out, bool thumbnail_mode, const ffmpeg_options& vid_params)
376 : impl_(new impl(graph, url_or_file, loop, in, out, thumbnail_mode, vid_params)){}
377 bool input::eof() const {return !impl_->executor_.is_running();}
378 bool input::try_pop(std::shared_ptr<AVPacket>& packet){return impl_->try_pop(packet);}
379 spl::shared_ptr<AVFormatContext> input::context(){return impl_->format_context_;}
380 void input::in(uint32_t value){impl_->in_ = value;}
381 uint32_t input::in() const{return impl_->in_;}
382 void input::out(uint32_t value){impl_->out_ = value;}
383 uint32_t input::out() const{return impl_->out_;}
384 void input::length(uint32_t value){impl_->out_ = impl_->in_ + value;}
385 uint32_t input::length() const{return impl_->out_ - impl_->in_;}
386 void input::loop(bool value){impl_->loop_ = value;}
387 bool input::loop() const{return impl_->loop_;}
388 int input::num_audio_streams() const { return impl_->num_audio_streams(); }
389 std::future<bool> input::seek(uint32_t target){return impl_->seek(target);}