]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input.cpp
2.0.0.2: ffmpeg_producer: Improved error-handling.
[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 #include "..\stdafx.h"\r
21 \r
22 #include "input.h"\r
23 #include "../ffmpeg_error.h"\r
24 \r
25 #include <core/video_format.h>\r
26 \r
27 #include <common/concurrency/executor.h>\r
28 #include <common/diagnostics/graph.h>\r
29 \r
30 #include <tbb/concurrent_queue.h>\r
31 #include <tbb/mutex.h>\r
32 \r
33 #if defined(_MSC_VER)\r
34 #pragma warning (disable : 4244)\r
35 #endif\r
36 \r
37 extern "C" \r
38 {\r
39         #define __STDC_CONSTANT_MACROS\r
40         #define __STDC_LIMIT_MACROS\r
41         #include <libavformat/avformat.h>\r
42 }\r
43 \r
44 namespace caspar {\r
45                 \r
46 struct input::implementation : boost::noncopyable\r
47 {               \r
48         static const size_t PACKET_BUFFER_COUNT = 25;\r
49 \r
50         safe_ptr<diagnostics::graph> graph_;\r
51 \r
52         std::shared_ptr<AVFormatContext> format_context_;       // Destroy this last\r
53 \r
54         std::shared_ptr<AVCodecContext> video_codec_context_;\r
55         std::shared_ptr<AVCodecContext> audio_codex_context_;\r
56         \r
57         const std::wstring      filename_;\r
58         const bool                      loop_;\r
59         int                                     video_s_index_;\r
60         int                                     audio_s_index_;\r
61         const int                       start_frame_;\r
62         const int                       end_frame_;\r
63         int                                     eof_count_;\r
64                 \r
65         tbb::concurrent_bounded_queue<std::shared_ptr<aligned_buffer>> video_packet_buffer_;\r
66         tbb::concurrent_bounded_queue<std::shared_ptr<aligned_buffer>> audio_packet_buffer_;\r
67 \r
68         boost::condition_variable       cond_;\r
69         boost::mutex                            mutex_;\r
70         \r
71         std::exception_ptr exception_;\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_frame, int end_frame) \r
75                 : graph_(graph)\r
76                 , loop_(loop)\r
77                 , video_s_index_(-1)\r
78                 , audio_s_index_(-1)\r
79                 , filename_(filename)\r
80                 , executor_(print())\r
81                 , start_frame_(std::max(start_frame, 0))\r
82                 , end_frame_(end_frame)\r
83                 , eof_count_(end_frame-start_frame)\r
84         {                       \r
85                 if(end_frame_ > 0 && end_frame <= start_frame_)\r
86                 {       \r
87                         BOOST_THROW_EXCEPTION(\r
88                                 invalid_argument() << \r
89                                 source_info(narrow(print())) << \r
90                                 msg_info("End-frame cannot be lower than start-frame."));       \r
91                 }\r
92 \r
93                 graph_->set_color("input-buffer", diagnostics::color(1.0f, 1.0f, 0.0f));\r
94                 graph_->set_color("seek", diagnostics::color(0.5f, 1.0f, 0.5f));        \r
95 \r
96                 int errn;\r
97                 AVFormatContext* weak_format_context_ = nullptr;\r
98                 if((errn = av_open_input_file(&weak_format_context_, narrow(filename).c_str(), nullptr, 0, nullptr)) < 0 || weak_format_context_ == nullptr)\r
99                         BOOST_THROW_EXCEPTION(\r
100                                 file_read_error() << \r
101                                 source_info(narrow(print())) << \r
102                                 msg_info(av_error_str(errn)) <<\r
103                                 boost::errinfo_api_function("av_open_input_file") <<\r
104                                 boost::errinfo_errno(AVUNERROR(errn)) <<\r
105                                 boost::errinfo_file_name(narrow(filename)));\r
106 \r
107                 format_context_.reset(weak_format_context_, av_close_input_file);\r
108                         \r
109                 if((errn = av_find_stream_info(format_context_.get())) < 0)\r
110                 {       \r
111                         BOOST_THROW_EXCEPTION(\r
112                                 file_read_error() << \r
113                                 source_info(narrow(print())) << \r
114                                 msg_info(av_error_str(errn)) <<\r
115                                 boost::errinfo_api_function("av_find_stream_info") <<\r
116                                 boost::errinfo_errno(AVUNERROR(errn)));\r
117                 }\r
118 \r
119                 video_codec_context_ = open_stream(CODEC_TYPE_VIDEO, video_s_index_);\r
120                 if(!video_codec_context_)\r
121                         CASPAR_LOG(warning) << print() << " Could not open any video stream.";\r
122                 else\r
123                         fix_time_base(video_codec_context_.get());\r
124                 \r
125                 audio_codex_context_ = open_stream(CODEC_TYPE_AUDIO, audio_s_index_);\r
126                 if(!audio_codex_context_)\r
127                         CASPAR_LOG(warning) << print() << " Could not open any audio stream.";\r
128                 else\r
129                         fix_time_base(audio_codex_context_.get());\r
130 \r
131                 if(!video_codec_context_ && !audio_codex_context_)\r
132                 {       \r
133                         BOOST_THROW_EXCEPTION(\r
134                                 file_read_error() << \r
135                                 msg_info(av_error_str(errn)) <<\r
136                                 source_info(narrow(print())) << \r
137                                 msg_info("No video or audio codec context found."));    \r
138                 }\r
139 \r
140                 if(start_frame_ != 0)                   \r
141                         seek_frame(start_frame_);\r
142                                         \r
143                 executor_.start();\r
144                 executor_.begin_invoke([this]{read_file();});\r
145                 CASPAR_LOG(info) << print() << " Started.";\r
146         }\r
147 \r
148         ~implementation()\r
149         {\r
150                 executor_.clear();\r
151                 executor_.stop();\r
152                 cond_.notify_all();\r
153         }\r
154                 \r
155         std::shared_ptr<aligned_buffer> get_video_packet()\r
156         {\r
157                 return get_packet(video_packet_buffer_);\r
158         }\r
159 \r
160         std::shared_ptr<aligned_buffer> get_audio_packet()\r
161         {\r
162                 return get_packet(audio_packet_buffer_);\r
163         }\r
164 \r
165         bool has_packet() const\r
166         {\r
167                 return !video_packet_buffer_.empty() || !audio_packet_buffer_.empty();\r
168         }\r
169                                 \r
170         double fps()\r
171         {\r
172                 return static_cast<double>(get_default_context()->time_base.den) / static_cast<double>(get_default_context()->time_base.num);\r
173         }\r
174 \r
175 private:\r
176 \r
177         void stop()\r
178         {\r
179                 executor_.stop();\r
180                 CASPAR_LOG(info) << print() << " Stopped.";\r
181         }\r
182                         \r
183         void fix_time_base(AVCodecContext* context) const // Some files give an invalid numerator, try to fix it.\r
184         {\r
185                 if(context && context->time_base.num == 1)\r
186                         context->time_base.num = static_cast<int>(std::pow(10.0, static_cast<int>(std::log10(static_cast<float>(context->time_base.den)))-1));\r
187         }\r
188 \r
189         std::shared_ptr<AVCodecContext> open_stream(int codec_type, int& s_index) const\r
190         {               \r
191                 AVStream** streams_end = format_context_->streams+format_context_->nb_streams;\r
192                 AVStream** stream = std::find_if(format_context_->streams, streams_end, [&](AVStream* stream) \r
193                 {\r
194                         return stream != nullptr && stream->codec->codec_type == codec_type;\r
195                 });\r
196                 \r
197                 if(stream == streams_end) \r
198                         return nullptr;\r
199                 \r
200                 auto codec = avcodec_find_decoder((*stream)->codec->codec_id);                  \r
201                 if(codec == nullptr)\r
202                         return nullptr;\r
203                         \r
204                 if((-avcodec_open((*stream)->codec, codec)) > 0)                \r
205                         return nullptr;\r
206                 \r
207                 s_index = (*stream)->index;\r
208 \r
209                 return std::shared_ptr<AVCodecContext>((*stream)->codec, avcodec_close);\r
210         }\r
211         \r
212         std::shared_ptr<AVCodecContext>& get_default_context()\r
213         {\r
214                 return video_codec_context_ ? video_codec_context_ : audio_codex_context_;\r
215         }\r
216                 \r
217         void read_file()\r
218         {               \r
219                 try\r
220                 {\r
221                         AVPacket tmp_packet;\r
222                         safe_ptr<AVPacket> read_packet(&tmp_packet, av_free_packet);    \r
223 \r
224                         const int errn = av_read_frame(format_context_.get(), read_packet.get());\r
225                         if(is_eof(errn))\r
226                         {\r
227                                 if(loop_)\r
228                                 {\r
229                                         seek_frame(start_frame_, AVSEEK_FLAG_BACKWARD);\r
230                                         // AVCodecContext.frame_number is not reset. Increase the target frame_number.\r
231                                         eof_count_ += end_frame_ - start_frame_; \r
232                                         graph_->add_tag("seek");        \r
233                                 }       \r
234                                 else\r
235                                         stop();\r
236                         }\r
237                         else if(errn < 0)\r
238                         {\r
239                                 BOOST_THROW_EXCEPTION(\r
240                                         invalid_operation() <<\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                                         video_packet_buffer_.try_push(std::make_shared<aligned_buffer>(read_packet->data, read_packet->data + read_packet->size));      \r
250                                 else if(read_packet->stream_index == audio_s_index_)    \r
251                                         audio_packet_buffer_.try_push(std::make_shared<aligned_buffer>(read_packet->data, read_packet->data + read_packet->size));      \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                 boost::unique_lock<boost::mutex> lock(mutex_);\r
265                 while(executor_.is_running() && audio_packet_buffer_.size() > PACKET_BUFFER_COUNT && video_packet_buffer_.size() > PACKET_BUFFER_COUNT)\r
266                         cond_.wait(lock);               \r
267         }\r
268 \r
269         void seek_frame(int64_t frame, int flags = 0)\r
270         {       \r
271                 // Convert from frames into seconds.\r
272                 auto ts = frame*static_cast<int64_t>((AV_TIME_BASE*get_default_context()->time_base.num) / get_default_context()->time_base.den);\r
273 \r
274                 const int errn = av_seek_frame(format_context_.get(), -1, ts, flags | AVSEEK_FLAG_FRAME);\r
275 \r
276                 if(errn < 0)\r
277                 {       \r
278                         BOOST_THROW_EXCEPTION(\r
279                                 invalid_operation() << \r
280                                 source_info(narrow(print())) << \r
281                                 msg_info(av_error_str(errn)) <<\r
282                                 boost::errinfo_api_function("seek_frame") <<\r
283                                 boost::errinfo_errno(AVUNERROR(errn)));\r
284                 }\r
285 \r
286                 // Notify decoders to flush buffers.\r
287                 video_packet_buffer_.try_push(std::make_shared<aligned_buffer>());      \r
288                 audio_packet_buffer_.try_push(std::make_shared<aligned_buffer>());\r
289         }\r
290                 \r
291 \r
292         bool is_eof(int errn)\r
293         {\r
294                 if(end_frame_ != -1)\r
295                         return get_default_context()->frame_number > eof_count_;                \r
296 \r
297                 return errn == AVERROR_EOF || errn == AVERROR_IO;\r
298         }\r
299                 \r
300         std::shared_ptr<aligned_buffer> get_packet(tbb::concurrent_bounded_queue<std::shared_ptr<aligned_buffer>>& buffer)\r
301         {\r
302                 cond_.notify_all();\r
303                 std::shared_ptr<aligned_buffer> packet;\r
304                 return buffer.try_pop(packet) ? packet : nullptr;\r
305         }\r
306 \r
307         std::wstring print() const\r
308         {\r
309                 return L"ffmpeg_input[" + filename_ + L"]";\r
310         }\r
311 };\r
312 \r
313 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start_frame, int end_frame) : impl_(new implementation(graph, filename, loop, start_frame, end_frame)){}\r
314 const std::shared_ptr<AVCodecContext>& input::get_video_codec_context() const{return impl_->video_codec_context_;}\r
315 const std::shared_ptr<AVCodecContext>& input::get_audio_codec_context() const{return impl_->audio_codex_context_;}\r
316 bool input::has_packet() const{return impl_->has_packet();}\r
317 bool input::is_running() const {return impl_->executor_.is_running();}\r
318 std::shared_ptr<aligned_buffer> input::get_video_packet(){return impl_->get_video_packet();}\r
319 std::shared_ptr<aligned_buffer> input::get_audio_packet(){return impl_->get_audio_packet();}\r
320 double input::fps() const { return impl_->fps(); }\r
321 }