]> 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) 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 static const size_t MAX_BUFFER_COUNT = 100;\r
60 static const size_t MIN_BUFFER_COUNT = 32;\r
61 static const size_t MAX_BUFFER_SIZE  = 32 * 1000000;\r
62 \r
63 namespace caspar { namespace ffmpeg {\r
64                 \r
65 struct input::impl : boost::noncopyable\r
66 {               \r
67         const spl::shared_ptr<diagnostics::graph>                                                       graph_;\r
68 \r
69         const spl::shared_ptr<AVFormatContext>                                                          format_context_; // Destroy this last\r
70         const int                                                                                                       default_stream_index_;\r
71                         \r
72         const std::wstring                                                                                      filename_;\r
73         tbb::atomic<uint32_t>                                                                           start_;         \r
74         tbb::atomic<uint32_t>                                                                           length_;\r
75         tbb::atomic<bool>                                                                                       loop_;\r
76         tbb::atomic<bool>                                                                                       eof_;\r
77         uint32_t                                                                                                        frame_number_;\r
78         double                                                                                                          fps_;\r
79         \r
80         tbb::concurrent_bounded_queue<std::shared_ptr<AVPacket>>        buffer_;\r
81         tbb::atomic<size_t>                                                                                     buffer_size_;\r
82                 \r
83         executor                                                                                                        executor_;\r
84         \r
85         impl(const spl::shared_ptr<diagnostics::graph> graph, const std::wstring& filename, const bool loop, const uint32_t start, const uint32_t length) \r
86                 : graph_(graph)\r
87                 , format_context_(open_input(filename))         \r
88                 , default_stream_index_(av_find_default_stream_index(format_context_.get()))\r
89                 , filename_(filename)\r
90                 , frame_number_(0)\r
91                 , fps_(read_fps(*format_context_, 25))\r
92                 , executor_(print())\r
93         {               \r
94                 start_                  = start;\r
95                 length_                 = length;\r
96                 loop_                   = loop;\r
97                 eof_                    = false;\r
98                 buffer_size_    = 0;\r
99 \r
100                 if(start_ > 0)                  \r
101                         seek(start_, false);\r
102                                                                 \r
103                 graph_->set_color("seek", diagnostics::color(1.0f, 0.5f, 0.0f));        \r
104                 graph_->set_color("buffer-count", diagnostics::color(0.7f, 0.4f, 0.4f));\r
105                 graph_->set_color("buffer-size", diagnostics::color(1.0f, 1.0f, 0.0f)); \r
106 \r
107                 tick();\r
108         }\r
109         \r
110         bool try_pop(std::shared_ptr<AVPacket>& packet)\r
111         {\r
112                 auto result = buffer_.try_pop(packet);\r
113                 \r
114                 if(result)\r
115                 {\r
116                         if(packet)\r
117                                 buffer_size_ -= packet->size;\r
118                         tick();\r
119                 }\r
120 \r
121                 graph_->set_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);\r
122                 graph_->set_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));\r
123                 \r
124                 return result;\r
125         }\r
126 \r
127         void seek(uint32_t target, bool clear)\r
128         {\r
129                 executor_.invoke([=]\r
130                 {\r
131                         if(clear)\r
132                         {\r
133                                 std::shared_ptr<AVPacket> packet;\r
134                                 while(buffer_.try_pop(packet) && packet)\r
135                                         buffer_size_ -= packet->size;\r
136                         }\r
137                         \r
138                         CASPAR_LOG(debug) << print() << " Seeking: " << target;\r
139 \r
140                         int flags = AVSEEK_FLAG_FRAME;\r
141                         if(target == 0)\r
142                         {\r
143                                 // Fix VP6 seeking\r
144                                 int vid_stream_index = av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_VIDEO, -1, -1, 0, 0);\r
145                                 if(vid_stream_index >= 0)\r
146                                 {\r
147                                         auto codec_id = format_context_->streams[vid_stream_index]->codec->codec_id;\r
148                                         if(codec_id == CODEC_ID_VP6A || codec_id == CODEC_ID_VP6F || codec_id == CODEC_ID_VP6)\r
149                                                 flags = AVSEEK_FLAG_BYTE;\r
150                                 }\r
151                         }\r
152                 \r
153                         auto stream = format_context_->streams[default_stream_index_];\r
154                         auto codec  = stream->codec;\r
155                         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
156                 \r
157                         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
158                 \r
159                         auto flush_packet       = create_packet();\r
160                         flush_packet->data      = nullptr;\r
161                         flush_packet->size      = 0;\r
162                         flush_packet->pts       = target;\r
163 \r
164                         buffer_.push(flush_packet);\r
165                         \r
166                         tick();\r
167                 }, task_priority::high_priority);\r
168         }\r
169         \r
170         std::wstring print() const\r
171         {\r
172                 return L"ffmpeg_input[" + filename_ + L")]";\r
173         }\r
174         \r
175         bool full() const\r
176         {\r
177                 return (buffer_size_ > MAX_BUFFER_SIZE || buffer_.size() > MAX_BUFFER_COUNT) && buffer_.size() > MIN_BUFFER_COUNT;\r
178         }\r
179 \r
180         void tick()\r
181         {       \r
182                 if(!executor_.is_running())\r
183                         return;\r
184                 \r
185                 executor_.begin_invoke([this]\r
186                 {                       \r
187                         if(full())\r
188                                 return;\r
189 \r
190                         try\r
191                         {\r
192                                 auto packet = create_packet();\r
193                 \r
194                                 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
195                 \r
196                                 if(is_eof(ret))                                                                                                              \r
197                                 {\r
198                                         frame_number_ = 0;\r
199 \r
200                                         if(loop_)\r
201                                         {\r
202                                                 seek(start_, false);\r
203                                                 graph_->set_tag("seek");                \r
204                                                 CASPAR_LOG(trace) << print() << " Looping.";    \r
205                                         }\r
206                                         else\r
207                                                 eof_ = true;\r
208                                 }\r
209                                 else\r
210                                 {               \r
211                                         eof_ = false;\r
212 \r
213                                         THROW_ON_ERROR(ret, "av_read_frame", print());\r
214 \r
215                                         if(packet->stream_index == default_stream_index_)\r
216                                                 ++frame_number_;\r
217 \r
218                                         THROW_ON_ERROR2(av_dup_packet(packet.get()), print());\r
219                                 \r
220                                         // Make sure that the packet is correctly deallocated even if size and data is modified during decoding.\r
221                                         auto size = packet->size;\r
222                                         auto data = packet->data;\r
223                         \r
224                                         packet = spl::shared_ptr<AVPacket>(packet.get(), [packet, size, data](AVPacket*)\r
225                                         {\r
226                                                 packet->size = size;\r
227                                                 packet->data = data;                            \r
228                                         });\r
229 \r
230                                         auto time_base = format_context_->streams[packet->stream_index]->time_base;\r
231                                         packet->pts = static_cast<uint64_t>((static_cast<double>(packet->pts * time_base.num)/time_base.den)*fps_);\r
232                                         \r
233                                         buffer_.try_push(packet);\r
234                                         buffer_size_ += packet->size;\r
235                                 \r
236                                         graph_->set_value("buffer-size", (static_cast<double>(buffer_size_)+0.001)/MAX_BUFFER_SIZE);\r
237                                         graph_->set_value("buffer-count", (static_cast<double>(buffer_.size()+0.001)/MAX_BUFFER_COUNT));                \r
238                                 }       \r
239 \r
240                                 if(!eof_)\r
241                                         tick();         \r
242                         }\r
243                         catch(...)\r
244                         {\r
245                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
246                                 executor_.stop();\r
247                         }\r
248                 });\r
249         }       \r
250                         \r
251         bool is_eof(int ret)\r
252         {\r
253                 #pragma warning (disable : 4146)\r
254 \r
255                 //if(ret == AVERROR(EIO))\r
256                 //      CASPAR_LOG(trace) << print() << " Received EIO, assuming EOF. ";\r
257                 //if(ret == AVERROR_EOF)\r
258                 //      CASPAR_LOG(trace) << print() << " Received EOF. ";\r
259 \r
260                 return ret == AVERROR_EOF || ret == AVERROR(EIO) || frame_number_ >= length_; // av_read_frame doesn't always correctly return AVERROR_EOF;\r
261         }\r
262 };\r
263 \r
264 input::input(const spl::shared_ptr<diagnostics::graph>& graph, const std::wstring& filename, bool loop, uint32_t start, uint32_t length) \r
265         : impl_(new impl(graph, filename, loop, start, length)){}\r
266 bool input::eof() const {return impl_->eof_;}\r
267 bool input::try_pop(std::shared_ptr<AVPacket>& packet){return impl_->try_pop(packet);}\r
268 spl::shared_ptr<AVFormatContext> input::context(){return impl_->format_context_;}\r
269 void input::loop(bool value){impl_->loop_ = value;}\r
270 bool input::loop() const{return impl_->loop_;}\r
271 void input::seek(uint32_t target){impl_->seek(target, true);}\r
272 void input::start(uint32_t value){impl_->start_ = value;}\r
273 uint32_t input::start() const{return impl_->start_;}\r
274 void input::length(uint32_t value){impl_->length_ = value;}\r
275 uint32_t input::length() const{return impl_->length_;}\r
276 }}\r