]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input.cpp
2.0.0.2: ffmpeg-producer: Updated with "auto-mode" which will try to convert files...
[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/concurrency/executor.h>\r
33 #include <common/diagnostics/graph.h>\r
34 \r
35 #include <tbb/concurrent_queue.h>\r
36 #include <tbb/atomic.h>\r
37 \r
38 #include <boost/range/algorithm.hpp>\r
39 #include <boost/thread/condition_variable.hpp>\r
40 #include <boost/thread/mutex.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  = 64 * 1000000;\r
54         \r
55 struct input::implementation : boost::noncopyable\r
56 {               \r
57         safe_ptr<diagnostics::graph> graph_;\r
58 \r
59         std::shared_ptr<AVFormatContext> format_context_;       // Destroy this last\r
60                 \r
61         const std::wstring                      filename_;\r
62         const bool                                      loop_;\r
63         const int                                       start_;         \r
64 \r
65         size_t                                          buffer_size_limit_;\r
66         tbb::atomic<size_t>                     buffer_size_;\r
67         boost::condition_variable       cond_;\r
68         boost::mutex                            mutex_;\r
69 \r
70         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>> buffer_;\r
71                 \r
72         executor executor_;\r
73 public:\r
74         explicit implementation(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start) \r
75                 : graph_(graph)\r
76                 , loop_(loop)\r
77                 , filename_(filename)\r
78                 , executor_(print())\r
79                 , start_(std::max(start, 0))\r
80         {                       \r
81                 int errn;\r
82 \r
83                 buffer_.set_capacity(MAX_BUFFER_COUNT);\r
84 \r
85                 AVFormatContext* weak_format_context_ = nullptr;\r
86                 errn = av_open_input_file(&weak_format_context_, narrow(filename).c_str(), nullptr, 0, nullptr);\r
87                 if(errn < 0 || weak_format_context_ == nullptr)\r
88                 {       \r
89                         BOOST_THROW_EXCEPTION(\r
90                                 file_read_error() << \r
91                                 source_info(narrow(print())) << \r
92                                 msg_info(av_error_str(errn)) <<\r
93                                 boost::errinfo_api_function("av_open_input_file") <<\r
94                                 boost::errinfo_errno(AVUNERROR(errn)) <<\r
95                                 boost::errinfo_file_name(narrow(filename)));\r
96                 }\r
97 \r
98                 format_context_.reset(weak_format_context_, av_close_input_file);\r
99                         \r
100                 errn = av_find_stream_info(format_context_.get());\r
101                 if(errn < 0)\r
102                 {       \r
103                         BOOST_THROW_EXCEPTION(\r
104                                 file_read_error() << \r
105                                 source_info(narrow(print())) << \r
106                                 msg_info(av_error_str(errn)) <<\r
107                                 boost::errinfo_api_function("av_find_stream_info") <<\r
108                                 boost::errinfo_errno(AVUNERROR(errn)));\r
109                 }\r
110                 \r
111                 if(start_ != 0)                 \r
112                         seek_frame(start_);\r
113                                 \r
114                 graph_->set_color("seek", diagnostics::color(0.5f, 1.0f, 0.5f));        \r
115                 graph_->set_color("buffer-count", diagnostics::color(0.2f, 0.8f, 1.0f));\r
116                 graph_->set_color("buffer-size", diagnostics::color(0.2f, 0.4f, 1.0f)); \r
117 \r
118                 executor_.begin_invoke([this]{read_file();});\r
119                 CASPAR_LOG(info) << print() << " Started.";\r
120         }\r
121 \r
122         ~implementation()\r
123         {\r
124                 stop();\r
125                 // Unblock thread.\r
126                 std::shared_ptr<AVPacket> packet;\r
127                 buffer_.try_pop(packet);\r
128                 buffer_size_ = 0;\r
129                 cond_.notify_all();\r
130         }\r
131                 \r
132         bool try_pop(std::shared_ptr<AVPacket>& packet)\r
133         {\r
134                 bool result = buffer_.try_pop(packet);\r
135                 graph_->update_value("buffer-count", MAX_BUFFER_SIZE/static_cast<double>(buffer_.size()));\r
136                 if(packet)\r
137                 {\r
138                         buffer_size_ -= packet->size;\r
139                         graph_->update_value("buffer-size", MAX_BUFFER_SIZE/static_cast<double>(buffer_size_));\r
140                         cond_.notify_all();\r
141                 }\r
142                 return result;\r
143         }\r
144                 \r
145         AVStream* stream(AVMediaType media_type)\r
146         {\r
147                 const auto streams = boost::iterator_range<AVStream**>(format_context_->streams, format_context_->streams + format_context_->nb_streams);\r
148                 const auto it = boost::find_if(streams, [&](AVStream* stream) \r
149                 {\r
150                         return stream && stream->codec->codec_type == media_type;\r
151                 });\r
152                 \r
153                 if(it == streams.end()) \r
154                         return nullptr;\r
155 \r
156                 return *it;\r
157         }\r
158 \r
159 private:\r
160 \r
161         void stop()\r
162         {\r
163                 executor_.stop();\r
164                 \r
165                 CASPAR_LOG(info) << print() << " Stopping.";\r
166         }\r
167 \r
168         void read_file()\r
169         {               \r
170                 read_next_packet();\r
171                 executor_.begin_invoke([this]{read_file();});\r
172         }\r
173                         \r
174         void read_next_packet()\r
175         {               \r
176                 try\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                         const int errn = av_read_frame(format_context_.get(), read_packet.get()); // read_packet is only valid until next call of av_read_frame.\r
186                         if(is_eof(errn))                                                                                                                  // Use av_dup_packet to extend its life.\r
187                         {\r
188                                 if(loop_)\r
189                                 {\r
190                                         seek_frame(start_, AVSEEK_FLAG_BACKWARD);\r
191                                         graph_->add_tag("seek");                \r
192                                         //CASPAR_LOG(info) << print() << " Received EOF. Looping.";                     \r
193                                 }       \r
194                                 else\r
195                                 {\r
196                                         stop();\r
197                                         //CASPAR_LOG(info) << print() << " Received EOF. Stopping.";\r
198                                 }\r
199                         }\r
200                         else if(errn < 0)\r
201                         {\r
202                                 BOOST_THROW_EXCEPTION(\r
203                                         file_read_error() <<\r
204                                         msg_info(av_error_str(errn)) <<\r
205                                         source_info(narrow(print())) << \r
206                                         boost::errinfo_api_function("av_read_frame") <<\r
207                                         boost::errinfo_errno(AVUNERROR(errn)));\r
208                         }\r
209                         else\r
210                         {\r
211                                 av_dup_packet(read_packet.get());\r
212                                 buffer_.push(read_packet);\r
213 \r
214                                 graph_->update_value("buffer-count", MAX_BUFFER_SIZE/static_cast<double>(buffer_.size()));\r
215                                 \r
216                                 boost::unique_lock<boost::mutex> lock(mutex_);\r
217                                 while(buffer_size_ > MAX_BUFFER_SIZE && buffer_.size() > 2)\r
218                                         cond_.wait(lock);\r
219 \r
220                                 buffer_size_ += read_packet->size;\r
221 \r
222                                 graph_->update_value("buffer-size", MAX_BUFFER_SIZE/static_cast<double>(buffer_size_));\r
223                         }                                                       \r
224                 }\r
225                 catch(...)\r
226                 {\r
227                         stop();\r
228                         CASPAR_LOG_CURRENT_EXCEPTION();\r
229                         return;\r
230                 }       \r
231         }\r
232 \r
233         void seek_frame(int64_t frame, int flags = 0)\r
234         {       \r
235                 static const AVRational base_q = {1, AV_TIME_BASE};\r
236 \r
237                 // Convert from frames into seconds.\r
238                 auto seek_target = frame;//*static_cast<int64_t>(AV_TIME_BASE/fps_);\r
239 \r
240                 int stream_index = -1;//video_stream_.index() >= 0 ? video_stream_.index() : audio_stream_.index();\r
241 \r
242                 //if(stream_index >= 0)         \r
243                 //      seek_target = av_rescale_q(seek_target, base_q, format_context_->streams[stream_index]->time_base);\r
244 \r
245                 const int errn = av_seek_frame(format_context_.get(), stream_index, seek_target, flags);\r
246                 if(errn < 0)\r
247                 {       \r
248                         BOOST_THROW_EXCEPTION(\r
249                                 invalid_operation() << \r
250                                 source_info(narrow(print())) << \r
251                                 msg_info(av_error_str(errn)) <<\r
252                                 boost::errinfo_api_function("av_seek_frame") <<\r
253                                 boost::errinfo_errno(AVUNERROR(errn)));\r
254                 }\r
255 \r
256                 buffer_.push(nullptr);\r
257         }               \r
258 \r
259         bool is_eof(int errn)\r
260         {\r
261                 //if(errn == AVERROR(EIO))\r
262                 //      CASPAR_LOG(warning) << print() << " Received EIO, assuming EOF";\r
263 \r
264                 return errn == AVERROR_EOF || errn == AVERROR(EIO); // av_read_frame doesn't always correctly return AVERROR_EOF;\r
265         }\r
266         \r
267         std::wstring print() const\r
268         {\r
269                 return L"ffmpeg_input[" + filename_ + L")]";\r
270         }\r
271 };\r
272 \r
273 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start, int length) \r
274         : impl_(new implementation(graph, filename, loop, start)){}\r
275 AVStream* input::stream(AVMediaType media_type){return impl_->stream(media_type);}\r
276 bool input::eof() const {return !impl_->executor_.is_running();}\r
277 bool input::try_pop(std::shared_ptr<AVPacket>& packet){return impl_->try_pop(packet);}\r
278 }