]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/input/input.cpp
git-svn-id: https://casparcg.svn.sourceforge.net/svnroot/casparcg/server/branches...
[casparcg] / modules / ffmpeg / producer / input / 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 #if defined(_MSC_VER)\r
21 #pragma warning (disable : 4244)\r
22 #endif\r
23 \r
24 #include "../../stdafx.h"\r
25 \r
26 #include "input.h"\r
27 \r
28 #include "../util/util.h"\r
29 #include "../../ffmpeg_error.h"\r
30 \r
31 #include <core/video_format.h>\r
32 \r
33 #include <common/diagnostics/graph.h>\r
34 #include <common/exception/exceptions.h>\r
35 #include <common/exception/win32_exception.h>\r
36 \r
37 #include <tbb/atomic.h>\r
38 \r
39 #include <agents.h>\r
40 #include <concrt_extras.h>\r
41 \r
42 #if defined(_MSC_VER)\r
43 #pragma warning (push)\r
44 #pragma warning (disable : 4244)\r
45 #endif\r
46 extern "C" \r
47 {\r
48         #define __STDC_CONSTANT_MACROS\r
49         #define __STDC_LIMIT_MACROS\r
50         #include <libavformat/avformat.h>\r
51 }\r
52 #if defined(_MSC_VER)\r
53 #pragma warning (pop)\r
54 #endif\r
55 \r
56 \r
57 #undef Yield\r
58 using namespace Concurrency;\r
59 \r
60 namespace caspar { namespace ffmpeg {\r
61 \r
62 static const size_t MAX_PACKETS_SIZE = 16 * 1000000;\r
63 static const size_t MAX_PACKETS_COUNT = 50;\r
64         \r
65 struct input::implementation : public Concurrency::agent\r
66                                                          , public std::enable_shared_from_this<implementation>\r
67                                                          , boost::noncopyable\r
68 {\r
69         input::target_t&                                                target_;\r
70         safe_ptr<diagnostics::graph>                    graph_;\r
71 \r
72         const std::wstring                                              filename_;\r
73         const safe_ptr<AVFormatContext>                 format_context_; // Destroy this last\r
74         const int                                                               default_stream_index_;\r
75         const boost::iterator_range<AVStream**> streams_;\r
76         const size_t                                                    start_;         \r
77         const size_t                                                    length_;\r
78                         \r
79         size_t                                                                  frame_number_;\r
80         tbb::atomic<bool>                                               loop_;\r
81                         \r
82         tbb::atomic<size_t>                                             nb_frames_;\r
83         tbb::atomic<size_t>                                             nb_loops_;      \r
84         tbb::atomic<size_t>                                             packets_count_;\r
85         tbb::atomic<size_t>                                             packets_size_;\r
86 \r
87         tbb::atomic<bool>                                               is_running_;\r
88 \r
89         Concurrency::event                                              event_;\r
90                 \r
91 public:\r
92         explicit implementation(input::target_t& target,\r
93                                                         const safe_ptr<diagnostics::graph>& graph, \r
94                                                         const std::wstring& filename, \r
95                                                         bool loop, \r
96                                                         size_t start,\r
97                                                         size_t length)\r
98                 : target_(target)\r
99                 , graph_(graph)\r
100                 , filename_(filename)\r
101                 , format_context_(open_input(filename))         \r
102                 , default_stream_index_(av_find_default_stream_index(format_context_.get()))\r
103                 , streams_(format_context_->streams, format_context_->streams + format_context_->nb_streams)\r
104                 , start_(start)\r
105                 , length_(length)\r
106                 , frame_number_(0)\r
107         {               \r
108                 event_.set();\r
109                 loop_                   = loop;\r
110                                 \r
111                 //av_dump_format(format_context_.get(), 0, narrow(filename).c_str(), 0);\r
112                                 \r
113                 if(start_ > 0)                  \r
114                         seek_frame(start_);\r
115                                                                 \r
116                 graph_->set_color("seek", diagnostics::color(1.0f, 0.5f, 0.0f));\r
117                 graph_->set_color("buffer-count", diagnostics::color(0.7f, 0.4f, 0.4f));\r
118                 graph_->set_color("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f)); \r
119                                 \r
120                 is_running_ = true;\r
121                 agent::start();\r
122         }\r
123 \r
124         ~implementation()\r
125         {\r
126                 if(is_running_)\r
127                         stop();\r
128         }\r
129                 \r
130         void stop()\r
131         {\r
132                 is_running_ = false;\r
133                 event_.set();\r
134                 agent::wait(this);\r
135         }\r
136         \r
137         virtual void run()\r
138         {\r
139                 win32_exception::install_handler();\r
140 \r
141                 try\r
142                 {\r
143                         for(auto packet = read_next_packet(); is_running_ && packet; packet = read_next_packet())\r
144                         {                               \r
145                                 Concurrency::asend(target_, make_safe_ptr(packet));\r
146                                 Context::Yield();\r
147                                 event_.wait();\r
148                         }\r
149                 }\r
150                 catch(...)\r
151                 {\r
152                         CASPAR_LOG_CURRENT_EXCEPTION();\r
153                 }       \r
154         \r
155                 BOOST_FOREACH(auto stream, streams_)\r
156                         Concurrency::send(target_, flush_packet(stream->index));        \r
157                 BOOST_FOREACH(auto stream, streams_)\r
158                         Concurrency::send(target_, eof_packet(stream->index));  \r
159 \r
160                 done();\r
161         }\r
162 \r
163         std::shared_ptr<AVPacket> read_next_packet()\r
164         {               \r
165                 auto packet = create_packet();\r
166                 \r
167                 int ret = [&]() -> int\r
168                 {\r
169                         Concurrency::scoped_oversubcription_token oversubscribe;\r
170                         return 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
171                 }();\r
172 \r
173                 if(is_eof(ret))                                                                                                              \r
174                 {\r
175                         ++nb_loops_;\r
176                         frame_number_ = 0;\r
177 \r
178                         if(loop_)\r
179                         {\r
180                                 CASPAR_LOG(trace) << print() << " Looping.";\r
181                                 seek_frame(start_, AVSEEK_FLAG_BACKWARD);               \r
182                                 return read_next_packet();\r
183                         }       \r
184                         else\r
185                         {\r
186                                 CASPAR_LOG(trace) << print() << " Stopping.";\r
187                                 return nullptr;\r
188                         }\r
189                 }\r
190 \r
191                 THROW_ON_ERROR(ret, "av_read_frame", print());\r
192 \r
193                 if(packet->stream_index == default_stream_index_)\r
194                 {\r
195                         if(nb_loops_ == 0)\r
196                                 ++nb_frames_;\r
197                         ++frame_number_;\r
198                 }\r
199 \r
200                 THROW_ON_ERROR2(av_dup_packet(packet.get()), print());\r
201                                 \r
202                 // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.\r
203                 auto size = packet->size;\r
204                 auto data = packet->data;                       \r
205                 \r
206                 ++packets_count_;\r
207                 packets_size_ += size;\r
208                 \r
209                 graph_->update_value("buffer-size", (packets_size_+0.001)/MAX_PACKETS_SIZE);\r
210                 graph_->update_value("buffer-count", (packets_count_+0.001)/MAX_PACKETS_COUNT);\r
211 \r
212                 auto self = shared_from_this();\r
213                 packet = safe_ptr<AVPacket>(packet.get(), [this, self, packet, size, data](AVPacket*)\r
214                 {\r
215                         packet->size = size;\r
216                         packet->data = data;\r
217                         --packets_count_;\r
218                         packets_size_ -= size;\r
219                         event_.set();\r
220 \r
221                         graph_->update_value("buffer-size", (packets_size_+0.001)/MAX_PACKETS_SIZE);\r
222                         graph_->update_value("buffer-count", (packets_count_+0.001)/MAX_PACKETS_COUNT);\r
223                 });\r
224 \r
225                 if(is_running_ && (packets_count_ > MAX_PACKETS_COUNT || packets_size_ > MAX_PACKETS_SIZE))\r
226                         event_.reset();\r
227                                                                         \r
228                 return packet;\r
229         }\r
230 \r
231         void seek_frame(int64_t frame, int flags = 0)\r
232         {                       \r
233                 if(flags == AVSEEK_FLAG_BACKWARD)\r
234                 {\r
235                         // Fix VP6 seeking\r
236                         int vid_stream_index = av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);\r
237                         if(vid_stream_index >= 0)\r
238                         {\r
239                                 auto codec_id = format_context_->streams[vid_stream_index]->codec->codec_id;\r
240                                 if(codec_id == CODEC_ID_VP6A || codec_id == CODEC_ID_VP6F || codec_id == CODEC_ID_VP6)\r
241                                         flags |= AVSEEK_FLAG_BYTE;\r
242                         }\r
243                 }\r
244 \r
245                 THROW_ON_ERROR2(av_seek_frame(format_context_.get(), default_stream_index_, frame, flags), print());    \r
246                 auto packet = create_packet();\r
247                 packet->size = 0;\r
248 \r
249                 BOOST_FOREACH(auto stream, streams_)\r
250                         Concurrency::asend(target_, flush_packet(stream->index));       \r
251 \r
252                 graph_->add_tag("seek");                \r
253         }               \r
254 \r
255         bool is_eof(int ret)\r
256         {\r
257                 if(ret == AVERROR(EIO))\r
258                         CASPAR_LOG(trace) << print() << " Received EIO, assuming EOF. " << nb_frames_;\r
259                 if(ret == AVERROR_EOF)\r
260                         CASPAR_LOG(trace) << print() << " Received EOF. " << nb_frames_;\r
261 \r
262                 CASPAR_VERIFY(ret >= 0 || ret == AVERROR_EOF || ret == AVERROR(EIO), ffmpeg_error() << source_info(narrow(print())));\r
263 \r
264                 return ret == AVERROR_EOF || ret == AVERROR(EIO) || frame_number_ >= length_; // av_read_frame doesn't always correctly return AVERROR_EOF;\r
265         }\r
266         \r
267         std::wstring print() const\r
268         {\r
269                 return L"ffmpeg_input[" + filename_ + L")]";\r
270         }\r
271 };\r
272 \r
273 input::input(input::target_t& target,\r
274                          const safe_ptr<diagnostics::graph>& graph, \r
275                          const std::wstring& filename, \r
276                          bool loop, \r
277                          size_t start, \r
278                          size_t length)\r
279         : impl_(new implementation(target, graph, filename, loop, start, length))\r
280 {\r
281 }\r
282 \r
283 safe_ptr<AVFormatContext> input::context()\r
284 {\r
285         return safe_ptr<AVFormatContext>(impl_->format_context_);\r
286 }\r
287 \r
288 size_t input::nb_frames() const\r
289 {\r
290         return impl_->nb_frames_;\r
291 }\r
292 \r
293 size_t input::nb_loops() const \r
294 {\r
295         return impl_->nb_loops_;\r
296 }\r
297 \r
298 void input::stop()\r
299 {\r
300         impl_->stop();\r
301 }\r
302 \r
303 bool input::loop() const\r
304 {\r
305         return impl_->loop_;\r
306 }\r
307 void input::loop(bool value)\r
308 {\r
309         impl_->loop_ = value;\r
310 }\r
311 \r
312 }}