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