]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input/input.cpp
channel-exp: ffmpeg: Fixed bug with nb_frames, fixed bug with length.
[casparcg] / modules / ffmpeg / producer / input / 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 \r
28 #include "../util/util.h"\r
29 #include "../../ffmpeg_error.h"\r
30 \r
31 #include <core/video_format.h>\r
32 \r
33 #include <common/diagnostics/graph.h>\r
34 #include <common/exception/exceptions.h>\r
35 #include <common/exception/win32_exception.h>\r
36 \r
37 #include <tbb/concurrent_queue.h>\r
38 #include <tbb/atomic.h>\r
39 \r
40 #include <boost/range/algorithm.hpp>\r
41 #include <boost/thread/condition_variable.hpp>\r
42 #include <boost/thread/mutex.hpp>\r
43 #include <boost/thread/thread.hpp>\r
44 \r
45 #if defined(_MSC_VER)\r
46 #pragma warning (push)\r
47 #pragma warning (disable : 4244)\r
48 #endif\r
49 extern "C" \r
50 {\r
51         #define __STDC_CONSTANT_MACROS\r
52         #define __STDC_LIMIT_MACROS\r
53         #include <libavformat/avformat.h>\r
54 }\r
55 #if defined(_MSC_VER)\r
56 #pragma warning (pop)\r
57 #endif\r
58 \r
59 namespace caspar { namespace ffmpeg {\r
60 \r
61 static const size_t MAX_BUFFER_COUNT = 100;\r
62 static const size_t MIN_BUFFER_COUNT = 4;\r
63 static const size_t MAX_BUFFER_SIZE  = 16 * 1000000;\r
64         \r
65 struct input::implementation : boost::noncopyable\r
66 {               \r
67         safe_ptr<diagnostics::graph>                                                            graph_;\r
68 \r
69         const safe_ptr<AVFormatContext>                                                         format_context_; // Destroy this last\r
70         const int                                                                                                       default_stream_index_;\r
71                         \r
72         const std::wstring                                                                                      filename_;\r
73         const bool                                                                                                      loop_;\r
74         const size_t                                                                                            start_;         \r
75         const size_t                                                                                            length_;\r
76         size_t                                                                                                          frame_number_;\r
77         \r
78         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>>        buffer_;\r
79         tbb::atomic<size_t>                                                                                     buffer_size_;\r
80         boost::condition_variable                                                                       buffer_cond_;\r
81         boost::mutex                                                                                            buffer_mutex_;\r
82                 \r
83         tbb::atomic<size_t>                                                                                     nb_frames_;\r
84         tbb::atomic<size_t>                                                                                     nb_loops_;\r
85 \r
86         boost::thread                                                                                           thread_;\r
87         tbb::atomic<bool>                                                                                       is_running_;\r
88 \r
89 public:\r
90         explicit implementation(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, size_t start, size_t length) \r
91                 : graph_(graph)\r
92                 , format_context_(open_input(filename))         \r
93                 , default_stream_index_(av_find_default_stream_index(format_context_.get()))\r
94                 , loop_(loop)\r
95                 , filename_(filename)\r
96                 , start_(start)\r
97                 , length_(length)\r
98                 , frame_number_(0)\r
99         {                                       \r
100                 buffer_size_    = 0;\r
101                 nb_frames_              = 0;\r
102                 nb_loops_               = 0;\r
103 \r
104                 if(start_ > 0)                  \r
105                         seek_frame(start_);\r
106                                                                 \r
107                 graph_->set_color("seek", diagnostics::color(1.0f, 0.5f, 0.0f));        \r
108                 graph_->set_color("buffer-count", diagnostics::color(0.7f, 0.4f, 0.4f));\r
109                 graph_->set_color("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f)); \r
110                 \r
111                 is_running_ = true;\r
112                 thread_ = boost::thread([this]{run();});\r
113 \r
114                 CASPAR_LOG(info) << print() << L" Initialized.";\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", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);\r
136                 graph_->update_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));\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         size_t nb_loops() const\r
147         {\r
148                 return nb_loops_;\r
149         }\r
150 \r
151 private:\r
152         \r
153         void run()\r
154         {               \r
155                 caspar::win32_exception::install_handler();\r
156 \r
157                 try\r
158                 {\r
159                         CASPAR_LOG(info) << print() << " Thread Started.";\r
160                         \r
161                         CASPAR_ASSERT(nb_frames_ < 1000);\r
162 \r
163                         while(is_running_)\r
164                         {\r
165                                 {\r
166                                         boost::unique_lock<boost::mutex> lock(buffer_mutex_);\r
167                                         while(full())\r
168                                                 buffer_cond_.timed_wait(lock, boost::posix_time::millisec(20));\r
169                                 }\r
170                                 read_next_packet();                     \r
171                         }\r
172 \r
173                         CASPAR_LOG(info) << print() << " Thread Stopped.";\r
174                 }\r
175                 catch(...)\r
176                 {\r
177                         CASPAR_LOG_CURRENT_EXCEPTION();\r
178                         is_running_ = false;\r
179                 }\r
180         }\r
181                         \r
182         void read_next_packet()\r
183         {               \r
184                 auto packet = create_packet();\r
185                 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.   \r
186                 \r
187                 CASPAR_ASSERT(nb_frames_ < 1000);\r
188 \r
189                 if(is_eof(ret))                                                                                                              \r
190                 {\r
191                         ++nb_loops_;\r
192                         frame_number_ = 0;\r
193 \r
194                         if(loop_)\r
195                         {\r
196                                 int flags = AVSEEK_FLAG_BACKWARD;\r
197 \r
198                                 int vid_stream_index = av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);\r
199                                 if(vid_stream_index >= 0)\r
200                                 {\r
201                                         auto codec_id = format_context_->streams[vid_stream_index]->codec->codec_id;\r
202                                         if(codec_id == CODEC_ID_VP6A || codec_id == CODEC_ID_VP6F || codec_id == CODEC_ID_VP6)\r
203                                                 flags |= AVSEEK_FLAG_BYTE;\r
204                                 }\r
205 \r
206                                 seek_frame(start_, flags);\r
207                                 graph_->add_tag("seek");                \r
208                                 CASPAR_LOG(debug) << print() << " Looping.";                    \r
209                         }       \r
210                         else\r
211                         {\r
212                                 is_running_ = false;\r
213                                 CASPAR_LOG(debug) << print() << " Stopping.";\r
214                         }\r
215                 }\r
216                 else\r
217                 {               \r
218                         THROW_ON_ERROR(ret, "av_read_frame", print());\r
219 \r
220                         if(packet->stream_index == default_stream_index_)\r
221                         {\r
222                                 if(nb_loops_ == 0)\r
223                                         ++nb_frames_;\r
224                                 ++frame_number_;\r
225                         }\r
226 \r
227                         THROW_ON_ERROR2(av_dup_packet(packet.get()), print());\r
228                                 \r
229                         // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.\r
230                         auto size = packet->size;\r
231                         auto data = packet->data;\r
232 \r
233                         packet = safe_ptr<AVPacket>(packet.get(), [packet, size, data](AVPacket*)\r
234                         {\r
235                                 packet->size = size;\r
236                                 packet->data = data;\r
237                         });\r
238 \r
239                         buffer_.try_push(packet);\r
240                         buffer_size_ += packet->size;\r
241                                 \r
242                         graph_->update_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);\r
243                         graph_->update_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));\r
244                 }                       \r
245         }\r
246 \r
247         bool full() const\r
248         {\r
249                 return is_running_ && (buffer_size_ > MAX_BUFFER_SIZE || buffer_.size() > MAX_BUFFER_COUNT) && buffer_.size() > MIN_BUFFER_COUNT;\r
250         }\r
251 \r
252         void seek_frame(int64_t frame, int flags = 0)\r
253         {                       \r
254                 if(flags == AVSEEK_FLAG_BACKWARD)\r
255                 {\r
256                         // Fix VP6 seeking\r
257                         int vid_stream_index = av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);\r
258                         if(vid_stream_index >= 0)\r
259                         {\r
260                                 auto codec_id = format_context_->streams[vid_stream_index]->codec->codec_id;\r
261                                 if(codec_id == CODEC_ID_VP6A || codec_id == CODEC_ID_VP6F || codec_id == CODEC_ID_VP6)\r
262                                         flags |= AVSEEK_FLAG_BYTE;\r
263                         }\r
264                 }\r
265 \r
266                 THROW_ON_ERROR2(av_seek_frame(format_context_.get(), default_stream_index_, frame, flags), print());            \r
267 \r
268                 buffer_.push(flush_packet());\r
269         }               \r
270 \r
271         bool is_eof(int ret)\r
272         {\r
273                 if(ret == AVERROR(EIO))\r
274                         CASPAR_LOG(trace) << print() << " Received EIO, assuming EOF. " << nb_frames_;\r
275                 if(ret == AVERROR_EOF)\r
276                         CASPAR_LOG(debug) << print() << " Received EOF. " << nb_frames_;\r
277 \r
278                 return ret == AVERROR_EOF || ret == AVERROR(EIO) || frame_number_ >= length_; // av_read_frame doesn't always correctly return AVERROR_EOF;\r
279         }\r
280         \r
281         std::wstring print() const\r
282         {\r
283                 return L"ffmpeg_input[" + filename_ + L")]";\r
284         }\r
285 };\r
286 \r
287 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, size_t start, size_t length) \r
288         : impl_(new implementation(graph, filename, loop, start, length)){}\r
289 bool input::eof() const {return !impl_->is_running_;}\r
290 bool input::try_pop(std::shared_ptr<AVPacket>& packet){return impl_->try_pop(packet);}\r
291 safe_ptr<AVFormatContext> input::context(){return impl_->format_context_;}\r
292 size_t input::nb_frames() const {return impl_->nb_frames();}\r
293 size_t input::nb_loops() const {return impl_->nb_loops();}\r
294 }}\r