]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input/input.cpp
* Added logging of severe diagnostics events to log at warning level. graph::set_tag...
[casparcg] / modules / ffmpeg / producer / input / input.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 "input.h"
25
26 #include "../util/util.h"
27 #include "../../ffmpeg_error.h"
28
29 #include <common/diagnostics/graph.h>
30 #include <common/executor.h>
31 #include <common/lock.h>
32 //#include <common/except.h>
33 #include <common/os/general_protection_fault.h>
34 #include <common/log.h>
35
36 #include <core/video_format.h>
37
38 #include <tbb/concurrent_queue.h>
39 #include <tbb/atomic.h>
40 #include <tbb/recursive_mutex.h>
41
42 #include <boost/thread/condition_variable.hpp>
43 #include <boost/thread/mutex.hpp>
44 #include <boost/thread/thread.hpp>
45
46 #if defined(_MSC_VER)
47 #pragma warning (push)
48 #pragma warning (disable : 4244)
49 #endif
50 extern "C" 
51 {
52         #define __STDC_CONSTANT_MACROS
53         #define __STDC_LIMIT_MACROS
54         #include <libavformat/avformat.h>
55 }
56 #if defined(_MSC_VER)
57 #pragma warning (pop)
58 #endif
59
60 namespace caspar { namespace ffmpeg {
61
62 static const int MIN_FRAMES = 25;
63
64 class stream
65 {
66         stream(const stream&);
67         stream& operator=(const stream&);
68
69         typedef tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>>::size_type size_type;
70
71         int                                                                                                              index_;
72         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>> packets_;
73 public:
74
75         stream(int index) 
76                 : index_(index)
77         {
78         }
79
80         bool is_available() const
81         {
82                 return index_ >= 0;
83         }
84         
85         void push(const std::shared_ptr<AVPacket>& packet)
86         {
87                 if(packet && packet->data && packet->stream_index != index_)
88                         return;
89
90                 packets_.push(packet);
91         }
92
93         bool try_pop(std::shared_ptr<AVPacket>& packet)
94         {
95                 return packets_.try_pop(packet);
96         }
97
98         void clear()
99         {
100                 std::shared_ptr<AVPacket> packet;
101                 while(packets_.try_pop(packet));
102         }
103                 
104         size_type size() const
105         {
106                 return is_available() ? packets_.size() : std::numeric_limits<size_type>::max();
107         }
108 };
109                 
110 struct input::impl : boost::noncopyable
111 {               
112         const spl::shared_ptr<diagnostics::graph>       graph_;
113
114         const std::wstring                                                      filename_;
115         const spl::shared_ptr<AVFormatContext>          format_context_                 = open_input(filename_); // Destroy this last
116         const int                                                                       default_stream_index_   = av_find_default_stream_index(format_context_.get());
117
118         tbb::atomic<uint32_t>                                           start_;         
119         tbb::atomic<uint32_t>                                           length_;
120         tbb::atomic<bool>                                                       loop_;
121         double                                                                          fps_                                    = read_fps(*format_context_, 0.0);
122         uint32_t                                                                        frame_number_                   = 0;
123
124         stream                                                                          video_stream_                   { av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0) };
125         stream                                                                          audio_stream_                   { av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_AUDIO, -1, -1, 0, 0) };
126
127         boost::optional<uint32_t>                                       seek_target_;
128
129         tbb::atomic<bool>                                                       is_running_;
130         boost::mutex                                                            mutex_;
131         boost::condition_variable                                       cond_;
132         boost::thread                                                           thread_;
133         
134         impl(const spl::shared_ptr<diagnostics::graph> graph, const std::wstring& filename, const bool loop, const uint32_t start, const uint32_t length) 
135                 : graph_(graph)
136                 , filename_(filename)
137         {               
138                 start_                  = start;
139                 length_                 = length;
140                 loop_                   = loop;
141                 is_running_             = true;
142
143                 if(start_ != 0)
144                         seek_target_ = start_;
145                                                                                                                 
146                 graph_->set_color("seek", diagnostics::color(1.0f, 0.5f, 0.0f));
147
148                 if (audio_stream_.is_available())
149                         graph_->set_color("audio-buffer", diagnostics::color(0.7f, 0.4f, 0.4f));
150
151                 if (video_stream_.is_available())
152                         graph_->set_color("video-buffer", diagnostics::color(1.0f, 1.0f, 0.0f));
153                 
154                 for(int n = 0; n < 8; ++n)
155                         tick();
156
157                 thread_ = boost::thread([this]{run();});
158         }
159
160         ~impl()
161         {
162                 is_running_ = false;
163                 cond_.notify_one();
164                 thread_.join();
165         }
166         
167         bool try_pop_video(std::shared_ptr<AVPacket>& packet)
168         {
169                 if (!video_stream_.is_available())
170                         return false;
171
172                 bool result = video_stream_.try_pop(packet);
173                 if(result)
174                         cond_.notify_one();
175                 
176                 graph_->set_value("video-buffer", std::min(1.0, static_cast<double>(video_stream_.size()/MIN_FRAMES)));
177                                 
178                 return result;
179         }
180         
181         bool try_pop_audio(std::shared_ptr<AVPacket>& packet)
182         {
183                 if (!audio_stream_.is_available())
184                         return false;
185
186                 bool result = audio_stream_.try_pop(packet);
187                 if(result)
188                         cond_.notify_one();
189                                 
190                 graph_->set_value("audio-buffer", std::min(1.0, static_cast<double>(audio_stream_.size()/MIN_FRAMES)));
191
192                 return result;
193         }
194
195         void seek(uint32_t target)
196         {
197                 {
198                         boost::lock_guard<boost::mutex> lock(mutex_);
199
200                         seek_target_ = target;
201                         video_stream_.clear();
202                         audio_stream_.clear();
203                 }
204                 
205                 cond_.notify_one();
206         }
207                 
208         std::wstring print() const
209         {
210                 return L"ffmpeg_input[" + filename_ + L")]";
211         }
212
213 private:
214         void internal_seek(uint32_t target)
215         {
216                 graph_->set_tag(diagnostics::tag_severity::INFO, "seek");
217
218                 CASPAR_LOG(debug) << print() << " Seeking: " << target;
219
220                 int flags = AVSEEK_FLAG_FRAME;
221                 if(target == 0)
222                 {
223                         // Fix VP6 seeking
224                         int vid_stream_index = av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);
225                         if(vid_stream_index >= 0)
226                         {
227                                 auto codec_id = format_context_->streams[vid_stream_index]->codec->codec_id;
228                                 if(codec_id == CODEC_ID_VP6A || codec_id == CODEC_ID_VP6F || codec_id == CODEC_ID_VP6)
229                                         flags = AVSEEK_FLAG_BYTE;
230                         }
231                 }
232                 
233                 auto stream     = format_context_->streams[default_stream_index_];
234                 auto fps        = read_fps(*format_context_, 0.0);
235                 
236                 THROW_ON_ERROR2(avformat_seek_file(
237                                 format_context_.get(),
238                                 default_stream_index_,
239                                 std::numeric_limits<int64_t>::min(),
240                                 static_cast<int64_t>((target / fps * stream->time_base.den) / stream->time_base.num),
241                                 std::numeric_limits<int64_t>::max(),
242                                 0), print());
243                 
244                 video_stream_.push(nullptr);
245                 audio_stream_.push(nullptr);
246         }
247
248         void tick()
249         {
250                 if(seek_target_)                                
251                 {
252                         internal_seek(*seek_target_);
253                         seek_target_.reset();
254                 }
255
256                 auto packet = create_packet();
257                 
258                 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.  
259                 
260                 if(is_eof(ret))                                                                                                              
261                 {
262                         if (loop_)
263                                 internal_seek(start_);
264                         else
265                         {
266                                 audio_stream_.push(packet);
267                                 video_stream_.push(packet);
268                         }
269                 }
270                 else
271                 {               
272                         THROW_ON_ERROR(ret, "av_read_frame", print());
273                                         
274                         THROW_ON_ERROR2(av_dup_packet(packet.get()), print());
275                                 
276                         // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.
277                         const auto size = packet->size;
278                         const auto data = packet->data;
279                         
280                         packet = spl::shared_ptr<AVPacket>(packet.get(), [packet, size, data](AVPacket*)
281                         {
282                                 packet->size = size;
283                                 packet->data = data;                            
284                         });
285                                         
286                         const auto stream_time_base = format_context_->streams[packet->stream_index]->time_base;
287                         const auto packet_frame_number = static_cast<uint32_t>((static_cast<double>(packet->pts * stream_time_base.num)/stream_time_base.den)*fps_);
288
289                         if(packet->stream_index == default_stream_index_)
290                                 frame_number_ = packet_frame_number;
291                                         
292                         if(packet_frame_number >= start_ && packet_frame_number < length_)
293                         {
294                                 video_stream_.push(packet);
295                                 audio_stream_.push(packet);
296                         }
297                 }       
298
299                 if (video_stream_.is_available())
300                         graph_->set_value("video-buffer", std::min(1.0, static_cast<double>(video_stream_.size()/MIN_FRAMES)));
301
302                 if (audio_stream_.is_available())
303                         graph_->set_value("audio-buffer", std::min(1.0, static_cast<double>(audio_stream_.size()/MIN_FRAMES)));
304         }
305                         
306         bool full() const
307         {
308                 return video_stream_.size() >= MIN_FRAMES && audio_stream_.size() >= MIN_FRAMES;
309         }
310
311         void run()
312         {
313                 ensure_gpf_handler_installed_for_thread(u8(print()).c_str());
314
315                 while(is_running_)
316                 {
317                         try
318                         {
319                                 
320                                 {
321                                         boost::unique_lock<boost::mutex> lock(mutex_);
322
323                                         while(full() && !seek_target_ && is_running_)
324                                                 cond_.wait(lock);
325                                         
326                                         tick();
327                                 }
328                         }
329                         catch(...)
330                         {
331                                 CASPAR_LOG_CURRENT_EXCEPTION();
332                                 is_running_ = false;
333                         }
334                 }
335         }
336                         
337         bool is_eof(int ret)
338         {
339                 #pragma warning (disable : 4146)
340                 return ret == AVERROR_EOF || ret == AVERROR(EIO) || frame_number_ >= length_; // av_read_frame doesn't always correctly return AVERROR_EOF;
341         }
342 };
343
344 input::input(const spl::shared_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, uint32_t start, uint32_t length) 
345         : impl_(new impl(graph, filename, loop, start, length)){}
346 bool input::try_pop_video(std::shared_ptr<AVPacket>& packet){return impl_->try_pop_video(packet);}
347 bool input::try_pop_audio(std::shared_ptr<AVPacket>& packet){return impl_->try_pop_audio(packet);}
348 AVFormatContext& input::context(){return *impl_->format_context_;}
349 void input::loop(bool value){impl_->loop_ = value;}
350 bool input::loop() const{return impl_->loop_;}
351 void input::seek(uint32_t target){impl_->seek(target);}
352 void input::start(uint32_t value){impl_->start_ = value;}
353 uint32_t input::start() const{return impl_->start_;}
354 void input::length(uint32_t value){impl_->length_ = value;}
355 uint32_t input::length() const{return impl_->length_;}
356 }}