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