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