]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input.cpp
2.0.0.2: ffmpeg_producer: Change syntax for frame seek.
[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_;\r
62         const int                       length_;\r
63         int                                     eof_count_;\r
64                 \r
65         tbb::concurrent_bounded_queue<packet> video_packet_buffer_;\r
66         tbb::concurrent_bounded_queue<packet> 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, int length) \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_(std::max(start, 0))\r
82                 , length_(length)\r
83                 , eof_count_(length)\r
84         {                       \r
85                 graph_->set_color("input-buffer", diagnostics::color(1.0f, 1.0f, 0.0f));\r
86                 graph_->set_color("seek", diagnostics::color(0.5f, 1.0f, 0.5f));        \r
87 \r
88                 int errn;\r
89                 AVFormatContext* weak_format_context_ = nullptr;\r
90                 if((errn = av_open_input_file(&weak_format_context_, narrow(filename).c_str(), nullptr, 0, nullptr)) < 0 || weak_format_context_ == nullptr)\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                 format_context_.reset(weak_format_context_, av_close_input_file);\r
100                         \r
101                 if((errn = av_find_stream_info(format_context_.get())) < 0)\r
102                 {       \r
103                         BOOST_THROW_EXCEPTION(\r
104                                 file_read_error() << \r
105                                 source_info(narrow(print())) << \r
106                                 msg_info(av_error_str(errn)) <<\r
107                                 boost::errinfo_api_function("av_find_stream_info") <<\r
108                                 boost::errinfo_errno(AVUNERROR(errn)));\r
109                 }\r
110 \r
111                 video_codec_context_ = open_stream(CODEC_TYPE_VIDEO, video_s_index_);\r
112                 if(!video_codec_context_)\r
113                         CASPAR_LOG(warning) << print() << " Could not open any video stream.";\r
114                 else\r
115                         fix_time_base(video_codec_context_.get());\r
116                 \r
117                 audio_codex_context_ = open_stream(CODEC_TYPE_AUDIO, audio_s_index_);\r
118                 if(!audio_codex_context_)\r
119                         CASPAR_LOG(warning) << print() << " Could not open any audio stream.";\r
120                 else\r
121                         fix_time_base(audio_codex_context_.get());\r
122 \r
123                 if(!video_codec_context_ && !audio_codex_context_)\r
124                 {       \r
125                         BOOST_THROW_EXCEPTION(\r
126                                 file_read_error() << \r
127                                 msg_info(av_error_str(errn)) <<\r
128                                 source_info(narrow(print())) << \r
129                                 msg_info("No video or audio codec context found."));    \r
130                 }\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                 executor_.clear();\r
143                 executor_.stop();\r
144                 cond_.notify_all();\r
145         }\r
146                 \r
147         packet get_video_packet()\r
148         {\r
149                 return get_packet(video_packet_buffer_);\r
150         }\r
151 \r
152         packet get_audio_packet()\r
153         {\r
154                 return get_packet(audio_packet_buffer_);\r
155         }\r
156 \r
157         bool has_packet() const\r
158         {\r
159                 return !video_packet_buffer_.empty() || !audio_packet_buffer_.empty();\r
160         }\r
161                                 \r
162         double fps()\r
163         {\r
164                 return static_cast<double>(get_default_context()->time_base.den) / static_cast<double>(get_default_context()->time_base.num);\r
165         }\r
166 \r
167 private:\r
168 \r
169         void stop()\r
170         {\r
171                 executor_.stop();\r
172                 CASPAR_LOG(info) << print() << " Stopped.";\r
173         }\r
174                         \r
175         void fix_time_base(AVCodecContext* context) const // Some files give an invalid numerator, try to fix it.\r
176         {\r
177                 if(context && context->time_base.num == 1)\r
178                         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
179         }\r
180 \r
181         std::shared_ptr<AVCodecContext> open_stream(int codec_type, int& s_index) const\r
182         {               \r
183                 AVStream** streams_end = format_context_->streams+format_context_->nb_streams;\r
184                 AVStream** stream = std::find_if(format_context_->streams, streams_end, [&](AVStream* stream) \r
185                 {\r
186                         return stream != nullptr && stream->codec->codec_type == codec_type;\r
187                 });\r
188                 \r
189                 if(stream == streams_end) \r
190                         return nullptr;\r
191                 \r
192                 auto codec = avcodec_find_decoder((*stream)->codec->codec_id);                  \r
193                 if(codec == nullptr)\r
194                         return nullptr;\r
195                         \r
196                 if((-avcodec_open((*stream)->codec, codec)) > 0)                \r
197                         return nullptr;\r
198                 \r
199                 s_index = (*stream)->index;\r
200 \r
201                 return std::shared_ptr<AVCodecContext>((*stream)->codec, avcodec_close);\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                 try\r
212                 {\r
213                         AVPacket tmp_packet;\r
214                         safe_ptr<AVPacket> read_packet(&tmp_packet, av_free_packet);    \r
215 \r
216                         const int errn = av_read_frame(format_context_.get(), read_packet.get());\r
217                         if(is_eof(errn))\r
218                         {\r
219                                 if(loop_)\r
220                                 {\r
221                                         seek_frame(start_, AVSEEK_FLAG_BACKWARD);\r
222                                         // AVCodecContext.frame_number is not reset. Increase the target frame_number.\r
223                                         eof_count_ += length_; \r
224                                         graph_->add_tag("seek");        \r
225                                 }       \r
226                                 else\r
227                                         stop();\r
228                         }\r
229                         else if(errn < 0)\r
230                         {\r
231                                 BOOST_THROW_EXCEPTION(\r
232                                         invalid_operation() <<\r
233                                         msg_info(av_error_str(errn)) <<\r
234                                         source_info(narrow(print())) << \r
235                                         boost::errinfo_api_function("av_read_frame") <<\r
236                                         boost::errinfo_errno(AVUNERROR(errn)));\r
237                         }\r
238                         else\r
239                         {\r
240                                 if(read_packet->stream_index == video_s_index_)                 \r
241                                         video_packet_buffer_.try_push(packet(read_packet->data, read_packet->data + read_packet->size));        \r
242                                 else if(read_packet->stream_index)\r
243                                         audio_packet_buffer_.try_push(packet(read_packet->data, read_packet->data + read_packet->size));        \r
244                         }\r
245                                                 \r
246                         graph_->update_value("input-buffer", static_cast<float>(video_packet_buffer_.size())/static_cast<float>(PACKET_BUFFER_COUNT));          \r
247                 }\r
248                 catch(...)\r
249                 {\r
250                         stop();\r
251                         CASPAR_LOG_CURRENT_EXCEPTION();\r
252                         return;\r
253                 }\r
254                                 \r
255                 executor_.begin_invoke([this]{read_file();});           \r
256                 boost::unique_lock<boost::mutex> lock(mutex_);\r
257                 while(executor_.is_running() && audio_packet_buffer_.size() > PACKET_BUFFER_COUNT && video_packet_buffer_.size() > PACKET_BUFFER_COUNT)\r
258                         cond_.wait(lock);               \r
259         }\r
260 \r
261         void seek_frame(int64_t frame, int flags = 0)\r
262         {       \r
263                 // Convert from frames into seconds.\r
264                 auto ts = frame*static_cast<int64_t>((AV_TIME_BASE*get_default_context()->time_base.num) / get_default_context()->time_base.den);\r
265 \r
266                 const int errn = av_seek_frame(format_context_.get(), -1, ts, flags | AVSEEK_FLAG_FRAME);\r
267 \r
268                 if(errn < 0)\r
269                 {       \r
270                         BOOST_THROW_EXCEPTION(\r
271                                 invalid_operation() << \r
272                                 source_info(narrow(print())) << \r
273                                 msg_info(av_error_str(errn)) <<\r
274                                 boost::errinfo_api_function("seek_frame") <<\r
275                                 boost::errinfo_errno(AVUNERROR(errn)));\r
276                 }\r
277 \r
278                 // Notify decoders to flush buffers.\r
279                 video_packet_buffer_.try_push(flush_packet);    \r
280                 audio_packet_buffer_.try_push(flush_packet);\r
281         }               \r
282 \r
283         bool is_eof(int errn)\r
284         {\r
285                 if(length_ != -1)\r
286                         return get_default_context()->frame_number > eof_count_;                \r
287 \r
288                 return errn == AVERROR_EOF || errn == AVERROR_IO;\r
289         }\r
290                 \r
291         packet get_packet(tbb::concurrent_bounded_queue<packet>& buffer)\r
292         {\r
293                 packet packet;\r
294                 buffer.try_pop(packet);\r
295                 cond_.notify_all();\r
296                 return packet;\r
297         }\r
298 \r
299         std::wstring print() const\r
300         {\r
301                 return L"ffmpeg_input[" + filename_ + L"]";\r
302         }\r
303 };\r
304 \r
305 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, int start, int length) \r
306         : impl_(new implementation(graph, filename, loop, start, length)){}\r
307 const std::shared_ptr<AVCodecContext>& input::get_video_codec_context() const{return impl_->video_codec_context_;}\r
308 const std::shared_ptr<AVCodecContext>& input::get_audio_codec_context() const{return impl_->audio_codex_context_;}\r
309 bool input::has_packet() const{return impl_->has_packet();}\r
310 bool input::is_running() const {return impl_->executor_.is_running();}\r
311 packet input::get_video_packet(){return impl_->get_video_packet();}\r
312 packet input::get_audio_packet(){return impl_->get_audio_packet();}\r
313 double input::fps() const { return impl_->fps(); }\r
314 }