]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input.cpp
2.0.0.2:
[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 \r
24 #include <core/video_format.h>\r
25 \r
26 #include <common/concurrency/executor.h>\r
27 #include <common/diagnostics/graph.h>\r
28 \r
29 #include <tbb/concurrent_queue.h>\r
30 #include <tbb/queuing_mutex.h>\r
31 \r
32 #include <boost/exception/error_info.hpp>\r
33 #include <boost/thread/once.hpp>\r
34 #include <boost/thread/thread.hpp>\r
35 \r
36 #include <errno.h>\r
37 #include <system_error>\r
38                 \r
39 #if defined(_MSC_VER)\r
40 #pragma warning (disable : 4244)\r
41 #endif\r
42 \r
43 extern "C" \r
44 {\r
45         #define __STDC_CONSTANT_MACROS\r
46         #define __STDC_LIMIT_MACROS\r
47         #include <libavformat/avformat.h>\r
48 }\r
49 \r
50 namespace caspar {\r
51                 \r
52 struct input::implementation : boost::noncopyable\r
53 {               \r
54         static const size_t PACKET_BUFFER_COUNT = 25;\r
55 \r
56         safe_ptr<diagnostics::graph> graph_;\r
57 \r
58         std::shared_ptr<AVFormatContext> format_context_;       // Destroy this last\r
59 \r
60         std::shared_ptr<AVCodecContext> video_codec_context_;\r
61         std::shared_ptr<AVCodecContext> audio_codex_context_;\r
62         \r
63         const std::wstring filename_;\r
64 \r
65         bool loop_;\r
66         int video_s_index_;\r
67         int     audio_s_index_;\r
68                 \r
69         tbb::concurrent_bounded_queue<std::shared_ptr<aligned_buffer>> video_packet_buffer_;\r
70         tbb::concurrent_bounded_queue<std::shared_ptr<aligned_buffer>> 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) \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         {                       \r
86                 graph_->set_color("input-buffer", diagnostics::color(1.0f, 1.0f, 0.0f));\r
87                 graph_->set_color("seek", diagnostics::color(0.5f, 1.0f, 0.5f));        \r
88 \r
89                 int errn;\r
90                 AVFormatContext* weak_format_context_ = nullptr;\r
91                 if((errn = av_open_input_file(&weak_format_context_, narrow(filename).c_str(), nullptr, 0, nullptr)) < 0 || weak_format_context_ == nullptr)\r
92                         BOOST_THROW_EXCEPTION(\r
93                                 file_read_error() << \r
94                                 source_info(narrow(print())) << \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                         BOOST_THROW_EXCEPTION(\r
103                                 file_read_error() << \r
104                                 source_info(narrow(print())) << \r
105                                 boost::errinfo_api_function("av_find_stream_info") <<\r
106                                 boost::errinfo_errno(AVUNERROR(errn)));\r
107 \r
108                 video_codec_context_ = open_stream(CODEC_TYPE_VIDEO, video_s_index_);\r
109                 if(!video_codec_context_)\r
110                         CASPAR_LOG(warning) << print() << " Could not open any video stream.";\r
111                 else\r
112                         fix_time_base(video_codec_context_.get());\r
113                 \r
114                 audio_codex_context_ = open_stream(CODEC_TYPE_AUDIO, audio_s_index_);\r
115                 if(!audio_codex_context_)\r
116                         CASPAR_LOG(warning) << print() << " Could not open any audio stream.";\r
117                 else\r
118                         fix_time_base(video_codec_context_.get());\r
119 \r
120                 if(!video_codec_context_ && !audio_codex_context_)\r
121                         BOOST_THROW_EXCEPTION(\r
122                                 file_read_error() << \r
123                                 source_info(narrow(print())) << \r
124                                 msg_info("No video or audio codec context found."));            \r
125                         \r
126                 executor_.start();\r
127                 executor_.begin_invoke([this]{read_file();});\r
128                 CASPAR_LOG(info) << print() << " Started.";\r
129         }\r
130 \r
131         ~implementation()\r
132         {\r
133                 executor_.clear();\r
134                 executor_.stop();\r
135                 cond_.notify_all();\r
136                 CASPAR_LOG(info) << print() << " Stopped.";\r
137         }\r
138                         \r
139         void fix_time_base(AVCodecContext* context) // Some files give an invalid numerator, try to fix it.\r
140         {\r
141                 if(context && context->time_base.num == 1)\r
142                         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
143         }\r
144 \r
145         std::shared_ptr<AVCodecContext> open_stream(int codec_type, int& s_index)\r
146         {               \r
147                 AVStream** streams_end = format_context_->streams+format_context_->nb_streams;\r
148                 AVStream** stream = std::find_if(format_context_->streams, streams_end, \r
149                         [&](AVStream* stream) { return stream != nullptr && stream->codec->codec_type == codec_type ;});\r
150                 \r
151                 if(stream == streams_end) \r
152                         return nullptr;\r
153 \r
154                 s_index = (*stream)->index;\r
155                 \r
156                 auto codec = avcodec_find_decoder((*stream)->codec->codec_id);                  \r
157                 if(codec == nullptr)\r
158                         return nullptr;\r
159                         \r
160                 if((-avcodec_open((*stream)->codec, codec)) > 0)                \r
161                         return nullptr;\r
162 \r
163                 return std::shared_ptr<AVCodecContext>((*stream)->codec, avcodec_close);\r
164         }\r
165                 \r
166         void read_file()\r
167         {               \r
168                 try\r
169                 {\r
170                         AVPacket tmp_packet;\r
171                         safe_ptr<AVPacket> read_packet(&tmp_packet, av_free_packet);    \r
172 \r
173                         auto read_frame_ret = av_read_frame(format_context_.get(), read_packet.get());\r
174                         if(read_frame_ret == AVERROR_EOF || read_frame_ret == AVERROR_IO)\r
175                         {\r
176                                 if(loop_)\r
177                                 {\r
178                                         auto seek_frame_ret = av_seek_frame(format_context_.get(), -1, 0, AVSEEK_FLAG_BACKWARD);\r
179                                         if(seek_frame_ret >= 0)\r
180                                                 graph_->add_tag("seek");\r
181                                         else\r
182                                         {\r
183                                                 BOOST_THROW_EXCEPTION(\r
184                                                         invalid_operation() <<\r
185                                                         boost::errinfo_api_function("av_seek_frame") <<\r
186                                                         boost::errinfo_errno(AVUNERROR(seek_frame_ret)));\r
187                                         }       \r
188                                 }       \r
189                                 else\r
190                                         stop();\r
191                         }\r
192                         else if(read_frame_ret < 0)\r
193                         {\r
194                                 BOOST_THROW_EXCEPTION(\r
195                                         invalid_operation() <<\r
196                                         boost::errinfo_api_function("av_read_frame") <<\r
197                                         boost::errinfo_errno(AVUNERROR(read_frame_ret)));\r
198                         }\r
199                         else\r
200                         {\r
201                                 auto packet = std::make_shared<aligned_buffer>(read_packet->data, read_packet->data + read_packet->size);\r
202                                 if(read_packet->stream_index == video_s_index_)                 \r
203                                         video_packet_buffer_.try_push(std::move(packet));       \r
204                                 else if(read_packet->stream_index == audio_s_index_)    \r
205                                         audio_packet_buffer_.try_push(std::move(packet));       \r
206                         }\r
207                         \r
208                         graph_->update_value("input-buffer", static_cast<float>(video_packet_buffer_.size())/static_cast<float>(PACKET_BUFFER_COUNT));          \r
209                 }\r
210                 catch(...)\r
211                 {\r
212                         stop();\r
213                         CASPAR_LOG_CURRENT_EXCEPTION();\r
214                         return;\r
215                 }\r
216                 \r
217                 executor_.begin_invoke([this]{read_file();});           \r
218                 boost::unique_lock<boost::mutex> lock(mutex_);\r
219                 while(executor_.is_running() && audio_packet_buffer_.size() > PACKET_BUFFER_COUNT && video_packet_buffer_.size() > PACKET_BUFFER_COUNT)\r
220                         cond_.wait(lock);               \r
221         }\r
222 \r
223         void stop()\r
224         {\r
225                 executor_.stop();\r
226                 CASPAR_LOG(info) << print() << " eof";\r
227         }\r
228                 \r
229         aligned_buffer get_video_packet()\r
230         {\r
231                 return get_packet(video_packet_buffer_);\r
232         }\r
233 \r
234         aligned_buffer get_audio_packet()\r
235         {\r
236                 return get_packet(audio_packet_buffer_);\r
237         }\r
238 \r
239         bool has_packet() const\r
240         {\r
241                 return !video_packet_buffer_.empty() || !audio_packet_buffer_.empty();\r
242         }\r
243         \r
244         aligned_buffer get_packet(tbb::concurrent_bounded_queue<std::shared_ptr<aligned_buffer>>& buffer)\r
245         {\r
246                 cond_.notify_all();\r
247                 std::shared_ptr<aligned_buffer> packet;\r
248                 return buffer.try_pop(packet) ? std::move(*packet) : aligned_buffer();\r
249         }\r
250                         \r
251         double fps() const\r
252         {\r
253                 return static_cast<double>(video_codec_context_->time_base.den) / static_cast<double>(video_codec_context_->time_base.num);\r
254         }\r
255 \r
256         std::wstring print() const\r
257         {\r
258                 return L"ffmpeg_input";\r
259         }\r
260 };\r
261 \r
262 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop) : impl_(new implementation(graph, filename, loop)){}\r
263 const std::shared_ptr<AVCodecContext>& input::get_video_codec_context() const{return impl_->video_codec_context_;}\r
264 const std::shared_ptr<AVCodecContext>& input::get_audio_codec_context() const{return impl_->audio_codex_context_;}\r
265 bool input::has_packet() const{return impl_->has_packet();}\r
266 bool input::is_running() const {return impl_->executor_.is_running();}\r
267 aligned_buffer input::get_video_packet(){return impl_->get_video_packet();}\r
268 aligned_buffer input::get_audio_packet(){return impl_->get_audio_packet();}\r
269 double input::fps() const { return impl_->fps(); }\r
270 }