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