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