]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input/input.cpp
git-svn-id: https://casparcg.svn.sourceforge.net/svnroot/casparcg/server/branches...
[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 #include <tbb/recursive_mutex.h>\r
40 \r
41 #include <boost/range/algorithm.hpp>\r
42 #include <boost/thread/condition_variable.hpp>\r
43 #include <boost/thread/mutex.hpp>\r
44 #include <boost/thread/thread.hpp>\r
45 \r
46 #if defined(_MSC_VER)\r
47 #pragma warning (push)\r
48 #pragma warning (disable : 4244)\r
49 #endif\r
50 extern "C" \r
51 {\r
52         #define __STDC_CONSTANT_MACROS\r
53         #define __STDC_LIMIT_MACROS\r
54         #include <libavformat/avformat.h>\r
55 }\r
56 #if defined(_MSC_VER)\r
57 #pragma warning (pop)\r
58 #endif\r
59 \r
60 namespace caspar { namespace ffmpeg {\r
61 \r
62 static const size_t MAX_BUFFER_COUNT = 100;\r
63 static const size_t MIN_BUFFER_COUNT = 4;\r
64 static const size_t MAX_BUFFER_SIZE  = 16 * 1000000;\r
65         \r
66 struct input::implementation : boost::noncopyable\r
67 {               \r
68         safe_ptr<diagnostics::graph>                                                            graph_;\r
69 \r
70         const safe_ptr<AVFormatContext>                                                         format_context_; // Destroy this last\r
71         const int                                                                                                       default_stream_index_;\r
72                         \r
73         const std::wstring                                                                                      filename_;\r
74         tbb::atomic<bool>                                                                                       loop_;\r
75         const size_t                                                                                            start_;         \r
76         const size_t                                                                                            length_;\r
77         size_t                                                                                                          frame_number_;\r
78         \r
79         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>>        buffer_;\r
80         tbb::atomic<size_t>                                                                                     buffer_size_;\r
81         boost::condition_variable                                                                       buffer_cond_;\r
82         boost::mutex                                                                                            buffer_mutex_;\r
83                 \r
84         boost::thread                                                                                           thread_;\r
85         tbb::atomic<bool>                                                                                       is_running_;\r
86         tbb::atomic<bool>                                                                                       is_eof_;\r
87 \r
88         tbb::recursive_mutex                                                                            mutex_;\r
89 \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                 , filename_(filename)\r
95                 , start_(start)\r
96                 , length_(length)\r
97                 , frame_number_(0)\r
98         {               \r
99                 is_eof_                 = false;\r
100                 loop_                   = loop;\r
101                 buffer_size_    = 0;\r
102 \r
103                 if(start_ > 0)                  \r
104                         do_seek(start_);\r
105                                                                 \r
106                 graph_->set_color("seek", diagnostics::color(1.0f, 0.5f, 0.0f));        \r
107                 graph_->set_color("buffer-count", diagnostics::color(0.7f, 0.4f, 0.4f));\r
108                 graph_->set_color("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f)); \r
109                 \r
110                 is_running_ = true;\r
111                 thread_ = boost::thread([this]{run();});\r
112 \r
113                 CASPAR_LOG(info) << print() << L" Initialized.";\r
114         }\r
115 \r
116         ~implementation()\r
117         {\r
118                 is_running_ = false;\r
119                 buffer_cond_.notify_all();\r
120                 thread_.join();\r
121         }\r
122                 \r
123         bool try_pop(std::shared_ptr<AVPacket>& packet)\r
124         {\r
125                 const bool result = buffer_.try_pop(packet);\r
126 \r
127                 if(result)\r
128                 {\r
129                         if(packet)\r
130                                 buffer_size_ -= packet->size;\r
131                         buffer_cond_.notify_all();\r
132                 }\r
133 \r
134                 graph_->update_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);\r
135                 graph_->update_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));\r
136 \r
137                 return result;\r
138         }\r
139                         \r
140         void run()\r
141         {               \r
142                 caspar::win32_exception::install_handler();\r
143 \r
144                 try\r
145                 {\r
146                         CASPAR_LOG(info) << print() << " Thread Started.";\r
147 \r
148                         while(is_running_)\r
149                         {\r
150                                 {\r
151                                         boost::unique_lock<boost::mutex> lock(buffer_mutex_);\r
152                                         while(full())\r
153                                                 buffer_cond_.timed_wait(lock, boost::posix_time::millisec(20));\r
154                                 }\r
155                                 read_next_packet();                     \r
156                         }\r
157 \r
158                         CASPAR_LOG(info) << print() << " Thread Stopped.";\r
159                 }\r
160                 catch(...)\r
161                 {\r
162                         CASPAR_LOG_CURRENT_EXCEPTION();\r
163                         is_running_ = false;\r
164                 }\r
165         }\r
166                         \r
167         void read_next_packet()\r
168         {               \r
169                 tbb::recursive_mutex::scoped_lock lock(mutex_);\r
170 \r
171                 auto packet = create_packet();\r
172                 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
173                 \r
174                 if(is_eof(ret))                                                                                                              \r
175                 {\r
176                         frame_number_   = 0;\r
177                         is_eof_                 = true;\r
178 \r
179                         if(loop_)\r
180                         {\r
181                                 do_seek(start_);\r
182                                 graph_->add_tag("seek");                \r
183                                 CASPAR_LOG(debug) << print() << " Looping.";                    \r
184                         }                                       \r
185                 }\r
186                 else\r
187                 {               \r
188                         THROW_ON_ERROR(ret, "av_read_frame", print());\r
189 \r
190                         if(packet->stream_index == default_stream_index_)\r
191                                 ++frame_number_;\r
192 \r
193                         THROW_ON_ERROR2(av_dup_packet(packet.get()), print());\r
194                                 \r
195                         // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.\r
196                         auto size = packet->size;\r
197                         auto data = packet->data;\r
198                         \r
199                         packet = safe_ptr<AVPacket>(packet.get(), [packet, size, data](AVPacket*)\r
200                         {\r
201                                 packet->size = size;\r
202                                 packet->data = data;\r
203                         });\r
204 \r
205                         buffer_.try_push(packet);\r
206                         buffer_size_ += packet->size;\r
207                                 \r
208                         graph_->update_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);\r
209                         graph_->update_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));\r
210                 }                       \r
211         }\r
212 \r
213         bool full() const\r
214         {\r
215                 return is_running_ && (is_eof_ || (buffer_size_ > MAX_BUFFER_SIZE || buffer_.size() > MAX_BUFFER_COUNT) && buffer_.size() > MIN_BUFFER_COUNT);\r
216         }\r
217         \r
218         void do_seek(const int64_t target)\r
219         {       \r
220                 CASPAR_LOG(debug) << print() << " Seeking: " << target;\r
221 \r
222                 int flags = AVSEEK_FLAG_FRAME;\r
223                 if(target == 0)\r
224                 {\r
225                         // Fix VP6 seeking\r
226                         int vid_stream_index = av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);\r
227                         if(vid_stream_index >= 0)\r
228                         {\r
229                                 auto codec_id = format_context_->streams[vid_stream_index]->codec->codec_id;\r
230                                 if(codec_id == CODEC_ID_VP6A || codec_id == CODEC_ID_VP6F || codec_id == CODEC_ID_VP6)\r
231                                         flags = AVSEEK_FLAG_BYTE;\r
232                         }\r
233                 }\r
234                 \r
235                 auto stream = format_context_->streams[default_stream_index_];\r
236                 auto codec  = stream->codec;\r
237                 auto fixed_target = (target*stream->time_base.den*codec->time_base.num)/(stream->time_base.num*codec->time_base.den);\r
238                 \r
239                 THROW_ON_ERROR2(avformat_seek_file(format_context_.get(), default_stream_index_, std::numeric_limits<int64_t>::min(), fixed_target, std::numeric_limits<int64_t>::max(), 0), print());          \r
240 \r
241                 is_eof_ = false;\r
242                 buffer_cond_.notify_all();\r
243 \r
244                 auto flush_packet       = create_packet();\r
245                 flush_packet->data      = nullptr;\r
246                 flush_packet->size      = 0;\r
247                 flush_packet->pos       = target;\r
248 \r
249                 buffer_.push(flush_packet);\r
250         }       \r
251 \r
252         void seek(int64_t target)\r
253         {\r
254                 tbb::recursive_mutex::scoped_lock lock(mutex_);\r
255 \r
256                 std::shared_ptr<AVPacket> packet;\r
257                 while(try_pop(packet))\r
258                 {\r
259                 }\r
260 \r
261                 do_seek(target);\r
262         }\r
263 \r
264         bool is_eof(int ret)\r
265         {\r
266                 if(ret == AVERROR(EIO))\r
267                         CASPAR_LOG(trace) << print() << " Received EIO, assuming EOF. ";\r
268                 if(ret == AVERROR_EOF)\r
269                         CASPAR_LOG(debug) << print() << " Received EOF. ";\r
270 \r
271                 return ret == AVERROR_EOF || ret == AVERROR(EIO) || frame_number_ >= length_; // av_read_frame doesn't always correctly return AVERROR_EOF;\r
272         }\r
273         \r
274         std::wstring print() const\r
275         {\r
276                 return L"ffmpeg_input[" + filename_ + L")]";\r
277         }\r
278 };\r
279 \r
280 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, size_t start, size_t length) \r
281         : impl_(new implementation(graph, filename, loop, start, length)){}\r
282 bool input::eof() const {return impl_->is_eof_;}\r
283 bool input::try_pop(std::shared_ptr<AVPacket>& packet){return impl_->try_pop(packet);}\r
284 safe_ptr<AVFormatContext> input::context(){return impl_->format_context_;}\r
285 void input::loop(bool value){impl_->loop_ = value;}\r
286 bool input::loop() const{return impl_->loop_;}\r
287 void input::seek(int64_t target){impl_->seek(target);}\r
288 }}\r