]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input/input.cpp
2.1.0: Merged trunk.
[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/concurrency/executor.h>\r
31 #include <common/exception/exceptions.h>\r
32 #include <common/exception/win32_exception.h>\r
33 #include <common/log/log.h>\r
34 \r
35 #include <core/video_format.h>\r
36 \r
37 #include <tbb/concurrent_queue.h>\r
38 #include <tbb/atomic.h>\r
39 #include <tbb/recursive_mutex.h>\r
40 \r
41 #include <boost/range/algorithm.hpp>\r
42 #include <boost/thread/condition_variable.hpp>\r
43 #include <boost/thread/mutex.hpp>\r
44 #include <boost/thread/thread.hpp>\r
45 \r
46 #if defined(_MSC_VER)\r
47 #pragma warning (push)\r
48 #pragma warning (disable : 4244)\r
49 #endif\r
50 extern "C" \r
51 {\r
52         #define __STDC_CONSTANT_MACROS\r
53         #define __STDC_LIMIT_MACROS\r
54         #include <libavformat/avformat.h>\r
55 }\r
56 #if defined(_MSC_VER)\r
57 #pragma warning (pop)\r
58 #endif\r
59 \r
60 static const size_t MAX_BUFFER_COUNT = 100;\r
61 static const size_t MIN_BUFFER_COUNT = 4;\r
62 static const size_t MAX_BUFFER_SIZE  = 16 * 1000000;\r
63 \r
64 namespace caspar { namespace ffmpeg {\r
65                 \r
66 struct input::impl : boost::noncopyable\r
67 {               \r
68         const safe_ptr<diagnostics::graph>                                                      graph_;\r
69 \r
70         const safe_ptr<AVFormatContext>                                                         format_context_; // Destroy this last\r
71         const int                                                                                                       default_stream_index_;\r
72                         \r
73         const std::wstring                                                                                      filename_;\r
74         const uint32_t                                                                                          start_;         \r
75         const uint32_t                                                                                          length_;\r
76         tbb::atomic<bool>                                                                                       loop_;\r
77         uint32_t                                                                                                        frame_number_;\r
78         \r
79         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>>        buffer_;\r
80         tbb::atomic<size_t>                                                                                     buffer_size_;\r
81                 \r
82         executor                                                                                                        executor_;\r
83         \r
84         impl(const safe_ptr<diagnostics::graph> graph, const std::wstring& filename, bool loop, uint32_t start, uint32_t length) \r
85                 : graph_(graph)\r
86                 , format_context_(open_input(filename))         \r
87                 , default_stream_index_(av_find_default_stream_index(format_context_.get()))\r
88                 , filename_(filename)\r
89                 , start_(start)\r
90                 , length_(length)\r
91                 , frame_number_(0)\r
92                 , executor_(print())\r
93         {               \r
94                 loop_                   = loop;\r
95                 buffer_size_    = 0;\r
96 \r
97                 if(start_ > 0)                  \r
98                         queued_seek(start_);\r
99                                                                 \r
100                 graph_->set_color("seek", diagnostics::color(1.0f, 0.5f, 0.0f));        \r
101                 graph_->set_color("buffer-count", diagnostics::color(0.7f, 0.4f, 0.4f));\r
102                 graph_->set_color("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f)); \r
103 \r
104                 tick();\r
105         }\r
106         \r
107         bool try_pop(std::shared_ptr<AVPacket>& packet)\r
108         {\r
109                 auto result = buffer_.try_pop(packet);\r
110                 \r
111                 if(result)\r
112                 {\r
113                         if(packet)\r
114                                 buffer_size_ -= packet->size;\r
115                         tick();\r
116                 }\r
117 \r
118                 graph_->set_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);\r
119                 graph_->set_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));\r
120                 \r
121                 return result;\r
122         }\r
123 \r
124         void seek(uint32_t target)\r
125         {\r
126                 executor_.begin_invoke([=]\r
127                 {\r
128                         std::shared_ptr<AVPacket> packet;\r
129                         while(buffer_.try_pop(packet) && packet)\r
130                                 buffer_size_ -= packet->size;\r
131 \r
132                         queued_seek(target);\r
133 \r
134                         tick();\r
135                 }, high_priority);\r
136         }\r
137         \r
138         std::wstring print() const\r
139         {\r
140                 return L"ffmpeg_input[" + filename_ + L")]";\r
141         }\r
142         \r
143         bool full() const\r
144         {\r
145                 return (buffer_size_ > MAX_BUFFER_SIZE || buffer_.size() > MAX_BUFFER_COUNT) && buffer_.size() > MIN_BUFFER_COUNT;\r
146         }\r
147 \r
148         void tick()\r
149         {       \r
150                 if(!executor_.is_running())\r
151                         return;\r
152                 \r
153                 executor_.begin_invoke([this]\r
154                 {                       \r
155                         if(full())\r
156                                 return;\r
157 \r
158                         try\r
159                         {\r
160                                 auto packet = create_packet();\r
161                 \r
162                                 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
163                 \r
164                                 if(is_eof(ret))                                                                                                              \r
165                                 {\r
166                                         frame_number_   = 0;\r
167 \r
168                                         if(loop_)\r
169                                         {\r
170                                                 queued_seek(start_);\r
171                                                 graph_->set_tag("seek");                \r
172                                                 CASPAR_LOG(trace) << print() << " Looping.";                    \r
173                                         }               \r
174                                         else\r
175                                                 executor_.stop();\r
176                                 }\r
177                                 else\r
178                                 {               \r
179                                         THROW_ON_ERROR(ret, "av_read_frame", print());\r
180 \r
181                                         if(packet->stream_index == default_stream_index_)\r
182                                                 ++frame_number_;\r
183 \r
184                                         THROW_ON_ERROR2(av_dup_packet(packet.get()), print());\r
185                                 \r
186                                         // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.\r
187                                         auto size = packet->size;\r
188                                         auto data = packet->data;\r
189                         \r
190                                         packet = safe_ptr<AVPacket>(packet.get(), [packet, size, data](AVPacket*)\r
191                                         {\r
192                                                 packet->size = size;\r
193                                                 packet->data = data;                            \r
194                                         });\r
195 \r
196                                         buffer_.try_push(packet);\r
197                                         buffer_size_ += packet->size;\r
198                                 \r
199                                         graph_->set_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);\r
200                                         graph_->set_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));\r
201                                 }       \r
202                 \r
203                                 tick();         \r
204                         }\r
205                         catch(...)\r
206                         {\r
207                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
208                                 executor_.stop();\r
209                         }\r
210                 });\r
211         }       \r
212                         \r
213         void queued_seek(const uint32_t target)\r
214         {       \r
215                 CASPAR_LOG(debug) << print() << " Seeking: " << target;\r
216 \r
217                 int flags = AVSEEK_FLAG_FRAME;\r
218                 if(target == 0)\r
219                 {\r
220                         // Fix VP6 seeking\r
221                         int vid_stream_index = av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);\r
222                         if(vid_stream_index >= 0)\r
223                         {\r
224                                 auto codec_id = format_context_->streams[vid_stream_index]->codec->codec_id;\r
225                                 if(codec_id == CODEC_ID_VP6A || codec_id == CODEC_ID_VP6F || codec_id == CODEC_ID_VP6)\r
226                                         flags = AVSEEK_FLAG_BYTE;\r
227                         }\r
228                 }\r
229                 \r
230                 auto stream = format_context_->streams[default_stream_index_];\r
231                 auto codec  = stream->codec;\r
232                 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
233                 \r
234                 THROW_ON_ERROR2(avformat_seek_file(format_context_.get(), default_stream_index_, std::numeric_limits<int64_t>::min(), fixed_target, std::numeric_limits<int64_t>::max(), 0), print());          \r
235                 \r
236                 auto flush_packet       = create_packet();\r
237                 flush_packet->data      = nullptr;\r
238                 flush_packet->size      = 0;\r
239                 flush_packet->pos       = target;\r
240 \r
241                 buffer_.push(flush_packet);\r
242         }       \r
243 \r
244         bool is_eof(int ret)\r
245         {\r
246                 #pragma warning (disable : 4146)\r
247 \r
248                 if(ret == AVERROR(EIO))\r
249                         CASPAR_LOG(trace) << print() << " Received EIO, assuming EOF. ";\r
250                 if(ret == AVERROR_EOF)\r
251                         CASPAR_LOG(trace) << print() << " Received EOF. ";\r
252 \r
253                 return ret == AVERROR_EOF || ret == AVERROR(EIO) || frame_number_ >= length_; // av_read_frame doesn't always correctly return AVERROR_EOF;\r
254         }\r
255 };\r
256 \r
257 input::input(const safe_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, uint32_t start, uint32_t length) \r
258         : impl_(new impl(graph, filename, loop, start, length)){}\r
259 bool input::eof() const {return !impl_->executor_.is_running();}\r
260 bool input::try_pop(std::shared_ptr<AVPacket>& packet){return impl_->try_pop(packet);}\r
261 safe_ptr<AVFormatContext> input::context(){return impl_->format_context_;}\r
262 void input::loop(bool value){impl_->loop_ = value;}\r
263 bool input::loop() const{return impl_->loop_;}\r
264 void input::seek(uint32_t target){impl_->seek(target);}\r
265 }}\r