wip: hacks which at least get GPU-decoded image on screen
[dcpomatic.git] / src / lib / butler.cc
1 /*
2     Copyright (C) 2016-2018 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 "butler.h"
22 #include "player.h"
23 #include "util.h"
24 #include "log.h"
25 #include "dcpomatic_log.h"
26 #include "cross.h"
27 #include "compose.hpp"
28 #include "exceptions.h"
29 #include "cpu_player_video_preparer.h"
30 #include "fastvideo_player_video_preparer.h"
31 #include <boost/weak_ptr.hpp>
32 #include <boost/shared_ptr.hpp>
33
34 using std::cout;
35 using std::pair;
36 using std::make_pair;
37 using std::string;
38 using boost::weak_ptr;
39 using boost::shared_ptr;
40 using boost::bind;
41 using boost::optional;
42 using boost::function;
43 using namespace dcpomatic;
44 #if BOOST_VERSION >= 106100
45 using namespace boost::placeholders;
46 #endif
47
48 /** Minimum video readahead in frames */
49 #define MINIMUM_VIDEO_READAHEAD 64
50 /** Maximum video readahead in frames; should never be exceeded (by much) unless there are bugs in Player */
51 #define MAXIMUM_VIDEO_READAHEAD 128
52 /** Minimum audio readahead in frames */
53 #define MINIMUM_AUDIO_READAHEAD (48000 * MINIMUM_VIDEO_READAHEAD / 24)
54 /** Maximum audio readahead in frames; should never be exceeded (by much) unless there are bugs in Player */
55 #define MAXIMUM_AUDIO_READAHEAD (48000 * MAXIMUM_VIDEO_READAHEAD / 24)
56
57 /** @param pixel_format Pixel format functor that will be used when calling ::image on PlayerVideos coming out of this
58  *  butler.  This will be used (where possible) to prepare the PlayerVideos so that calling image() on them is quick.
59  *  @param aligned Same as above for the `aligned' flag.
60  *  @param fast Same as above for the `fast' flag.
61  */
62 Butler::Butler (
63         shared_ptr<Player> player,
64         AudioMapping audio_mapping,
65         int audio_channels,
66         function<AVPixelFormat (AVPixelFormat)> pixel_format,
67         bool aligned,
68         bool fast
69         )
70         : _player (player)
71         , _pending_seek_accurate (false)
72         , _suspended (0)
73         , _finished (false)
74         , _died (false)
75         , _stop_thread (false)
76         , _audio_mapping (audio_mapping)
77         , _audio_channels (audio_channels)
78         , _disable_audio (false)
79         , _pixel_format (pixel_format)
80         , _aligned (aligned)
81         , _fast (fast)
82 {
83         _preparer.reset (new FastvideoPlayerVideoPreparer(pixel_format, aligned, fast));
84
85         _player_video_connection = _player->Video.connect (bind (&Butler::video, this, _1, _2));
86         _player_audio_connection = _player->Audio.connect (bind (&Butler::audio, this, _1, _2, _3));
87         _player_text_connection = _player->Text.connect (bind (&Butler::text, this, _1, _2, _3, _4));
88         /* The butler must hear about things first, otherwise it might not sort out suspensions in time for
89            get_video() to be called in response to this signal.
90         */
91         _player_change_connection = _player->Change.connect (bind (&Butler::player_change, this, _1), boost::signals2::at_front);
92         _thread = boost::thread (bind(&Butler::thread, this));
93 #ifdef DCPOMATIC_LINUX
94         pthread_setname_np (_thread.native_handle(), "butler");
95 #endif
96 }
97
98 Butler::~Butler ()
99 {
100         boost::this_thread::disable_interruption dis;
101
102         {
103                 boost::mutex::scoped_lock lm (_mutex);
104                 _stop_thread = true;
105         }
106
107         _thread.interrupt ();
108         try {
109                 _thread.join ();
110         } catch (...) {}
111
112         _preparer.reset ();
113 }
114
115 /** Caller must hold a lock on _mutex */
116 bool
117 Butler::should_run () const
118 {
119         if (_video.size() >= MAXIMUM_VIDEO_READAHEAD * 10) {
120                 /* This is way too big */
121                 optional<DCPTime> pos = _audio.peek();
122                 if (pos) {
123                         throw ProgrammingError
124                                 (__FILE__, __LINE__, String::compose ("Butler video buffers reached %1 frames (audio is %2 at %3)", _video.size(), _audio.size(), pos->get()));
125                 } else {
126                         throw ProgrammingError
127                                 (__FILE__, __LINE__, String::compose ("Butler video buffers reached %1 frames (audio is %2)", _video.size(), _audio.size()));
128                 }
129         }
130
131         if (_audio.size() >= MAXIMUM_AUDIO_READAHEAD * 10) {
132                 /* This is way too big */
133                 optional<DCPTime> pos = _audio.peek();
134                 if (pos) {
135                         throw ProgrammingError
136                                 (__FILE__, __LINE__, String::compose ("Butler audio buffers reached %1 frames at %2 (video is %3)", _audio.size(), pos->get(), _video.size()));
137                 } else {
138                         throw ProgrammingError
139                                 (__FILE__, __LINE__, String::compose ("Butler audio buffers reached %1 frames (video is %3)", _audio.size(), _video.size()));
140                 }
141         }
142
143         if (_video.size() >= MAXIMUM_VIDEO_READAHEAD * 2) {
144                 LOG_WARNING ("Butler video buffers reached %1 frames (audio is %2)", _video.size(), _audio.size());
145         }
146
147         if (_audio.size() >= MAXIMUM_AUDIO_READAHEAD * 2) {
148                 LOG_WARNING ("Butler audio buffers reached %1 frames (video is %2)", _audio.size(), _video.size());
149         }
150
151         if (_stop_thread || _finished || _died || _suspended) {
152                 /* Definitely do not run */
153                 return false;
154         }
155
156         if (_video.size() < MINIMUM_VIDEO_READAHEAD || (!_disable_audio && _audio.size() < MINIMUM_AUDIO_READAHEAD)) {
157                 /* Definitely do run: we need data */
158                 return true;
159         }
160
161         /* Run if we aren't full of video or audio */
162         return (_video.size() < MAXIMUM_VIDEO_READAHEAD) && (_audio.size() < MAXIMUM_AUDIO_READAHEAD);
163 }
164
165 void
166 Butler::thread ()
167 try
168 {
169         while (true) {
170                 boost::mutex::scoped_lock lm (_mutex);
171
172                 /* Wait until we have something to do */
173                 while (!should_run() && !_pending_seek_position) {
174                         _summon.wait (lm);
175                 }
176
177                 /* Do any seek that has been requested */
178                 if (_pending_seek_position) {
179                         _finished = false;
180                         _player->seek (*_pending_seek_position, _pending_seek_accurate);
181                         _pending_seek_position = optional<DCPTime> ();
182                 }
183
184                 /* Fill _video and _audio.  Don't try to carry on if a pending seek appears
185                    while lm is unlocked, as in that state nothing will be added to
186                    _video/_audio.
187                 */
188                 while (should_run() && !_pending_seek_position) {
189                         lm.unlock ();
190                         bool const r = _player->pass ();
191                         lm.lock ();
192                         if (r) {
193                                 _finished = true;
194                                 _arrived.notify_all ();
195                                 break;
196                         }
197                         _arrived.notify_all ();
198                 }
199         }
200 } catch (boost::thread_interrupted) {
201         /* The butler thread is being terminated */
202         boost::mutex::scoped_lock lm (_mutex);
203         _finished = true;
204         _arrived.notify_all ();
205 } catch (std::exception& e) {
206         store_current ();
207         boost::mutex::scoped_lock lm (_mutex);
208         _died = true;
209         _died_message = e.what ();
210         _arrived.notify_all ();
211 } catch (...) {
212         store_current ();
213         boost::mutex::scoped_lock lm (_mutex);
214         _died = true;
215         _arrived.notify_all ();
216 }
217
218 /** @param blocking true if we should block until video is available.  If blocking is false
219  *  and no video is immediately available the method will return a 0 PlayerVideo and the error AGAIN.
220  *  @param e if non-0 this is filled with an error code (if an error occurs) or is untouched if no error occurs.
221  */
222 pair<shared_ptr<PlayerVideo>, DCPTime>
223 Butler::get_video (bool blocking, Error* e)
224 {
225         boost::mutex::scoped_lock lm (_mutex);
226
227         if (_suspended || (_video.empty() && !blocking)) {
228                 if (e) {
229                         e->code = Error::AGAIN;
230                 }
231                 return make_pair(shared_ptr<PlayerVideo>(), DCPTime());
232         }
233
234         /* Wait for data if we have none */
235         while (_video.empty() && !_finished && !_died) {
236                 _arrived.wait (lm);
237         }
238
239         if (_video.empty()) {
240                 if (e) {
241                         if (_died) {
242                                 e->code = Error::DIED;
243                                 e->message = _died_message;
244                         } else if (_finished) {
245                                 e->code = Error::FINISHED;
246                         } else {
247                                 e->code = Error::NONE;
248                         }
249                 }
250                 return make_pair(shared_ptr<PlayerVideo>(), DCPTime());
251         }
252
253         pair<shared_ptr<PlayerVideo>, DCPTime> const r = _video.get ();
254         _summon.notify_all ();
255         return r;
256 }
257
258 optional<TextRingBuffers::Data>
259 Butler::get_closed_caption ()
260 {
261         boost::mutex::scoped_lock lm (_mutex);
262         return _closed_caption.get ();
263 }
264
265 void
266 Butler::seek (DCPTime position, bool accurate)
267 {
268         boost::mutex::scoped_lock lm (_mutex);
269         _awaiting = optional<DCPTime>();
270         seek_unlocked (position, accurate);
271 }
272
273 void
274 Butler::seek_unlocked (DCPTime position, bool accurate)
275 {
276         if (_died) {
277                 return;
278         }
279
280         _finished = false;
281         _pending_seek_position = position;
282         _pending_seek_accurate = accurate;
283
284         _video.clear ();
285         _audio.clear ();
286         _closed_caption.clear ();
287
288         _summon.notify_all ();
289 }
290
291 void
292 Butler::video (shared_ptr<PlayerVideo> video, DCPTime time)
293 {
294         boost::mutex::scoped_lock lm (_mutex);
295
296         if (_pending_seek_position) {
297                 /* Don't store any video in this case */
298                 return;
299         }
300
301         _preparer->request (video);
302
303         _video.put (video, time);
304 }
305
306 void
307 Butler::audio (shared_ptr<AudioBuffers> audio, DCPTime time, int frame_rate)
308 {
309         boost::mutex::scoped_lock lm (_mutex);
310         if (_pending_seek_position || _disable_audio) {
311                 /* Don't store any audio in these cases */
312                 return;
313         }
314
315         _audio.put (remap (audio, _audio_channels, _audio_mapping), time, frame_rate);
316 }
317
318 /** Try to get `frames' frames of audio and copy it into `out'.  Silence
319  *  will be filled if no audio is available.
320  *  @return time of this audio, or unset if there was a buffer underrun.
321  */
322 optional<DCPTime>
323 Butler::get_audio (float* out, Frame frames)
324 {
325         optional<DCPTime> t = _audio.get (out, _audio_channels, frames);
326         _summon.notify_all ();
327         return t;
328 }
329
330 void
331 Butler::disable_audio ()
332 {
333         boost::mutex::scoped_lock lm (_mutex);
334         _disable_audio = true;
335 }
336
337 pair<size_t, string>
338 Butler::memory_used () const
339 {
340         /* XXX: should also look at _audio.memory_used() */
341         return _video.memory_used();
342 }
343
344 void
345 Butler::player_change (ChangeType type)
346 {
347         boost::mutex::scoped_lock lm (_mutex);
348
349         if (type == CHANGE_TYPE_PENDING) {
350                 ++_suspended;
351         } else if (type == CHANGE_TYPE_DONE) {
352                 --_suspended;
353                 if (_died || _pending_seek_position) {
354                         lm.unlock ();
355                         _summon.notify_all ();
356                         return;
357                 }
358
359                 DCPTime seek_to;
360                 DCPTime next = _video.get().second;
361                 if (_awaiting && _awaiting > next) {
362                         /* We have recently done a player_changed seek and our buffers haven't been refilled yet,
363                            so assume that we're seeking to the same place as last time.
364                         */
365                         seek_to = *_awaiting;
366                 } else {
367                         seek_to = next;
368                 }
369
370                 seek_unlocked (seek_to, true);
371                 _awaiting = seek_to;
372         } else if (type == CHANGE_TYPE_CANCELLED) {
373                 --_suspended;
374         }
375
376         lm.unlock ();
377         _summon.notify_all ();
378 }
379
380 void
381 Butler::text (PlayerText pt, TextType type, optional<DCPTextTrack> track, DCPTimePeriod period)
382 {
383         if (type != TEXT_CLOSED_CAPTION) {
384                 return;
385         }
386
387         DCPOMATIC_ASSERT (track);
388
389         _closed_caption.put (pt, *track, period);
390 }
391
392 string
393 Butler::Error::summary () const
394 {
395         switch (code)
396         {
397                 case Error::NONE:
398                         return "No error registered";
399                 case Error::AGAIN:
400                         return "Butler not ready";
401                 case Error::DIED:
402                         return String::compose("Butler died (%1)", message);
403                 case Error::FINISHED:
404                         return "Butler finished";
405         }
406
407         return "";
408 }
409