]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input/input.cpp
2.1.0: -ffmpeg_producer: Removed "audio_resampler" in favor of "swresample" API....
[casparcg] / modules / ffmpeg / producer / input / input.cpp
1 /*\r
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 * This file is part of CasparCG (www.casparcg.com).\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 * Author: Robert Nagy, ronag89@gmail.com\r
20 */\r
21 \r
22 #include "../../stdafx.h"\r
23 \r
24 #include "input.h"\r
25 \r
26 #include "../util/util.h"\r
27 #include "../../ffmpeg_error.h"\r
28 \r
29 #include <common/diagnostics/graph.h>\r
30 #include <common/executor.h>\r
31 #include <common/except.h>\r
32 #include <common/log.h>\r
33 \r
34 #include <core/video_format.h>\r
35 \r
36 #include <tbb/concurrent_queue.h>\r
37 #include <tbb/atomic.h>\r
38 #include <tbb/recursive_mutex.h>\r
39 \r
40 #include <boost/range/algorithm.hpp>\r
41 #include <boost/thread/condition_variable.hpp>\r
42 #include <boost/thread/mutex.hpp>\r
43 #include <boost/thread/thread.hpp>\r
44 \r
45 #if defined(_MSC_VER)\r
46 #pragma warning (push)\r
47 #pragma warning (disable : 4244)\r
48 #endif\r
49 extern "C" \r
50 {\r
51         #define __STDC_CONSTANT_MACROS\r
52         #define __STDC_LIMIT_MACROS\r
53         #include <libavformat/avformat.h>\r
54 }\r
55 #if defined(_MSC_VER)\r
56 #pragma warning (pop)\r
57 #endif\r
58 \r
59 namespace caspar { namespace ffmpeg {\r
60 \r
61 static const int MIN_FRAMES = 25;\r
62 \r
63 class stream\r
64 {\r
65         stream(const stream&);\r
66         stream& operator=(const stream&);\r
67 \r
68         typedef tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>>::size_type size_type;\r
69 \r
70         int                                                                                                              index_;\r
71         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>> packets_;\r
72 public:\r
73 \r
74         stream(int index) \r
75                 : index_(index)\r
76         {\r
77         }\r
78         \r
79         void push(const std::shared_ptr<AVPacket>& packet)\r
80         {\r
81                 if(packet->stream_index != index_ && packet != flush_packet() && packet != eof_packet())\r
82                         return;\r
83 \r
84                 packets_.push(packet);\r
85         }\r
86 \r
87         bool try_pop(std::shared_ptr<AVPacket>& packet)\r
88         {\r
89                 return packets_.try_pop(packet);\r
90         }\r
91 \r
92         void clear()\r
93         {\r
94                 std::shared_ptr<AVPacket> packet;\r
95                 while(packets_.try_pop(packet));\r
96         }\r
97 \r
98         size_type size() const\r
99         {\r
100                 return index_ != -1 ? packets_.size() : std::numeric_limits<size_type>::max();\r
101         }\r
102 };\r
103                 \r
104 struct input::impl : boost::noncopyable\r
105 {               \r
106         const spl::shared_ptr<diagnostics::graph>                                       graph_;\r
107 \r
108         const spl::shared_ptr<AVFormatContext>                                          format_context_; // Destroy this last\r
109         const int                                                                                                       default_stream_index_;\r
110                         \r
111         const std::wstring                                                                                      filename_;\r
112         tbb::atomic<uint32_t>                                                                           start_;         \r
113         tbb::atomic<uint32_t>                                                                           length_;\r
114         tbb::atomic<bool>                                                                                       loop_;\r
115         double                                                                                                          fps_;\r
116         uint32_t                                                                                                        frame_number_;\r
117         \r
118         stream                                                                                                          video_stream_;\r
119         stream                                                                                                          audio_stream_;\r
120 \r
121         executor                                                                                                        executor_;\r
122         \r
123         impl(const spl::shared_ptr<diagnostics::graph> graph, const std::wstring& filename, const bool loop, const uint32_t start, const uint32_t length) \r
124                 : graph_(graph)\r
125                 , format_context_(open_input(filename))         \r
126                 , default_stream_index_(av_find_default_stream_index(format_context_.get()))\r
127                 , filename_(filename)\r
128                 , frame_number_(0)\r
129                 , fps_(read_fps(*format_context_, 0.0))\r
130                 , video_stream_(av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0))\r
131                 , audio_stream_(av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_AUDIO, -1, -1, 0, 0))\r
132                 , executor_(print())\r
133         {               \r
134                 start_                  = start;\r
135                 length_                 = length;\r
136                 loop_                   = loop;\r
137 \r
138                 if(start_ > 0)                  \r
139                         seek(start_, false);\r
140                                                                 \r
141                 graph_->set_color("seek", diagnostics::color(1.0f, 0.5f, 0.0f));        \r
142                 graph_->set_color("audio-buffer", diagnostics::color(0.7f, 0.4f, 0.4f));\r
143                 graph_->set_color("video-buffer", diagnostics::color(1.0f, 1.0f, 0.0f));        \r
144                 \r
145                 tick();\r
146         }\r
147         \r
148         bool try_pop_video(std::shared_ptr<AVPacket>& packet)\r
149         {                               \r
150                 bool result = video_stream_.try_pop(packet);\r
151                 if(result)\r
152                         tick();\r
153                 \r
154                 graph_->set_value("video-buffer", std::min(1.0, static_cast<double>(video_stream_.size()/MIN_FRAMES)));\r
155                                 \r
156                 return result;\r
157         }\r
158         \r
159         bool try_pop_audio(std::shared_ptr<AVPacket>& packet)\r
160         {                               \r
161                 bool result = audio_stream_.try_pop(packet);\r
162                 if(result)\r
163                         tick();\r
164                                 \r
165                 graph_->set_value("audio-buffer", std::min(1.0, static_cast<double>(audio_stream_.size()/MIN_FRAMES)));\r
166 \r
167                 return result;\r
168         }\r
169 \r
170         void seek(uint32_t target, bool clear)\r
171         {\r
172                 executor_.invoke([=]\r
173                 {                       \r
174                         CASPAR_LOG(debug) << print() << " Seeking: " << target;\r
175 \r
176                         int flags = AVSEEK_FLAG_FRAME;\r
177                         if(target == 0)\r
178                         {\r
179                                 // Fix VP6 seeking\r
180                                 int vid_stream_index = av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);\r
181                                 if(vid_stream_index >= 0)\r
182                                 {\r
183                                         auto codec_id = format_context_->streams[vid_stream_index]->codec->codec_id;\r
184                                         if(codec_id == CODEC_ID_VP6A || codec_id == CODEC_ID_VP6F || codec_id == CODEC_ID_VP6)\r
185                                                 flags = AVSEEK_FLAG_BYTE;\r
186                                 }\r
187                         }\r
188                 \r
189                         auto stream = format_context_->streams[default_stream_index_];\r
190                         auto codec  = stream->codec;\r
191                         auto fixed_target = (target*stream->time_base.den*codec->time_base.num)/(stream->time_base.num*codec->time_base.den)*codec->ticks_per_frame;\r
192                 \r
193                         THROW_ON_ERROR2(avformat_seek_file(format_context_.get(), default_stream_index_, std::numeric_limits<int64_t>::min(), fixed_target, fixed_target, 0), print());         \r
194                 \r
195                         if(clear)\r
196                         {\r
197                                 video_stream_.clear();\r
198                                 audio_stream_.clear();\r
199                         }\r
200 \r
201                         video_stream_.push(flush_packet());\r
202                         audio_stream_.push(flush_packet());\r
203                         \r
204                         tick();\r
205                 }, task_priority::high_priority);\r
206         }\r
207                 \r
208         std::wstring print() const\r
209         {\r
210                 return L"ffmpeg_input[" + filename_ + L")]";\r
211         }\r
212         \r
213         bool full() const\r
214         {\r
215                 return video_stream_.size() > MIN_FRAMES && audio_stream_.size() > MIN_FRAMES;\r
216         }\r
217 \r
218         void tick()\r
219         {       \r
220                 if(!executor_.is_running())\r
221                         return;\r
222                 \r
223                 executor_.begin_invoke([this]\r
224                 {                       \r
225                         if(full())\r
226                                 return;\r
227 \r
228                         try\r
229                         {\r
230                                 auto packet = create_packet();\r
231                 \r
232                                 auto ret = av_read_frame(format_context_.get(), packet.get()); // packet is only valid until next call of av_read_frame. Use av_dup_packet to extend its life.  \r
233                 \r
234                                 if(is_eof(ret))                                                                                                              \r
235                                 {\r
236                                         video_stream_.push(eof_packet());\r
237                                         audio_stream_.push(eof_packet());\r
238 \r
239                                         if(loop_)\r
240                                         {\r
241                                                 seek(start_, false);\r
242                                                 graph_->set_tag("seek");                \r
243                                         }\r
244                                 }\r
245                                 else\r
246                                 {               \r
247                                         THROW_ON_ERROR(ret, "av_read_frame", print());\r
248                                         \r
249                                         THROW_ON_ERROR2(av_dup_packet(packet.get()), print());\r
250                                 \r
251                                         // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.\r
252                                         auto size = packet->size;\r
253                                         auto data = packet->data;\r
254                         \r
255                                         packet = spl::shared_ptr<AVPacket>(packet.get(), [packet, size, data](AVPacket*)\r
256                                         {\r
257                                                 packet->size = size;\r
258                                                 packet->data = data;                            \r
259                                         });\r
260                                         \r
261                                         auto stream_time_base = format_context_->streams[packet->stream_index]->time_base;\r
262                                         auto packet_frame_number = static_cast<uint32_t>((static_cast<double>(packet->pts * stream_time_base.num)/stream_time_base.den)*fps_);\r
263 \r
264                                         if(packet->stream_index == default_stream_index_)\r
265                                                 frame_number_ = packet_frame_number;\r
266                                         \r
267                                         if(packet_frame_number >= start_ && packet_frame_number < length_)\r
268                                         {\r
269                                                 video_stream_.push(packet);\r
270                                                 audio_stream_.push(packet);\r
271                                                 \r
272                                                 graph_->set_value("video-buffer", std::min(1.0, static_cast<double>(video_stream_.size()/MIN_FRAMES)));\r
273                                                 graph_->set_value("audio-buffer", std::min(1.0, static_cast<double>(audio_stream_.size()/MIN_FRAMES)));\r
274                                         }\r
275 \r
276                                         tick();         \r
277                                 }       \r
278                         }\r
279                         catch(...)\r
280                         {\r
281                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
282                                 executor_.stop();\r
283                         }\r
284                 });\r
285         }       \r
286                         \r
287         bool is_eof(int ret)\r
288         {\r
289                 #pragma warning (disable : 4146)\r
290 \r
291                 //if(ret == AVERROR(EIO))\r
292                 //      CASPAR_LOG(trace) << print() << " Received EIO, assuming EOF. ";\r
293                 //if(ret == AVERROR_EOF)\r
294                 //      CASPAR_LOG(trace) << print() << " Received EOF. ";\r
295 \r
296                 return ret == AVERROR_EOF || ret == AVERROR(EIO) || frame_number_ > length_; // av_read_frame doesn't always correctly return AVERROR_EOF;\r
297         }\r
298 };\r
299 \r
300 input::input(const spl::shared_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, uint32_t start, uint32_t length) \r
301         : impl_(new impl(graph, filename, loop, start, length)){}\r
302 bool input::try_pop_video(std::shared_ptr<AVPacket>& packet){return impl_->try_pop_video(packet);}\r
303 bool input::try_pop_audio(std::shared_ptr<AVPacket>& packet){return impl_->try_pop_audio(packet);}\r
304 spl::shared_ptr<AVFormatContext> input::context(){return impl_->format_context_;}\r
305 void input::loop(bool value){impl_->loop_ = value;}\r
306 bool input::loop() const{return impl_->loop_;}\r
307 void input::seek(uint32_t target){impl_->seek(target, true);}\r
308 void input::start(uint32_t value){impl_->start_ = value;}\r
309 uint32_t input::start() const{return impl_->start_;}\r
310 void input::length(uint32_t value){impl_->length_ = value;}\r
311 uint32_t input::length() const{return impl_->length_;}\r
312 }}\r