]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input.cpp
2.0. ffmpeg_producer: Improved frame number count accuracy.
[casparcg] / modules / ffmpeg / producer / input.cpp
1 /*\r
2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 *  This file is part of CasparCG.\r
5 *\r
6 *    CasparCG is free software: you can redistribute it and/or modify\r
7 *    it under the terms of the GNU General Public License as published by\r
8 *    the Free Software Foundation, either version 3 of the License, or\r
9 *    (at your option) any later version.\r
10 *\r
11 *    CasparCG is distributed in the hope that it will be useful,\r
12 *    but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14 *    GNU General Public License for more details.\r
15 \r
16 *    You should have received a copy of the GNU General Public License\r
17 *    along with CasparCG.  If not, see <http://www.gnu.org/licenses/>.\r
18 *\r
19 */\r
20 #if defined(_MSC_VER)\r
21 #pragma warning (disable : 4244)\r
22 #endif\r
23 \r
24 #include "../stdafx.h"\r
25 \r
26 #include "input.h"\r
27 #include "../ffmpeg_error.h"\r
28 #include "../tbb_avcodec.h"\r
29 \r
30 #include <core/video_format.h>\r
31 \r
32 #include <common/diagnostics/graph.h>\r
33 #include <common/exception/exceptions.h>\r
34 #include <common/exception/win32_exception.h>\r
35 \r
36 #include <tbb/concurrent_queue.h>\r
37 #include <tbb/atomic.h>\r
38 \r
39 #include <boost/range/algorithm.hpp>\r
40 #include <boost/thread/condition_variable.hpp>\r
41 #include <boost/thread/mutex.hpp>\r
42 #include <boost/thread/thread.hpp>\r
43 \r
44 #if defined(_MSC_VER)\r
45 #pragma warning (push)\r
46 #pragma warning (disable : 4244)\r
47 #endif\r
48 extern "C" \r
49 {\r
50         #define __STDC_CONSTANT_MACROS\r
51         #define __STDC_LIMIT_MACROS\r
52         #include <libavformat/avformat.h>\r
53 }\r
54 #if defined(_MSC_VER)\r
55 #pragma warning (pop)\r
56 #endif\r
57 \r
58 namespace caspar {\r
59 \r
60 static const size_t MAX_BUFFER_COUNT = 128;\r
61 static const size_t MAX_BUFFER_SIZE  = 32 * 1000000;\r
62         \r
63 struct input::implementation : boost::noncopyable\r
64 {               \r
65         std::shared_ptr<AVFormatContext>                                                        format_context_; // Destroy this last\r
66 \r
67         safe_ptr<diagnostics::graph>                                                            graph_;\r
68                 \r
69         const std::wstring                                                                                      filename_;\r
70         const bool                                                                                                      loop_;\r
71         const int                                                                                                       start_;         \r
72         \r
73         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>>        buffer_;\r
74         tbb::atomic<size_t>                                                                                     buffer_size_;\r
75         boost::condition_variable                                                                       buffer_cond_;\r
76         boost::mutex                                                                                            buffer_mutex_;\r
77                 \r
78         boost::thread                                                                                           thread_;\r
79         tbb::atomic<bool>                                                                                       is_running_;\r
80         tbb::atomic<size_t>                                                                                     nb_frames_;\r
81         int64_t                                                                                                         frame_number_;\r
82 \r
83         int                                                                                                                     default_stream_index_;\r
84 public:\r
85         explicit implementation(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start) \r
86                 : graph_(graph)\r
87                 , loop_(loop)\r
88                 , filename_(filename)\r
89                 , start_(std::max(start, 0))\r
90                 , frame_number_(0)\r
91         {                       \r
92                 is_running_ = true;\r
93                 nb_frames_ = 0;\r
94                 \r
95                 AVFormatContext* weak_format_context_ = nullptr;\r
96                 THROW_ON_ERROR2(avformat_open_input(&weak_format_context_, narrow(filename).c_str(), nullptr, nullptr), print());\r
97 \r
98                 format_context_.reset(weak_format_context_, av_close_input_file);\r
99                         \r
100                 THROW_ON_ERROR2(avformat_find_stream_info(format_context_.get(), nullptr), print());\r
101                 \r
102                 default_stream_index_ = THROW_ON_ERROR2(av_find_default_stream_index(format_context_.get()), print());\r
103 \r
104                 if(start_ != 0)                 \r
105                         seek_frame(start_);\r
106                 \r
107                 for(int n = 0; n < 16 && !full(); ++n)\r
108                         read_next_packet();\r
109                                                 \r
110                 graph_->set_color("seek", diagnostics::color(0.5f, 1.0f, 0.5f));        \r
111                 graph_->set_color("buffer-count", diagnostics::color(0.2f, 0.8f, 1.0f));\r
112                 graph_->set_color("buffer-size", diagnostics::color(0.2f, 0.4f, 1.0f)); \r
113 \r
114                 thread_ = boost::thread([this]{run();});\r
115         }\r
116 \r
117         ~implementation()\r
118         {\r
119                 is_running_ = false;\r
120                 buffer_cond_.notify_all();\r
121                 thread_.join();\r
122         }\r
123                 \r
124         bool try_pop(std::shared_ptr<AVPacket>& packet)\r
125         {\r
126                 const bool result = buffer_.try_pop(packet);\r
127 \r
128                 if(result)\r
129                 {\r
130                         if(packet)\r
131                                 buffer_size_ -= packet->size;\r
132                         buffer_cond_.notify_all();\r
133                 }\r
134 \r
135                 graph_->update_value("buffer-size", MAX_BUFFER_SIZE/static_cast<double>(buffer_size_));\r
136                 graph_->update_value("buffer-count", MAX_BUFFER_SIZE/static_cast<double>(buffer_.size()));\r
137 \r
138                 return result;\r
139         }\r
140 \r
141         size_t nb_frames() const\r
142         {\r
143                 return nb_frames_;\r
144         }\r
145 \r
146 private:\r
147         \r
148         void run()\r
149         {               \r
150                 caspar::win32_exception::install_handler();\r
151 \r
152                 try\r
153                 {\r
154                         CASPAR_LOG(info) << print() << " Thread Started.";\r
155 \r
156                         while(is_running_)\r
157                         {\r
158                                 {\r
159                                         boost::unique_lock<boost::mutex> lock(buffer_mutex_);\r
160                                         buffer_cond_.wait(lock, [this]{return !full();});\r
161                                 }\r
162                                 read_next_packet();                     \r
163                         }\r
164 \r
165                         CASPAR_LOG(info) << print() << " Thread Stopped.";\r
166                 }\r
167                 catch(...)\r
168                 {\r
169                         CASPAR_LOG_CURRENT_EXCEPTION();\r
170                         is_running_ = false;\r
171                 }\r
172         }\r
173                         \r
174         void read_next_packet()\r
175         {               \r
176                 int ret = 0;\r
177 \r
178                 std::shared_ptr<AVPacket> read_packet(new AVPacket, [](AVPacket* p)\r
179                 {\r
180                         av_free_packet(p);\r
181                         delete p;\r
182                 });\r
183                 av_init_packet(read_packet.get());\r
184 \r
185                 ret = av_read_frame(format_context_.get(), read_packet.get()); // read_packet is only valid until next call of av_read_frame. Use av_dup_packet to extend its life.     \r
186                 \r
187                 if(is_eof(ret))                                                                                                              \r
188                 {\r
189                         if(nb_frames_ == 0)\r
190                                 nb_frames_ = static_cast<size_t>(frame_number_);\r
191 \r
192                         if(loop_)\r
193                         {\r
194                                 seek_frame(start_, AVSEEK_FLAG_BACKWARD);\r
195                                 graph_->add_tag("seek");                \r
196                                 CASPAR_LOG(trace) << print() << " Received EOF. Looping.";                      \r
197                         }       \r
198                         else\r
199                         {\r
200                                 is_running_ = false;\r
201                                 CASPAR_LOG(trace) << print() << " Received EOF. Stopping.";\r
202                         }\r
203                 }\r
204                 else\r
205                 {               \r
206                         THROW_ON_ERROR(ret, print(), "av_read_frame");\r
207 \r
208                         if(read_packet->stream_index == default_stream_index_)\r
209                                 ++frame_number_;\r
210 \r
211                         THROW_ON_ERROR2(av_dup_packet(read_packet.get()), print());\r
212                                 \r
213                         // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.\r
214                         auto size = read_packet->size;\r
215                         auto data = read_packet->data;\r
216 \r
217                         read_packet = std::shared_ptr<AVPacket>(read_packet.get(), [=](AVPacket*)\r
218                         {\r
219                                 read_packet->size = size;\r
220                                 read_packet->data = data;\r
221                         });\r
222 \r
223                         buffer_.try_push(read_packet);\r
224                         buffer_size_ += read_packet->size;\r
225                                 \r
226                         graph_->update_value("buffer-count", MAX_BUFFER_SIZE/static_cast<double>(buffer_.size()));\r
227                         graph_->update_value("buffer-size", MAX_BUFFER_SIZE/static_cast<double>(buffer_size_));\r
228                 }                       \r
229         }\r
230 \r
231         bool full() const\r
232         {\r
233                 return is_running_ && buffer_size_ > MAX_BUFFER_SIZE && buffer_.size() > MAX_BUFFER_COUNT;\r
234         }\r
235 \r
236         void seek_frame(int64_t frame, int flags = 0)\r
237         {                                                       \r
238                 THROW_ON_ERROR2(av_seek_frame(format_context_.get(), default_stream_index_, frame, flags), print());            \r
239                 buffer_.push(nullptr);\r
240         }               \r
241 \r
242         bool is_eof(int ret)\r
243         {\r
244                 if(ret == AVERROR(EIO))\r
245                         CASPAR_LOG(debug) << print() << " Received EIO, assuming EOF.";\r
246                 //if(ret == AVERROR_EOF)\r
247                 //      CASPAR_LOG(info) << print() << " Received EOF.";\r
248 \r
249                 return ret == AVERROR_EOF || ret == AVERROR(EIO); // av_read_frame doesn't always correctly return AVERROR_EOF;\r
250         }\r
251         \r
252         std::wstring print() const\r
253         {\r
254                 return L"ffmpeg_input[" + filename_ + L")]";\r
255         }\r
256 };\r
257 \r
258 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start, int length) \r
259         : impl_(new implementation(graph, filename, loop, start)){}\r
260 bool input::eof() const {return !impl_->is_running_;}\r
261 bool input::try_pop(std::shared_ptr<AVPacket>& packet){return impl_->try_pop(packet);}\r
262 std::shared_ptr<AVFormatContext> input::context(){return impl_->format_context_;}\r
263 size_t input::nb_frames() const {return impl_->nb_frames();}\r
264 }