]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input/input.cpp
72648037d8d9704374ebaacf0e3ee89d3dc3394e
[casparcg] / modules / ffmpeg / producer / input / input.cpp
1 /*
2 * Copyright 2013 Sveriges Television AB http://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 "input.h"
25
26 #include "../util/util.h"
27 #include "../util/flv.h"
28 #include "../../ffmpeg_error.h"
29 #include "../../ffmpeg.h"
30
31 #include <core/video_format.h>
32
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>
39
40 #include <tbb/concurrent_queue.h>
41 #include <tbb/atomic.h>
42 #include <tbb/recursive_mutex.h>
43
44 #include <boost/rational.hpp>
45 #include <boost/range/algorithm.hpp>
46 #include <boost/thread/condition_variable.hpp>
47 #include <boost/thread/mutex.hpp>
48 #include <boost/thread/thread.hpp>
49
50 #if defined(_MSC_VER)
51 #pragma warning (push)
52 #pragma warning (disable : 4244)
53 #endif
54 extern "C"
55 {
56         #define __STDC_CONSTANT_MACROS
57         #define __STDC_LIMIT_MACROS
58         #include <libavformat/avformat.h>
59 }
60 #if defined(_MSC_VER)
61 #pragma warning (pop)
62 #endif
63
64 static const size_t MAX_BUFFER_COUNT    = 100;
65 static const size_t MAX_BUFFER_COUNT_RT = 3;
66 static const size_t MIN_BUFFER_COUNT    = 50;
67 static const size_t MAX_BUFFER_SIZE     = 64 * 1000000;
68
69 namespace caspar { namespace ffmpeg {
70 struct input::implementation : boost::noncopyable
71 {
72         const spl::shared_ptr<diagnostics::graph>                                       graph_;
73
74         const spl::shared_ptr<AVFormatContext>                                          format_context_; // Destroy this last
75         const int                                                                                                       default_stream_index_   = av_find_default_stream_index(format_context_.get());
76
77         const std::wstring                                                                                      filename_;
78         tbb::atomic<uint32_t>                                                                           start_;
79         tbb::atomic<uint32_t>                                                                           length_;
80         const bool                                                                                                      thumbnail_mode_;
81         tbb::atomic<bool>                                                                                       loop_;
82         uint32_t                                                                                                        frame_number_                   = 0;
83         boost::rational<int>                                                                            framerate_                              = read_framerate(*format_context_, 1);
84
85         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>>        buffer_;
86         tbb::atomic<size_t>                                                                                     buffer_size_;
87
88         executor                                                                                                        executor_;
89
90         explicit implementation(const spl::shared_ptr<diagnostics::graph> graph, const std::wstring& url_or_file, bool loop, uint32_t start, uint32_t length, bool thumbnail_mode, const ffmpeg_options& vid_params)
91                 : graph_(graph)
92                 , format_context_(open_input(url_or_file, vid_params))
93                 , filename_(url_or_file)
94                 , thumbnail_mode_(thumbnail_mode)
95                 , executor_(print())
96         {
97                 if (thumbnail_mode_)
98                         executor_.invoke([]
99                         {
100                                 enable_quiet_logging_for_thread();
101                         });
102
103                 start_                  = start;
104                 length_                 = length;
105                 loop_                   = loop;
106                 buffer_size_    = 0;
107
108                 if(start_ > 0)
109                         queued_seek(start_);
110
111                 graph_->set_color("seek", diagnostics::color(1.0f, 0.5f, 0.0f));
112                 graph_->set_color("buffer-count", diagnostics::color(0.7f, 0.4f, 0.4f));
113                 graph_->set_color("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f));
114
115                 tick();
116         }
117
118         bool try_pop(std::shared_ptr<AVPacket>& packet)
119         {
120                 auto result = buffer_.try_pop(packet);
121
122                 if(result)
123                 {
124                         if(packet)
125                                 buffer_size_ -= packet->size;
126                         tick();
127                 }
128
129                 graph_->set_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);
130                 graph_->set_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));
131
132                 return result;
133         }
134
135         std::ptrdiff_t get_max_buffer_count() const
136         {
137                 return thumbnail_mode_ ? 1 : MAX_BUFFER_COUNT;
138         }
139
140         std::ptrdiff_t get_min_buffer_count() const
141         {
142                 return thumbnail_mode_ ? 0 : MIN_BUFFER_COUNT;
143         }
144
145         std::future<bool> seek(uint32_t target)
146         {
147                 if (!executor_.is_running())
148                         return make_ready_future(false);
149
150                 return executor_.begin_invoke([=]() -> bool
151                 {
152                         std::shared_ptr<AVPacket> packet;
153                         while(buffer_.try_pop(packet) && packet)
154                                 buffer_size_ -= packet->size;
155
156                         queued_seek(target);
157
158                         tick();
159
160                         return true;
161                 }, task_priority::high_priority);
162         }
163
164         std::wstring print() const
165         {
166                 return L"ffmpeg_input[" + filename_ + L")]";
167         }
168
169         bool full() const
170         {
171                 return (buffer_size_ > MAX_BUFFER_SIZE || buffer_.size() > get_max_buffer_count()) && buffer_.size() > get_min_buffer_count();
172         }
173
174         void tick()
175         {
176                 if(!executor_.is_running())
177                         return;
178
179                 executor_.begin_invoke([this]
180                 {
181                         if(full())
182                                 return;
183
184                         try
185                         {
186                                 auto packet = create_packet();
187
188                                 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.
189
190                                 if(is_eof(ret))
191                                 {
192                                         frame_number_   = 0;
193
194                                         if(loop_)
195                                         {
196                                                 queued_seek(start_);
197                                                 graph_->set_tag(diagnostics::tag_severity::INFO, "seek");
198                                                 CASPAR_LOG(trace) << print() << " Looping.";
199                                         }
200                                         else
201                                                 executor_.stop();
202                                 }
203                                 else
204                                 {
205                                         THROW_ON_ERROR(ret, "av_read_frame", print());
206
207                                         if(packet->stream_index == default_stream_index_)
208                                                 ++frame_number_;
209
210                                         THROW_ON_ERROR2(av_dup_packet(packet.get()), print());
211
212                                         // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.
213                                         auto size = packet->size;
214                                         auto data = packet->data;
215
216                                         packet = spl::shared_ptr<AVPacket>(packet.get(), [packet, size, data](AVPacket*)
217                                         {
218                                                 packet->size = size;
219                                                 packet->data = data;
220                                         });
221
222                                         buffer_.try_push(packet);
223                                         buffer_size_ += packet->size;
224
225                                         graph_->set_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);
226                                         graph_->set_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));
227                                 }
228
229                                 tick();
230                         }
231                         catch(...)
232                         {
233                                 if (!thumbnail_mode_)
234                                         CASPAR_LOG_CURRENT_EXCEPTION();
235                                 executor_.stop();
236                         }
237                 });
238         }
239
240         spl::shared_ptr<AVFormatContext> open_input(const std::wstring& url_or_file, const ffmpeg_options& vid_params)
241         {
242                 AVDictionary* format_options = nullptr;
243
244                 CASPAR_SCOPE_EXIT
245                 {
246                         if (format_options)
247                                 av_dict_free(&format_options);
248                 };
249
250                 for (auto& option : vid_params)
251                         av_dict_set(&format_options, option.first.c_str(), option.second.c_str(), 0);
252
253                 auto resource_name                      = std::wstring();
254                 auto parts                                      = caspar::protocol_split(url_or_file);
255                 AVInputFormat* input_format     = nullptr;
256
257                 if (parts.at(0).empty())
258                         resource_name = parts.at(1);
259                 else if (parts.at(0) == L"dshow")
260                 {
261                         input_format = av_find_input_format("dshow");
262                         resource_name = parts.at(1);
263                 }
264                 else
265                         resource_name = parts.at(0) + L"://" + parts.at(1);
266
267                 AVFormatContext* weak_context = nullptr;
268                 THROW_ON_ERROR2(avformat_open_input(&weak_context, u8(resource_name).c_str(), input_format, &format_options), resource_name);
269
270                 spl::shared_ptr<AVFormatContext> context(weak_context, [](AVFormatContext* ptr)
271                 {
272                         avformat_close_input(&ptr);
273                 });
274
275                 if (format_options)
276                 {
277                         std::string unsupported_tokens = "";
278                         AVDictionaryEntry *t = NULL;
279                         while ((t = av_dict_get(format_options, "", t, AV_DICT_IGNORE_SUFFIX)) != nullptr)
280                         {
281                                 if (!unsupported_tokens.empty())
282                                         unsupported_tokens += ", ";
283                                 unsupported_tokens += t->key;
284                         }
285                         CASPAR_THROW_EXCEPTION(user_error() << msg_info(unsupported_tokens));
286                 }
287
288                 THROW_ON_ERROR2(avformat_find_stream_info(context.get(), nullptr), resource_name);
289                 fix_meta_data(*context);
290                 return context;
291         }
292
293         void fix_meta_data(AVFormatContext& context)
294         {
295                 auto video_index = av_find_best_stream(&context, AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);
296
297                 if (video_index > -1)
298                 {
299                         auto video_stream = context.streams[video_index];
300                         auto video_context = context.streams[video_index]->codec;
301
302                         if (boost::filesystem::path(context.filename).extension().string() == ".flv")
303                         {
304                                 try
305                                 {
306                                         auto meta = read_flv_meta_info(context.filename);
307                                         double fps = boost::lexical_cast<double>(meta["framerate"]);
308                                         video_stream->nb_frames = static_cast<int64_t>(boost::lexical_cast<double>(meta["duration"])*fps);
309                                 }
310                                 catch (...) {}
311                         }
312                         else
313                         {
314                                 auto stream_time = video_stream->time_base;
315                                 auto duration = video_stream->duration;
316                                 auto codec_time = video_context->time_base;
317                                 auto ticks = video_context->ticks_per_frame;
318
319                                 if (video_stream->nb_frames == 0)
320                                         video_stream->nb_frames = (duration*stream_time.num*codec_time.den) / (stream_time.den*codec_time.num*ticks);
321                         }
322                 }
323         }
324
325         void queued_seek(const uint32_t target)
326         {
327                 if (!thumbnail_mode_)
328                         CASPAR_LOG(debug) << print() << " Seeking: " << target;
329
330                 int flags = AVSEEK_FLAG_FRAME;
331                 if(target == 0)
332                 {
333                         // Fix VP6 seeking
334                         int vid_stream_index = av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);
335                         if(vid_stream_index >= 0)
336                         {
337                                 auto codec_id = format_context_->streams[vid_stream_index]->codec->codec_id;
338                                 if(codec_id == CODEC_ID_VP6A || codec_id == CODEC_ID_VP6F || codec_id == CODEC_ID_VP6)
339                                         flags = AVSEEK_FLAG_BYTE;
340                         }
341                 }
342
343                 auto stream = format_context_->streams[default_stream_index_];
344
345
346                 auto fps = read_fps(*format_context_, 0.0);
347
348                 THROW_ON_ERROR2(avformat_seek_file(
349                         format_context_.get(),
350                         default_stream_index_,
351                         std::numeric_limits<int64_t>::min(),
352                         static_cast<int64_t>((target / fps * stream->time_base.den) / stream->time_base.num),
353                         std::numeric_limits<int64_t>::max(),
354                         0), print());
355
356                 auto flush_packet       = create_packet();
357                 flush_packet->data      = nullptr;
358                 flush_packet->size      = 0;
359                 flush_packet->pos       = target;
360
361                 buffer_.push(flush_packet);
362         }
363
364         bool is_eof(int ret)
365         {
366                 if(ret == AVERROR(EIO))
367                         CASPAR_LOG(trace) << print() << " Received EIO, assuming EOF. ";
368                 if(ret == AVERROR_EOF)
369                         CASPAR_LOG(trace) << print() << " Received EOF. ";
370
371                 return ret == AVERROR_EOF || ret == AVERROR(EIO) || frame_number_ >= length_; // av_read_frame doesn't always correctly return AVERROR_EOF;
372         }
373
374         int num_audio_streams() const
375         {
376                 return 0; // TODO
377         }
378
379         boost::rational<int> framerate() const
380         {
381                 return framerate_;
382         }
383 };
384
385 input::input(const spl::shared_ptr<diagnostics::graph>& graph, const std::wstring& url_or_file, bool loop, uint32_t start, uint32_t length, bool thumbnail_mode, const ffmpeg_options& vid_params)
386         : impl_(new implementation(graph, url_or_file, loop, start, length, thumbnail_mode, vid_params)){}
387 bool input::eof() const {return !impl_->executor_.is_running();}
388 bool input::try_pop(std::shared_ptr<AVPacket>& packet){return impl_->try_pop(packet);}
389 spl::shared_ptr<AVFormatContext> input::context(){return impl_->format_context_;}
390 void input::start(uint32_t value){impl_->start_ = value;}
391 uint32_t input::start() const{return impl_->start_;}
392 void input::length(uint32_t value){impl_->length_ = value;}
393 uint32_t input::length() const{return impl_->length_;}
394 void input::loop(bool value){impl_->loop_ = value;}
395 bool input::loop() const{return impl_->loop_;}
396 int input::num_audio_streams() const { return impl_->num_audio_streams(); }
397 boost::rational<int> input::framerate() const { return impl_->framerate(); }
398 std::future<bool> input::seek(uint32_t target){return impl_->seek(target);}
399 }}