]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input.cpp
2.0.0.2: Added copyright notice to all files.
[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 = 50;\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         executor executor_;\r
76 public:\r
77         explicit implementation(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop) \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         {                       \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_;\r
90                 if((errn = -av_open_input_file(&weak_format_context_, narrow(filename).c_str(), nullptr, 0, nullptr)) > 0)\r
91                         BOOST_THROW_EXCEPTION(\r
92                                 file_read_error() << \r
93                                 source_info(narrow(print())) << \r
94                                 msg_info("No format context found.") << \r
95                                 boost::errinfo_api_function("av_open_input_file") <<\r
96                                 boost::errinfo_errno(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                                 msg_info("No stream found.") << \r
107                                 boost::errinfo_errno(errn));\r
108 \r
109                 video_codec_context_ = open_stream(CODEC_TYPE_VIDEO, video_s_index_);\r
110                 if(!video_codec_context_)\r
111                         CASPAR_LOG(warning) << print() << " Could not open any video stream.";\r
112                 else\r
113                         fix_time_base(video_codec_context_.get());\r
114                 \r
115                 audio_codex_context_ = open_stream(CODEC_TYPE_AUDIO, audio_s_index_);\r
116                 if(!audio_codex_context_)\r
117                         CASPAR_LOG(warning) << print() << " Could not open any audio stream.";\r
118                 else\r
119                         fix_time_base(video_codec_context_.get());\r
120 \r
121                 if(!video_codec_context_ && !audio_codex_context_)\r
122                         BOOST_THROW_EXCEPTION(\r
123                                 file_read_error() << \r
124                                 source_info(narrow(print())) << \r
125                                 msg_info("No video or audio codec context found."));            \r
126                         \r
127                 executor_.start();\r
128                 executor_.begin_invoke([this]{read_file();});\r
129                 CASPAR_LOG(info) << print() << " Started.";\r
130         }\r
131 \r
132         ~implementation()\r
133         {\r
134                 executor_.clear();\r
135                 executor_.stop();\r
136                 cond_.notify_all();\r
137                 CASPAR_LOG(info) << print() << " Stopped.";\r
138         }\r
139                         \r
140         void fix_time_base(AVCodecContext* context) // Some files give an invalid numerator, try to fix it.\r
141         {\r
142                 if(context && context->time_base.num == 1)\r
143                         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
144         }\r
145 \r
146         std::shared_ptr<AVCodecContext> open_stream(int codec_type, int& s_index)\r
147         {               \r
148                 AVStream** streams_end = format_context_->streams+format_context_->nb_streams;\r
149                 AVStream** stream = std::find_if(format_context_->streams, streams_end, \r
150                         [&](AVStream* stream) { return stream != nullptr && stream->codec->codec_type == codec_type ;});\r
151                 \r
152                 if(stream == streams_end) \r
153                         return nullptr;\r
154 \r
155                 s_index = (*stream)->index;\r
156                 \r
157                 auto codec = avcodec_find_decoder((*stream)->codec->codec_id);                  \r
158                 if(codec == nullptr)\r
159                         return nullptr;\r
160                         \r
161                 if((-avcodec_open((*stream)->codec, codec)) > 0)                \r
162                         return nullptr;\r
163 \r
164                 return std::shared_ptr<AVCodecContext>((*stream)->codec, avcodec_close);\r
165         }\r
166                 \r
167         void read_file()\r
168         {                                       \r
169                 AVPacket tmp_packet;\r
170                 safe_ptr<AVPacket> read_packet(&tmp_packet, av_free_packet);    \r
171 \r
172                 if (av_read_frame(format_context_.get(), read_packet.get()) >= 0) // NOTE: read_packet is only valid until next call of av_read_frame or av_close_input_file\r
173                 {\r
174                         auto packet = std::make_shared<aligned_buffer>(read_packet->data, read_packet->data + read_packet->size);\r
175                         if(read_packet->stream_index == video_s_index_)                 \r
176                                 video_packet_buffer_.try_push(std::move(packet));       \r
177                         else if(read_packet->stream_index == audio_s_index_)    \r
178                                 audio_packet_buffer_.try_push(std::move(packet));               \r
179                 }\r
180                 else if(!loop_ || av_seek_frame(format_context_.get(), -1, 0, AVSEEK_FLAG_BACKWARD) < 0) // TODO: av_seek_frame does not work for all formats\r
181                 {\r
182                         executor_.stop();\r
183                         CASPAR_LOG(info) << print() << " eof";\r
184                 }       \r
185                 else\r
186                         graph_->add_tag("seek");                \r
187                                         \r
188                 graph_->update_value("input-buffer", static_cast<float>(video_packet_buffer_.size())/static_cast<float>(PACKET_BUFFER_COUNT));          \r
189                 \r
190                 executor_.begin_invoke([this]{read_file();});           \r
191                 boost::unique_lock<boost::mutex> lock(mutex_);\r
192                 while(executor_.is_running() && audio_packet_buffer_.size() > PACKET_BUFFER_COUNT && video_packet_buffer_.size() > PACKET_BUFFER_COUNT)\r
193                         cond_.wait(lock);               \r
194         }\r
195                 \r
196         aligned_buffer get_video_packet()\r
197         {\r
198                 return get_packet(video_packet_buffer_);\r
199         }\r
200 \r
201         aligned_buffer get_audio_packet()\r
202         {\r
203                 return get_packet(audio_packet_buffer_);\r
204         }\r
205         \r
206         aligned_buffer get_packet(tbb::concurrent_bounded_queue<std::shared_ptr<aligned_buffer>>& buffer)\r
207         {\r
208                 cond_.notify_all();\r
209                 std::shared_ptr<aligned_buffer> packet;\r
210                 return buffer.try_pop(packet) ? std::move(*packet) : aligned_buffer();\r
211         }\r
212 \r
213         bool is_eof() const\r
214         {\r
215                 return !executor_.is_running() && video_packet_buffer_.empty() && audio_packet_buffer_.empty();\r
216         }\r
217                 \r
218         double fps() const\r
219         {\r
220                 return static_cast<double>(video_codec_context_->time_base.den) / static_cast<double>(video_codec_context_->time_base.num);\r
221         }\r
222 \r
223         std::wstring print() const\r
224         {\r
225                 return L"ffmpeg_input";\r
226         }\r
227 };\r
228 \r
229 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop) : impl_(new implementation(graph, filename, loop)){}\r
230 const std::shared_ptr<AVCodecContext>& input::get_video_codec_context() const{return impl_->video_codec_context_;}\r
231 const std::shared_ptr<AVCodecContext>& input::get_audio_codec_context() const{return impl_->audio_codex_context_;}\r
232 bool input::is_eof() const{return impl_->is_eof();}\r
233 bool input::is_running() const {return impl_->executor_.is_running();}\r
234 aligned_buffer input::get_video_packet(){return impl_->get_video_packet();}\r
235 aligned_buffer input::get_audio_packet(){return impl_->get_audio_packet();}\r
236 double input::fps() const { return impl_->fps(); }\r
237 }