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