]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input.cpp
2.0. Refactoring
[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 \r
34 #include <tbb/concurrent_queue.h>\r
35 #include <tbb/atomic.h>\r
36 \r
37 #include <boost/range/algorithm.hpp>\r
38 #include <boost/thread/condition_variable.hpp>\r
39 #include <boost/thread/mutex.hpp>\r
40 #include <boost/thread/thread.hpp>\r
41 #include <boost/range/iterator_range.hpp>\r
42 \r
43 extern "C" \r
44 {\r
45         #define __STDC_CONSTANT_MACROS\r
46         #define __STDC_LIMIT_MACROS\r
47         #include <libavformat/avformat.h>\r
48 }\r
49 \r
50 namespace caspar {\r
51 \r
52 static const size_t MAX_BUFFER_COUNT = 128;\r
53 static const size_t MAX_BUFFER_SIZE  = 32 * 1000000;\r
54         \r
55 struct input::implementation : boost::noncopyable\r
56 {               \r
57         std::shared_ptr<AVFormatContext>                                                        format_context_; // Destroy this last\r
58 \r
59         safe_ptr<diagnostics::graph>                                                            graph_;\r
60                 \r
61         const std::wstring                                                                                      filename_;\r
62         const bool                                                                                                      loop_;\r
63         const int                                                                                                       start_;         \r
64         \r
65         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>>        buffer_;\r
66         tbb::atomic<size_t>                                                                                     buffer_size_;\r
67         boost::condition_variable                                                                       buffer_cond_;\r
68         boost::mutex                                                                                            buffer_mutex_;\r
69                 \r
70         boost::thread                                                                                           thread_;\r
71         tbb::atomic<bool>                                                                                       is_running_;\r
72 public:\r
73         explicit implementation(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start) \r
74                 : graph_(graph)\r
75                 , loop_(loop)\r
76                 , filename_(filename)\r
77                 , start_(std::max(start, 0))\r
78         {                       \r
79                 is_running_ = true;\r
80 \r
81                 int ret;\r
82 \r
83                 AVFormatContext* weak_format_context_ = nullptr;\r
84                 ret = avformat_open_input(&weak_format_context_, narrow(filename).c_str(), nullptr, nullptr);\r
85                 if(ret < 0 || weak_format_context_ == nullptr)\r
86                 {       \r
87                         BOOST_THROW_EXCEPTION(\r
88                                 file_read_error() << \r
89                                 source_info(narrow(print())) << \r
90                                 msg_info(av_error_str(ret)) <<\r
91                                 boost::errinfo_api_function("av_open_input_file") <<\r
92                                 boost::errinfo_errno(AVUNERROR(ret)) <<\r
93                                 boost::errinfo_file_name(narrow(filename)));\r
94                 }\r
95 \r
96                 format_context_.reset(weak_format_context_, av_close_input_file);\r
97                         \r
98                 ret = avformat_find_stream_info(format_context_.get(), nullptr);\r
99                 if(ret < 0)\r
100                 {       \r
101                         BOOST_THROW_EXCEPTION(\r
102                                 file_read_error() << \r
103                                 source_info(narrow(print())) << \r
104                                 msg_info(av_error_str(ret)) <<\r
105                                 boost::errinfo_api_function("av_find_stream_info") <<\r
106                                 boost::errinfo_errno(AVUNERROR(ret)));\r
107                 }\r
108                 \r
109                 if(start_ != 0)                 \r
110                         seek_frame(start_);\r
111                 \r
112                 for(int n = 0; n < 16 && !full(); ++n)\r
113                         read_next_packet();\r
114                                                 \r
115                 graph_->set_color("seek", diagnostics::color(0.5f, 1.0f, 0.5f));        \r
116                 graph_->set_color("buffer-count", diagnostics::color(0.2f, 0.8f, 1.0f));\r
117                 graph_->set_color("buffer-size", diagnostics::color(0.2f, 0.4f, 1.0f)); \r
118 \r
119                 thread_ = boost::thread([this]{run();});\r
120         }\r
121 \r
122         ~implementation()\r
123         {\r
124                 is_running_ = false;\r
125                 buffer_cond_.notify_all();\r
126                 thread_.join();\r
127         }\r
128                 \r
129         bool try_pop(std::shared_ptr<AVPacket>& packet)\r
130         {\r
131                 const bool result = buffer_.try_pop(packet);\r
132 \r
133                 if(result)\r
134                 {\r
135                         if(packet)\r
136                                 buffer_size_ -= packet->size;\r
137                         buffer_cond_.notify_all();\r
138                 }\r
139 \r
140                 graph_->update_value("buffer-size", MAX_BUFFER_SIZE/static_cast<double>(buffer_size_));\r
141                 graph_->update_value("buffer-count", MAX_BUFFER_SIZE/static_cast<double>(buffer_.size()));\r
142 \r
143                 return result;\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                 std::shared_ptr<AVPacket> read_packet(new AVPacket, [](AVPacket* p)\r
177                 {\r
178                         av_free_packet(p);\r
179                         delete p;\r
180                 });\r
181                 av_init_packet(read_packet.get());\r
182 \r
183                 const int ret = av_read_frame(format_context_.get(), read_packet.get()); // read_packet is only valid until next call of av_read_frame.\r
184                 if(is_eof(ret))                                                                                                              // Use av_dup_packet to extend its life.\r
185                 {\r
186                         if(loop_)\r
187                         {\r
188                                 seek_frame(start_, AVSEEK_FLAG_BACKWARD);\r
189                                 graph_->add_tag("seek");                \r
190                                 CASPAR_LOG(trace) << print() << " Received EOF. Looping.";                      \r
191                         }       \r
192                         else\r
193                         {\r
194                                 is_running_ = false;\r
195                                 CASPAR_LOG(trace) << print() << " Received EOF. Stopping.";\r
196                         }\r
197                 }\r
198                 else if(ret < 0)\r
199                 {\r
200                         BOOST_THROW_EXCEPTION(\r
201                                 file_read_error() <<\r
202                                 msg_info(av_error_str(ret)) <<\r
203                                 source_info(narrow(print())) << \r
204                                 boost::errinfo_api_function("av_read_frame") <<\r
205                                 boost::errinfo_errno(AVUNERROR(ret)));\r
206                 }\r
207                 else\r
208                 {               \r
209                         const int ret = av_dup_packet(read_packet.get());\r
210                         if(ret < 0)\r
211                         {\r
212                                 BOOST_THROW_EXCEPTION(\r
213                                         invalid_operation() <<\r
214                                         msg_info(av_error_str(ret)) <<\r
215                                         source_info(narrow(print())) << \r
216                                         boost::errinfo_api_function("av_dup_packet") <<\r
217                                         boost::errinfo_errno(AVUNERROR(ret)));\r
218                         }\r
219                                 \r
220                         // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.\r
221                         auto size = read_packet->size;\r
222                         auto data = read_packet->data;\r
223 \r
224                         read_packet = std::shared_ptr<AVPacket>(read_packet.get(), [=](AVPacket*)\r
225                         {\r
226                                 read_packet->size = size;\r
227                                 read_packet->data = data;\r
228                         });\r
229 \r
230                         buffer_.try_push(read_packet);\r
231                         buffer_size_ += read_packet->size;\r
232                                 \r
233                         graph_->update_value("buffer-count", MAX_BUFFER_SIZE/static_cast<double>(buffer_.size()));\r
234                         graph_->update_value("buffer-size", MAX_BUFFER_SIZE/static_cast<double>(buffer_size_));\r
235                 }                       \r
236         }\r
237 \r
238         bool full() const\r
239         {\r
240                 return is_running_ && buffer_size_ > MAX_BUFFER_SIZE && buffer_.size() > MAX_BUFFER_COUNT;\r
241         }\r
242 \r
243         void seek_frame(int64_t frame, int flags = 0)\r
244         {       \r
245                 static const AVRational base_q = {1, AV_TIME_BASE};\r
246 \r
247                 int stream_index = av_find_default_stream_index(format_context_.get());\r
248                 \r
249                 if(stream_index < 0)\r
250                 {       \r
251                         BOOST_THROW_EXCEPTION(\r
252                                 invalid_operation() << \r
253                                 source_info(narrow(print())) << \r
254                                 msg_info(av_error_str(stream_index)) <<\r
255                                 boost::errinfo_api_function("av_find_default_stream_index") <<\r
256                                 boost::errinfo_errno(AVUNERROR(stream_index)));\r
257                 }\r
258                                                 \r
259                 const int ret = av_seek_frame(format_context_.get(), stream_index, frame, flags);\r
260                 if(ret < 0)\r
261                 {       \r
262                         BOOST_THROW_EXCEPTION(\r
263                                 invalid_operation() << \r
264                                 source_info(narrow(print())) << \r
265                                 msg_info(av_error_str(ret)) <<\r
266                                 boost::errinfo_api_function("av_seek_frame") <<\r
267                                 boost::errinfo_errno(AVUNERROR(ret)));\r
268                 }\r
269 \r
270                 buffer_.push(nullptr);\r
271         }               \r
272 \r
273         bool is_eof(int ret)\r
274         {\r
275                 if(ret == AVERROR(EIO))\r
276                         CASPAR_LOG(debug) << print() << " Received EIO, assuming EOF.";\r
277                 //if(ret == AVERROR_EOF)\r
278                 //      CASPAR_LOG(info) << print() << " Received EOF.";\r
279 \r
280                 return ret == AVERROR_EOF || ret == AVERROR(EIO); // av_read_frame doesn't always correctly return AVERROR_EOF;\r
281         }\r
282         \r
283         std::wstring print() const\r
284         {\r
285                 return L"ffmpeg_input[" + filename_ + L")]";\r
286         }\r
287 };\r
288 \r
289 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start, int length) \r
290         : impl_(new implementation(graph, filename, loop, start)){}\r
291 bool input::eof() const {return !impl_->is_running_;}\r
292 bool input::try_pop(std::shared_ptr<AVPacket>& packet){return impl_->try_pop(packet);}\r
293 std::shared_ptr<AVFormatContext> input::context(){return impl_->format_context_;}\r
294 }