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