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