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