]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input.cpp
a4e8b4c9639e24f57446997b2e28f52f0eda1b02
[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 \r
29 #include <core/video_format.h>\r
30 \r
31 #include <common/concurrency/executor.h>\r
32 #include <common/diagnostics/graph.h>\r
33 \r
34 #include <tbb/concurrent_queue.h>\r
35 #include <tbb/mutex.h>\r
36 \r
37 #include <boost/range/iterator_range.hpp>\r
38 #include <boost/range/algorithm.hpp>\r
39 \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 = 50;\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         const int                       length_;\r
67         int                                     eof_count_;\r
68                 \r
69         tbb::concurrent_bounded_queue<packet> video_packet_buffer_;\r
70         tbb::concurrent_bounded_queue<packet> audio_packet_buffer_;\r
71 \r
72         boost::condition_variable       cond_;\r
73         boost::mutex                            mutex_;\r
74         \r
75         std::exception_ptr exception_;\r
76         executor executor_;\r
77 public:\r
78         explicit implementation(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start, int length) \r
79                 : graph_(graph)\r
80                 , loop_(loop)\r
81                 , video_s_index_(-1)\r
82                 , audio_s_index_(-1)\r
83                 , filename_(filename)\r
84                 , executor_(print())\r
85                 , start_(std::max(start, 0))\r
86                 , length_(length)\r
87                 , eof_count_(length)\r
88         {                       \r
89                 graph_->set_color("input-buffer", diagnostics::color(1.0f, 1.0f, 0.0f));\r
90                 graph_->set_color("seek", diagnostics::color(0.5f, 1.0f, 0.5f));        \r
91 \r
92                 int errn;\r
93                 AVFormatContext* weak_format_context_ = nullptr;\r
94                 if((errn = av_open_input_file(&weak_format_context_, narrow(filename).c_str(), nullptr, 0, nullptr)) < 0 || weak_format_context_ == nullptr)\r
95                         BOOST_THROW_EXCEPTION(\r
96                                 file_read_error() << \r
97                                 source_info(narrow(print())) << \r
98                                 msg_info(av_error_str(errn)) <<\r
99                                 boost::errinfo_api_function("av_open_input_file") <<\r
100                                 boost::errinfo_errno(AVUNERROR(errn)) <<\r
101                                 boost::errinfo_file_name(narrow(filename)));\r
102 \r
103                 format_context_.reset(weak_format_context_, av_close_input_file);\r
104                         \r
105                 if((errn = av_find_stream_info(format_context_.get())) < 0)\r
106                 {       \r
107                         BOOST_THROW_EXCEPTION(\r
108                                 file_read_error() << \r
109                                 source_info(narrow(print())) << \r
110                                 msg_info(av_error_str(errn)) <<\r
111                                 boost::errinfo_api_function("av_find_stream_info") <<\r
112                                 boost::errinfo_errno(AVUNERROR(errn)));\r
113                 }\r
114 \r
115                 video_codec_context_ = open_stream(CODEC_TYPE_VIDEO, video_s_index_);\r
116                 if(!video_codec_context_)\r
117                         CASPAR_LOG(warning) << print() << " Could not open any video stream.";\r
118                 else\r
119                         fix_time_base(video_codec_context_.get());\r
120                 \r
121                 audio_codex_context_ = open_stream(CODEC_TYPE_AUDIO, audio_s_index_);\r
122                 if(!audio_codex_context_)\r
123                         CASPAR_LOG(warning) << print() << " Could not open any audio stream.";\r
124                 else\r
125                         fix_time_base(audio_codex_context_.get());\r
126 \r
127                 if(!video_codec_context_ && !audio_codex_context_)\r
128                 {       \r
129                         BOOST_THROW_EXCEPTION(\r
130                                 file_read_error() << \r
131                                 msg_info(av_error_str(errn)) <<\r
132                                 source_info(narrow(print())) << \r
133                                 msg_info("No video or audio codec context found."));    \r
134                 }\r
135 \r
136                 if(start_ != 0)                 \r
137                         seek_frame(start_);\r
138                                         \r
139                 executor_.start();\r
140                 executor_.begin_invoke([this]{read_file();});\r
141                 CASPAR_LOG(info) << print() << " Started.";\r
142         }\r
143 \r
144         ~implementation()\r
145         {\r
146                 executor_.clear();\r
147                 executor_.stop();\r
148                 cond_.notify_all();\r
149         }\r
150                 \r
151         packet get_video_packet()\r
152         {\r
153                 return get_packet(video_packet_buffer_);\r
154         }\r
155 \r
156         packet get_audio_packet()\r
157         {\r
158                 return get_packet(audio_packet_buffer_);\r
159         }\r
160 \r
161         bool has_packet() const\r
162         {\r
163                 return !video_packet_buffer_.empty() || !audio_packet_buffer_.empty();\r
164         }\r
165                                 \r
166         double fps()\r
167         {\r
168                 return static_cast<double>(get_default_context()->time_base.den) / static_cast<double>(get_default_context()->time_base.num);\r
169         }\r
170 \r
171 private:\r
172 \r
173         void stop()\r
174         {\r
175                 executor_.stop();\r
176                 CASPAR_LOG(info) << print() << " Stopped.";\r
177         }\r
178                         \r
179         void fix_time_base(AVCodecContext* context) const // Some files give an invalid numerator, try to fix it.\r
180         {\r
181                 if(context && context->time_base.num == 1)\r
182                         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
183         }\r
184 \r
185         std::shared_ptr<AVCodecContext> open_stream(int codec_type, int& s_index) const\r
186         {               \r
187                 const auto streams = boost::iterator_range<AVStream**>(format_context_->streams, format_context_->streams+format_context_->nb_streams);\r
188                 const auto stream = boost::find_if(streams, [&](AVStream* stream) \r
189                 {\r
190                         return stream != nullptr && stream->codec->codec_type == codec_type;\r
191                 });\r
192                 \r
193                 if(stream == streams.end()) \r
194                         return nullptr;\r
195                 \r
196                 auto codec = avcodec_find_decoder((*stream)->codec->codec_id);                  \r
197                 if(codec == nullptr)\r
198                         return nullptr;\r
199                         \r
200                 if(avcodec_open((*stream)->codec, codec) < 0)           \r
201                         return nullptr;\r
202                 \r
203                 s_index = (*stream)->index;\r
204 \r
205                 return std::shared_ptr<AVCodecContext>((*stream)->codec, avcodec_close);\r
206         }\r
207         \r
208         std::shared_ptr<AVCodecContext>& get_default_context()\r
209         {\r
210                 return video_codec_context_ ? video_codec_context_ : audio_codex_context_;\r
211         }\r
212                 \r
213         void read_file()\r
214         {               \r
215                 if(audio_packet_buffer_.size() > 4 && video_packet_buffer_.size() > 4)\r
216                         boost::this_thread::yield(); // There is enough packets, no hurry.\r
217 \r
218                 try\r
219                 {\r
220                         AVPacket tmp_packet;\r
221                         safe_ptr<AVPacket> read_packet(&tmp_packet, av_free_packet);    \r
222 \r
223                         const int errn = av_read_frame(format_context_.get(), read_packet.get());\r
224                         if(is_eof(errn))\r
225                         {\r
226                                 if(loop_)\r
227                                 {\r
228                                         seek_frame(start_, AVSEEK_FLAG_BACKWARD);\r
229                                         // AVCodecContext.frame_number is not reset. Increase the target frame_number.\r
230                                         eof_count_ += length_; \r
231                                         graph_->add_tag("seek");        \r
232                                 }       \r
233                                 else\r
234                                         stop();\r
235                         }\r
236                         else if(errn < 0)\r
237                         {\r
238                                 BOOST_THROW_EXCEPTION(\r
239                                         invalid_operation() <<\r
240                                         msg_info(av_error_str(errn)) <<\r
241                                         source_info(narrow(print())) << \r
242                                         boost::errinfo_api_function("av_read_frame") <<\r
243                                         boost::errinfo_errno(AVUNERROR(errn)));\r
244                         }\r
245                         else\r
246                         {\r
247                                 if(read_packet->stream_index == video_s_index_)                 \r
248                                         video_packet_buffer_.try_push(packet(read_packet->data, read_packet->data + read_packet->size));        \r
249                                 else if(read_packet->stream_index)\r
250                                         audio_packet_buffer_.try_push(packet(read_packet->data, read_packet->data + read_packet->size));        \r
251                         }\r
252                                                 \r
253                         graph_->update_value("input-buffer", static_cast<float>(video_packet_buffer_.size())/static_cast<float>(PACKET_BUFFER_COUNT));          \r
254                 }\r
255                 catch(...)\r
256                 {\r
257                         stop();\r
258                         CASPAR_LOG_CURRENT_EXCEPTION();\r
259                         return;\r
260                 }\r
261                                 \r
262                 executor_.begin_invoke([this]{read_file();});           \r
263                 boost::unique_lock<boost::mutex> lock(mutex_);\r
264                 while(executor_.is_running() && audio_packet_buffer_.size() > PACKET_BUFFER_COUNT && video_packet_buffer_.size() > PACKET_BUFFER_COUNT)\r
265                         cond_.wait(lock);               \r
266         }\r
267 \r
268         void seek_frame(int64_t frame, int flags = 0)\r
269         {       \r
270                 // Convert from frames into seconds.\r
271                 const auto ts = frame*static_cast<int64_t>((AV_TIME_BASE*get_default_context()->time_base.num) / get_default_context()->time_base.den);\r
272 \r
273                 const int errn = av_seek_frame(format_context_.get(), -1, ts, flags | AVSEEK_FLAG_FRAME);\r
274 \r
275                 if(errn < 0)\r
276                 {       \r
277                         BOOST_THROW_EXCEPTION(\r
278                                 invalid_operation() << \r
279                                 source_info(narrow(print())) << \r
280                                 msg_info(av_error_str(errn)) <<\r
281                                 boost::errinfo_api_function("seek_frame") <<\r
282                                 boost::errinfo_errno(AVUNERROR(errn)));\r
283                 }\r
284 \r
285                 // Notify decoders to flush buffers.\r
286                 video_packet_buffer_.try_push(flush_packet);    \r
287                 audio_packet_buffer_.try_push(flush_packet);\r
288         }               \r
289 \r
290         bool is_eof(int errn)\r
291         {\r
292                 if(length_ != -1)\r
293                         return get_default_context()->frame_number > eof_count_;                \r
294 \r
295                 return errn == AVERROR_EOF || errn == AVERROR_IO;\r
296         }\r
297                 \r
298         packet get_packet(tbb::concurrent_bounded_queue<packet>& buffer)\r
299         {\r
300                 packet packet;\r
301                 if(buffer.try_pop(packet))\r
302                         cond_.notify_all();\r
303                 return packet;\r
304         }\r
305 \r
306         std::wstring print() const\r
307         {\r
308                 return L"ffmpeg_input[" + filename_ + L"]";\r
309         }\r
310 };\r
311 \r
312 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start, int length) \r
313         : impl_(new implementation(graph, filename, loop, start, length)){}\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 packet input::get_video_packet(){return impl_->get_video_packet();}\r
319 packet input::get_audio_packet(){return impl_->get_audio_packet();}\r
320 double input::fps() const { return impl_->fps(); }\r
321 }