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