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