]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input.cpp
2.0.0.2: ffmpeg_input: Refactoring. Extracted "stream" class from input.
[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/mutex.h>\r
37 \r
38 #include <boost/range/iterator_range.hpp>\r
39 #include <boost/range/algorithm.hpp>\r
40 \r
41 extern "C" \r
42 {\r
43         #define __STDC_CONSTANT_MACROS\r
44         #define __STDC_LIMIT_MACROS\r
45         #include <libavformat/avformat.h>\r
46 }\r
47 \r
48 namespace caspar {\r
49         \r
50 static const size_t PACKET_BUFFER_COUNT = 100; // Assume that av_read_frame distance between audio and video packets is less than PACKET_BUFFER_COUNT.\r
51 \r
52 class stream\r
53 {\r
54         std::shared_ptr<AVCodecContext> ctx_;\r
55         int index_;\r
56         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>> buffer_;\r
57 \r
58 public:\r
59 \r
60         stream()\r
61                 : index_(-1)\r
62         {\r
63                 buffer_.set_capacity(PACKET_BUFFER_COUNT);\r
64         }\r
65 \r
66         int open(std::shared_ptr<AVFormatContext>& fctx, AVMediaType media_type)\r
67         {               \r
68                 const auto streams = boost::iterator_range<AVStream**>(fctx->streams, fctx->streams+fctx->nb_streams);\r
69                 const auto stream = boost::find_if(streams, [&](AVStream* stream) \r
70                 {\r
71                         return stream && stream->codec->codec_type == media_type;\r
72                 });\r
73                 \r
74                 if(stream == streams.end()) \r
75                         return AVERROR_STREAM_NOT_FOUND;\r
76                 \r
77                 auto codec = avcodec_find_decoder((*stream)->codec->codec_id);                  \r
78                 if(!codec)\r
79                         return AVERROR_DECODER_NOT_FOUND;\r
80                         \r
81                 index_ = (*stream)->index;\r
82 \r
83                 int errn = tbb_avcodec_open((*stream)->codec, codec);\r
84                 if(errn >= 0)\r
85                 {\r
86                         ctx_.reset((*stream)->codec, tbb_avcodec_close);\r
87 \r
88                         // Some files give an invalid time_base numerator, try to fix it.\r
89                         if(ctx_ && ctx_->time_base.num == 1)\r
90                                 ctx_->time_base.num = static_cast<int>(std::pow(10.0, static_cast<int>(std::log10(static_cast<float>(ctx_->time_base.den)))-1));\r
91                 }\r
92                 return errn;    \r
93         }\r
94 \r
95         std::shared_ptr<AVPacket> pop()\r
96         {\r
97                 std::shared_ptr<AVPacket> pkt;\r
98                 buffer_.try_pop(pkt);\r
99                 return pkt;\r
100         }\r
101 \r
102         void push(const std::shared_ptr<AVPacket>& pkt)\r
103         {\r
104                 if(pkt->stream_index != index_)\r
105                         return;\r
106 \r
107                 av_dup_packet(pkt.get());\r
108                 buffer_.push(pkt);      \r
109         }\r
110 \r
111         const std::shared_ptr<AVCodecContext>& ctx() { return ctx_; }\r
112 \r
113         operator bool(){return ctx_ != nullptr;}\r
114 \r
115         double fps() const { return !ctx_ ? -1.0 : static_cast<double>(ctx_->time_base.den) / static_cast<double>(ctx_->time_base.num); }\r
116 \r
117         bool empty() const { return buffer_.empty();}\r
118         int size() const { return buffer_.size();}\r
119 };\r
120                 \r
121 struct input::implementation : boost::noncopyable\r
122 {               \r
123         safe_ptr<diagnostics::graph> graph_;\r
124 \r
125         std::shared_ptr<AVFormatContext> format_context_;       // Destroy this last\r
126                 \r
127         const std::wstring      filename_;\r
128         const bool                      loop_;\r
129         const int                       start_;         \r
130         double                          fps_;\r
131 \r
132         stream video_stream_;\r
133         stream audio_stream_;\r
134                 \r
135         std::exception_ptr exception_;\r
136         executor executor_;\r
137 public:\r
138         explicit implementation(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start) \r
139                 : graph_(graph)\r
140                 , loop_(loop)\r
141                 , filename_(filename)\r
142                 , executor_(print())\r
143                 , start_(std::max(start, 0))\r
144         {               \r
145                 graph_->set_color("input-buffer", diagnostics::color(1.0f, 1.0f, 0.0f));\r
146                 graph_->set_color("seek", diagnostics::color(0.5f, 1.0f, 0.5f));        \r
147                 \r
148                 int errn;\r
149 \r
150                 AVFormatContext* weak_format_context_ = nullptr;\r
151                 errn = av_open_input_file(&weak_format_context_, narrow(filename).c_str(), nullptr, 0, nullptr);\r
152                 if(errn < 0 || weak_format_context_ == nullptr)\r
153                 {       \r
154                         BOOST_THROW_EXCEPTION(\r
155                                 file_read_error() << \r
156                                 source_info(narrow(print())) << \r
157                                 msg_info(av_error_str(errn)) <<\r
158                                 boost::errinfo_api_function("av_open_input_file") <<\r
159                                 boost::errinfo_errno(AVUNERROR(errn)) <<\r
160                                 boost::errinfo_file_name(narrow(filename)));\r
161                 }\r
162 \r
163                 format_context_.reset(weak_format_context_, av_close_input_file);\r
164                         \r
165                 errn = av_find_stream_info(format_context_.get());\r
166                 if(errn < 0)\r
167                 {       \r
168                         BOOST_THROW_EXCEPTION(\r
169                                 file_read_error() << \r
170                                 source_info(narrow(print())) << \r
171                                 msg_info(av_error_str(errn)) <<\r
172                                 boost::errinfo_api_function("av_find_stream_info") <<\r
173                                 boost::errinfo_errno(AVUNERROR(errn)));\r
174                 }\r
175                 \r
176                 errn = video_stream_.open(format_context_, AVMEDIA_TYPE_VIDEO);\r
177                 if(errn < 0)\r
178                         CASPAR_LOG(warning) << print() << L" Could not open video stream: " << widen(av_error_str(errn));\r
179                 \r
180                 errn = audio_stream_.open(format_context_, AVMEDIA_TYPE_AUDIO);\r
181                 if(errn < 0)\r
182                         CASPAR_LOG(warning) << print() << L" Could not open audio stream: " << widen(av_error_str(errn));\r
183                 \r
184                 if(!video_stream_ && !audio_stream_)\r
185                 {       \r
186                         BOOST_THROW_EXCEPTION(\r
187                                 file_read_error() << \r
188                                 source_info(narrow(print())) << \r
189                                 msg_info("No video or audio codec context found."));    \r
190                 }\r
191 \r
192                 fps_ = video_stream_ ? video_stream_.fps() : audio_stream_.fps();\r
193 \r
194                 if(start_ != 0)                 \r
195                         seek_frame(start_);\r
196                                         \r
197                 executor_.start();\r
198                 executor_.begin_invoke([this]{read_file();});\r
199                 CASPAR_LOG(info) << print() << " Started.";\r
200         }\r
201 \r
202         ~implementation()\r
203         {\r
204                 stop();\r
205         }\r
206                 \r
207         std::shared_ptr<AVPacket> get_video_packet()\r
208         {\r
209                 return video_stream_.pop();\r
210         }\r
211 \r
212         std::shared_ptr<AVPacket> get_audio_packet()\r
213         {\r
214                 return audio_stream_.pop();\r
215         }\r
216 \r
217         bool has_packet() const\r
218         {\r
219                 return !video_stream_.empty() || !audio_stream_.empty();\r
220         }\r
221                                 \r
222         double fps()\r
223         {\r
224                 return fps_;\r
225         }\r
226 \r
227 private:\r
228 \r
229         void stop()\r
230         {\r
231                 executor_.stop();\r
232                 get_video_packet();\r
233                 get_audio_packet();\r
234                 CASPAR_LOG(info) << print() << " Stopping.";\r
235         }\r
236                         \r
237         void read_file()\r
238         {               \r
239                 if(audio_stream_.size() > 4 && video_stream_.size() > 4)\r
240                         boost::this_thread::yield(); // There are enough packets, no hurry.\r
241 \r
242                 try\r
243                 {\r
244                         std::shared_ptr<AVPacket> read_packet(new AVPacket(), [](AVPacket* p)\r
245                         {\r
246                                 av_free_packet(p);\r
247                                 delete p;\r
248                         });\r
249 \r
250                         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
251                         if(is_eof(errn))                                                                                                                  // Use av_dup_packet to extend its life.\r
252                         {\r
253                                 if(loop_)\r
254                                 {\r
255                                         seek_frame(start_, AVSEEK_FLAG_BACKWARD);\r
256                                         graph_->add_tag("seek");                \r
257                                         CASPAR_LOG(info) << print() << " Received EOF. Looping.";                       \r
258                                 }       \r
259                                 else\r
260                                 {\r
261                                         stop();\r
262                                         CASPAR_LOG(info) << print() << " Received EOF. Stopping.";\r
263                                 }\r
264                         }\r
265                         else if(errn < 0)\r
266                         {\r
267                                 BOOST_THROW_EXCEPTION(\r
268                                         file_read_error() <<\r
269                                         msg_info(av_error_str(errn)) <<\r
270                                         source_info(narrow(print())) << \r
271                                         boost::errinfo_api_function("av_read_frame") <<\r
272                                         boost::errinfo_errno(AVUNERROR(errn)));\r
273                         }\r
274                         else\r
275                         {\r
276                                 video_stream_.push(read_packet);\r
277                                 audio_stream_.push(read_packet);\r
278                         }\r
279                                                 \r
280                         graph_->update_value("input-buffer", static_cast<float>(std::max(video_stream_.size(), audio_stream_.size()))/static_cast<float>(PACKET_BUFFER_COUNT));         \r
281                 }\r
282                 catch(...)\r
283                 {\r
284                         stop();\r
285                         CASPAR_LOG_CURRENT_EXCEPTION();\r
286                         return;\r
287                 }\r
288                                                 \r
289                 executor_.begin_invoke([this]{read_file();});           \r
290         }\r
291 \r
292         void seek_frame(int64_t frame, int flags = 0)\r
293         {       \r
294                 // Convert from frames into seconds.\r
295                 const auto ts = frame*static_cast<int64_t>(AV_TIME_BASE/fps_);\r
296 \r
297                 const int errn = av_seek_frame(format_context_.get(), -1, ts, flags | AVSEEK_FLAG_FRAME);\r
298                 if(errn < 0)\r
299                 {       \r
300                         BOOST_THROW_EXCEPTION(\r
301                                 invalid_operation() << \r
302                                 source_info(narrow(print())) << \r
303                                 msg_info(av_error_str(errn)) <<\r
304                                 boost::errinfo_api_function("av_seek_frame") <<\r
305                                 boost::errinfo_errno(AVUNERROR(errn)));\r
306                 }\r
307         }               \r
308 \r
309         bool is_eof(int errn)\r
310         {\r
311                 if(errn == AVERROR(EIO))\r
312                         CASPAR_LOG(warning) << print() << " Received EIO, assuming EOF";\r
313 \r
314                 return errn == AVERROR_EOF || errn == AVERROR(EIO); // av_read_frame doesn't always correctly return AVERROR_EOF;\r
315         }\r
316         \r
317         std::wstring print() const\r
318         {\r
319                 return L"ffmpeg_input[" + filename_ + L"]";\r
320         }\r
321 };\r
322 \r
323 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start) \r
324         : impl_(new implementation(graph, filename, loop, start)){}\r
325 const std::shared_ptr<AVCodecContext>& input::get_video_codec_context() const{return impl_->video_stream_.ctx();}\r
326 const std::shared_ptr<AVCodecContext>& input::get_audio_codec_context() const{return impl_->audio_stream_.ctx();}\r
327 bool input::has_packet() const{return impl_->has_packet();}\r
328 bool input::is_running() const {return impl_->executor_.is_running();}\r
329 std::shared_ptr<AVPacket> input::get_video_packet(){return impl_->get_video_packet();}\r
330 std::shared_ptr<AVPacket> input::get_audio_packet(){return impl_->get_audio_packet();}\r
331 double input::fps() const { return impl_->fps(); }\r
332 }