A possibly-better approach to seeking.
[dcpomatic.git] / src / lib / video_decoder.cc
1 /*
2     Copyright (C) 2012-2016 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "video_decoder.h"
22 #include "image.h"
23 #include "raw_image_proxy.h"
24 #include "film.h"
25 #include "log.h"
26 #include "compose.hpp"
27 #include <boost/foreach.hpp>
28 #include <iostream>
29
30 #include "i18n.h"
31
32 using std::cout;
33 using std::list;
34 using std::max;
35 using std::back_inserter;
36 using boost::shared_ptr;
37 using boost::optional;
38
39 VideoDecoder::VideoDecoder (Decoder* parent, shared_ptr<const Content> c, shared_ptr<Log> log)
40 #ifdef DCPOMATIC_DEBUG
41         : test_gaps (0)
42         , _parent (parent),
43           _content (c)
44 #else
45         : _parent (parent)
46         , _content (c)
47 #endif
48         , _log (log)
49         , _last_seek_accurate (true)
50         , _ignore (false)
51 {
52         _black_image.reset (new Image (AV_PIX_FMT_RGB24, _content->video->size(), true));
53         _black_image->make_black ();
54 }
55
56 list<ContentVideo>
57 VideoDecoder::decoded (Frame frame)
58 {
59         list<ContentVideo> output;
60
61         BOOST_FOREACH (ContentVideo const & i, _decoded) {
62                 if (i.frame.index() == frame) {
63                         output.push_back (i);
64                 }
65         }
66
67         return output;
68 }
69
70 /** Get all frames which exist in the content at a given frame index.
71  *  @param frame Frame index.
72  *  @param accurate true to try hard to return frames at the precise time that was requested, otherwise frames nearby may be returned.
73  *  @return Frames; there may be none (if there is no video there), 1 for 2D or 2 for 3D.
74  */
75 list<ContentVideo>
76 VideoDecoder::get (Frame frame, bool accurate)
77 {
78         if (_no_data_frame && frame >= _no_data_frame.get()) {
79                 return list<ContentVideo> ();
80         }
81
82         /* At this stage, if we have get_video()ed before, _decoded will contain the last frame that this
83            method returned (and possibly a few more).  If the requested frame is not in _decoded and it is not the next
84            one after the end of _decoded we need to seek.
85         */
86
87         _log->log (String::compose ("VD has request for %1", frame), LogEntry::TYPE_DEBUG_DECODE);
88
89         /* See if we have frame, and suggest a seek if not */
90         list<ContentVideo>::const_iterator i = _decoded.begin ();
91         while (i != _decoded.end() && i->frame.index() != frame) {
92                 ++i;
93         }
94         if (i == _decoded.end()) {
95                 Frame seek_frame = frame;
96                 if (_content->video->frame_type() == VIDEO_FRAME_TYPE_3D_ALTERNATE) {
97                         /* 3D alternate is a special case as the frame index in the content is not the same
98                            as the frame index we are talking about here.
99                         */
100                         seek_frame *= 2;
101                 }
102                 _parent->maybe_seek (ContentTime::from_frames (seek_frame, _content->active_video_frame_rate()), accurate);
103         }
104
105         /* Work out the number of frames that we should return; we
106            must return all frames in our content at the requested `time'
107            (i.e. frame)
108         */
109         unsigned int frames_wanted = 0;
110         switch (_content->video->frame_type()) {
111         case VIDEO_FRAME_TYPE_2D:
112         case VIDEO_FRAME_TYPE_3D_LEFT:
113         case VIDEO_FRAME_TYPE_3D_RIGHT:
114                 frames_wanted = 1;
115                 break;
116         case VIDEO_FRAME_TYPE_3D:
117         case VIDEO_FRAME_TYPE_3D_ALTERNATE:
118         case VIDEO_FRAME_TYPE_3D_LEFT_RIGHT:
119         case VIDEO_FRAME_TYPE_3D_TOP_BOTTOM:
120                 frames_wanted = 2;
121                 break;
122         default:
123                 DCPOMATIC_ASSERT (false);
124         }
125
126         list<ContentVideo> dec;
127
128         /* Now enough pass() calls should either:
129          *  (a) give us what we want, or
130          *  (b) give us something after what we want, indicating that we will never get what we want, or
131          *  (c) hit the end of the decoder.
132          */
133         if (accurate) {
134                 /* We are being accurate, so we want the right frame.
135                  * This could all be one statement but it's split up for clarity.
136                  */
137                 bool no_data = false;
138
139                 while (true) {
140                         if (decoded(frame).size() == frames_wanted) {
141                                 /* We got what we want */
142                                 break;
143                         }
144
145                         if (_parent->pass (Decoder::PASS_REASON_VIDEO, accurate)) {
146                                 /* The decoder has nothing more for us */
147                                 no_data = true;
148                                 break;
149                         }
150
151                         if (!_decoded.empty() && _decoded.front().frame.index() > frame) {
152                                 /* We're never going to get the frame we want.  Perhaps the caller is asking
153                                  * for a video frame before the content's video starts (if its audio
154                                  * begins before its video, for example).
155                                  */
156                                 break;
157                         }
158                 }
159
160                 dec = decoded (frame);
161
162                 if (no_data && dec.empty()) {
163                         _no_data_frame = frame;
164                 }
165
166         } else {
167                 /* Any frame(s) will do: use the first one(s) that comes out of pass() */
168                 while (_decoded.size() < frames_wanted && !_parent->pass (Decoder::PASS_REASON_VIDEO, accurate)) {}
169                 list<ContentVideo>::const_iterator i = _decoded.begin();
170                 unsigned int j = 0;
171                 while (i != _decoded.end() && j < frames_wanted) {
172                         dec.push_back (*i);
173                         ++i;
174                         ++j;
175                 }
176         }
177
178         /* Clean up _decoded; keep the frame we are returning, if any (which may have two images
179            for 3D), but nothing before that
180         */
181         while (!_decoded.empty() && !dec.empty() && _decoded.front().frame.index() < dec.front().frame.index()) {
182                 _decoded.pop_front ();
183         }
184
185         return dec;
186 }
187
188 /** Fill _decoded from `from' up to, but not including, `to' with
189  *  a frame for one particular Eyes value (which could be EYES_BOTH,
190  *  EYES_LEFT or EYES_RIGHT)
191  */
192 void
193 VideoDecoder::fill_one_eye (Frame from, Frame to, Eyes eye)
194 {
195         if (to == 0) {
196                 /* Already OK */
197                 return;
198         }
199
200         /* Fill with black... */
201         shared_ptr<const ImageProxy> filler_image (new RawImageProxy (_black_image));
202         Part filler_part = PART_WHOLE;
203
204         /* ...unless there's some video we can fill with */
205         if (!_decoded.empty ()) {
206                 filler_image = _decoded.back().image;
207                 filler_part = _decoded.back().part;
208         }
209
210         for (Frame i = from; i < to; ++i) {
211 #ifdef DCPOMATIC_DEBUG
212                 test_gaps++;
213 #endif
214                 _decoded.push_back (
215                         ContentVideo (filler_image, VideoFrame (i, eye), filler_part)
216                         );
217         }
218 }
219
220 /** Fill _decoded from `from' up to, but not including, `to'
221  *  adding both left and right eye frames.
222  */
223 void
224 VideoDecoder::fill_both_eyes (VideoFrame from, VideoFrame to)
225 {
226         /* Fill with black... */
227         shared_ptr<const ImageProxy> filler_left_image (new RawImageProxy (_black_image));
228         shared_ptr<const ImageProxy> filler_right_image (new RawImageProxy (_black_image));
229         Part filler_left_part = PART_WHOLE;
230         Part filler_right_part = PART_WHOLE;
231
232         /* ...unless there's some video we can fill with */
233         for (list<ContentVideo>::const_reverse_iterator i = _decoded.rbegin(); i != _decoded.rend(); ++i) {
234                 if (i->frame.eyes() == EYES_LEFT && !filler_left_image) {
235                         filler_left_image = i->image;
236                         filler_left_part = i->part;
237                 } else if (i->frame.eyes() == EYES_RIGHT && !filler_right_image) {
238                         filler_right_image = i->image;
239                         filler_right_part = i->part;
240                 }
241
242                 if (filler_left_image && filler_right_image) {
243                         break;
244                 }
245         }
246
247         while (from != to) {
248
249 #ifdef DCPOMATIC_DEBUG
250                 test_gaps++;
251 #endif
252
253                 _decoded.push_back (
254                         ContentVideo (
255                                 from.eyes() == EYES_LEFT ? filler_left_image : filler_right_image,
256                                 from,
257                                 from.eyes() == EYES_LEFT ? filler_left_part : filler_right_part
258                                 )
259                         );
260
261                 ++from;
262         }
263 }
264
265 /** Called by decoder classes when they have a video frame ready.
266  *  @param frame Frame index within the content; this does not take into account 3D
267  *  so for 3D_ALTERNATE this value goes:
268  *     0: frame 0 left
269  *     1: frame 0 right
270  *     2: frame 1 left
271  *     3: frame 1 right
272  *  and so on.
273  */
274 void
275 VideoDecoder::give (shared_ptr<const ImageProxy> image, Frame frame)
276 {
277         if (_ignore) {
278                 return;
279         }
280
281         _log->log (String::compose ("VD receives %1", frame), LogEntry::TYPE_DEBUG_DECODE);
282
283         /* Work out what we are going to push into _decoded next */
284         list<ContentVideo> to_push;
285         switch (_content->video->frame_type ()) {
286         case VIDEO_FRAME_TYPE_2D:
287                 to_push.push_back (ContentVideo (image, VideoFrame (frame, EYES_BOTH), PART_WHOLE));
288                 break;
289         case VIDEO_FRAME_TYPE_3D:
290         {
291                 /* We receive the same frame index twice for 3D; hence we know which
292                    frame this one is.
293                 */
294                 bool const same = (!_decoded.empty() && frame == _decoded.back().frame.index());
295                 to_push.push_back (ContentVideo (image, VideoFrame (frame, same ? EYES_RIGHT : EYES_LEFT), PART_WHOLE));
296                 break;
297         }
298         case VIDEO_FRAME_TYPE_3D_ALTERNATE:
299                 to_push.push_back (ContentVideo (image, VideoFrame (frame / 2, (frame % 2) ? EYES_RIGHT : EYES_LEFT), PART_WHOLE));
300                 break;
301         case VIDEO_FRAME_TYPE_3D_LEFT_RIGHT:
302                 to_push.push_back (ContentVideo (image, VideoFrame (frame, EYES_LEFT), PART_LEFT_HALF));
303                 to_push.push_back (ContentVideo (image, VideoFrame (frame, EYES_RIGHT), PART_RIGHT_HALF));
304                 break;
305         case VIDEO_FRAME_TYPE_3D_TOP_BOTTOM:
306                 to_push.push_back (ContentVideo (image, VideoFrame (frame, EYES_LEFT), PART_TOP_HALF));
307                 to_push.push_back (ContentVideo (image, VideoFrame (frame, EYES_RIGHT), PART_BOTTOM_HALF));
308                 break;
309         case VIDEO_FRAME_TYPE_3D_LEFT:
310                 to_push.push_back (ContentVideo (image, VideoFrame (frame, EYES_LEFT), PART_WHOLE));
311                 break;
312         case VIDEO_FRAME_TYPE_3D_RIGHT:
313                 to_push.push_back (ContentVideo (image, VideoFrame (frame, EYES_RIGHT), PART_WHOLE));
314                 break;
315         default:
316                 DCPOMATIC_ASSERT (false);
317         }
318
319         /* Now VideoDecoder is required never to have gaps in the frames that it presents
320            via get_video().  Hence we need to fill in any gap between the last thing in _decoded
321            and the things we are about to push.
322         */
323
324         optional<VideoFrame> from;
325
326         if (_decoded.empty() && _last_seek_time && _last_seek_accurate) {
327                 from = VideoFrame (
328                         _last_seek_time->frames_round (_content->active_video_frame_rate ()),
329                         _content->video->frame_type() == VIDEO_FRAME_TYPE_2D ? EYES_BOTH : EYES_LEFT
330                         );
331         } else if (!_decoded.empty ()) {
332                 /* Get the last frame we have */
333                 from = _decoded.back().frame;
334                 /* And move onto the first frame we need */
335                 ++(*from);
336                 if (_content->video->frame_type() == VIDEO_FRAME_TYPE_3D_LEFT || _content->video->frame_type() == VIDEO_FRAME_TYPE_3D_RIGHT) {
337                         /* The previous ++ will increment a 3D-left-eye to the same index right-eye.  If we are dealing with
338                            a single-eye source we need an extra ++ to move back to the same eye.
339                         */
340                         ++(*from);
341                 }
342         }
343
344         /* If we've pre-rolled on a seek we may now receive out-of-order frames
345            (frames before the last seek time) which we can just ignore.
346         */
347         if (from && (*from) > to_push.front().frame) {
348                 return;
349         }
350
351         int const max_decoded_size = 96;
352
353         /* If _decoded is already `full' there is no point in adding anything more to it,
354            as the new stuff will just be removed again.
355         */
356         if (_decoded.size() < max_decoded_size) {
357                 if (from) {
358                         switch (_content->video->frame_type ()) {
359                         case VIDEO_FRAME_TYPE_2D:
360                                 fill_one_eye (from->index(), to_push.front().frame.index(), EYES_BOTH);
361                                 break;
362                         case VIDEO_FRAME_TYPE_3D:
363                         case VIDEO_FRAME_TYPE_3D_LEFT_RIGHT:
364                         case VIDEO_FRAME_TYPE_3D_TOP_BOTTOM:
365                         case VIDEO_FRAME_TYPE_3D_ALTERNATE:
366                                 fill_both_eyes (from.get(), to_push.front().frame);
367                                 break;
368                         case VIDEO_FRAME_TYPE_3D_LEFT:
369                                 fill_one_eye (from->index(), to_push.front().frame.index(), EYES_LEFT);
370                                 break;
371                         case VIDEO_FRAME_TYPE_3D_RIGHT:
372                                 fill_one_eye (from->index(), to_push.front().frame.index(), EYES_RIGHT);
373                                 break;
374                         }
375                 }
376
377                 copy (to_push.begin(), to_push.end(), back_inserter (_decoded));
378         }
379
380         /* We can't let this build up too much or we will run out of memory.  There is a
381            `best' value for the allowed size of _decoded which balances memory use
382            with decoding efficiency (lack of seeks).  Throwing away video frames here
383            is not a problem for correctness, so do it.
384         */
385         while (_decoded.size() > max_decoded_size) {
386                 _decoded.pop_back ();
387         }
388 }
389
390 void
391 VideoDecoder::seek (ContentTime s, bool accurate)
392 {
393         _decoded.clear ();
394         _last_seek_time = s;
395         _last_seek_accurate = accurate;
396 }
397
398 /** Set this decoder never to produce any data */
399 void
400 VideoDecoder::set_ignore ()
401 {
402         _ignore = true;
403 }