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