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