409963016f76304d7829d47f2170984c9799fe1d
[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 "cross.h"
26 #include "compose.hpp"
27 #include "exceptions.h"
28 #include <boost/weak_ptr.hpp>
29 #include <boost/shared_ptr.hpp>
30
31 #define LOG_TIMING(...)  _log->log (String::compose(__VA_ARGS__), LogEntry::TYPE_TIMING);
32 #define LOG_WARNING(...) _log->log (String::compose(__VA_ARGS__), LogEntry::TYPE_WARNING);
33
34 using std::cout;
35 using std::pair;
36 using std::make_pair;
37 using std::string;
38 using boost::weak_ptr;
39 using boost::shared_ptr;
40 using boost::bind;
41 using boost::optional;
42 using boost::function;
43
44 /** Minimum video readahead in frames */
45 #define MINIMUM_VIDEO_READAHEAD 10
46 /** Maximum video readahead in frames; should never be reached unless there are bugs in Player */
47 #define MAXIMUM_VIDEO_READAHEAD 48
48 /** Minimum audio readahead in frames */
49 #define MINIMUM_AUDIO_READAHEAD (48000 * MINIMUM_VIDEO_READAHEAD / 24)
50 /** Minimum audio readahead in frames; should never be reached unless there are bugs in Player */
51 #define MAXIMUM_AUDIO_READAHEAD (48000 * MAXIMUM_VIDEO_READAHEAD / 24)
52
53 /** @param pixel_format Pixel format functor that will be used when calling ::image on PlayerVideos coming out of this
54  *  butler.  This will be used (where possible) to prepare the PlayerVideos so that calling image() on them is quick().
55  *  @param aligned Same as above for the `aligned' flag.
56  *  @param fast Same as above for the `fast' flag.
57  */
58 Butler::Butler (
59         shared_ptr<Player> player,
60         shared_ptr<Log> log,
61         AudioMapping audio_mapping,
62         int audio_channels,
63         function<AVPixelFormat (AVPixelFormat)> pixel_format,
64         bool aligned,
65         bool fast
66         )
67         : _player (player)
68         , _log (log)
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));
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, _3), boost::signals2::at_front);
89         _thread = new 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         if (_log) {
99                 LOG_TIMING("start-prepare-threads %1", boost::thread::hardware_concurrency() * 2);
100         }
101
102         for (size_t i = 0; i < boost::thread::hardware_concurrency() * 2; ++i) {
103                 _prepare_pool.create_thread (bind (&boost::asio::io_service::run, &_prepare_service));
104         }
105 }
106
107 Butler::~Butler ()
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 (boost::thread_interrupted& e) {
122                 /* No problem */
123         }
124         delete _thread;
125 }
126
127 /** Caller must hold a lock on _mutex */
128 bool
129 Butler::should_run () const
130 {
131         if (_video.size() >= MAXIMUM_VIDEO_READAHEAD * 10) {
132                 /* This is way too big */
133                 throw ProgrammingError
134                         (__FILE__, __LINE__, String::compose ("Butler video buffers reached %1 frames (audio is %2)", _video.size(), _audio.size()));
135         }
136
137         if (_audio.size() >= MAXIMUM_AUDIO_READAHEAD * 10) {
138                 /* This is way too big */
139                 throw ProgrammingError
140                         (__FILE__, __LINE__, String::compose ("Butler audio buffers reached %1 frames (video is %2)", _audio.size(), _video.size()));
141         }
142
143         if (_video.size() >= MAXIMUM_VIDEO_READAHEAD * 2 && _log) {
144                 LOG_WARNING ("Butler video buffers reached %1 frames (audio is %2)", _video.size(), _audio.size());
145         }
146
147         if (_audio.size() >= MAXIMUM_AUDIO_READAHEAD * 2 && _log) {
148                 LOG_WARNING ("Butler audio buffers reached %1 frames (video is %2)", _audio.size(), _video.size());
149         }
150
151         if (_stop_thread || _finished || _died || _suspended) {
152                 /* Definitely do not run */
153                 return false;
154         }
155
156         if (_video.size() < MINIMUM_VIDEO_READAHEAD || (!_disable_audio && _audio.size() < MINIMUM_AUDIO_READAHEAD)) {
157                 /* Definitely do run: we need data */
158                 return true;
159         }
160
161         /* Run if we aren't full of video or audio */
162         return (_video.size() < MAXIMUM_VIDEO_READAHEAD) && (_audio.size() < MAXIMUM_AUDIO_READAHEAD);
163 }
164
165 void
166 Butler::thread ()
167 try
168 {
169         while (true) {
170                 boost::mutex::scoped_lock lm (_mutex);
171
172                 /* Wait until we have something to do */
173                 while (!should_run() && !_pending_seek_position) {
174                         _summon.wait (lm);
175                 }
176
177                 /* Do any seek that has been requested */
178                 if (_pending_seek_position) {
179                         _finished = false;
180                         _player->seek (*_pending_seek_position, _pending_seek_accurate);
181                         _pending_seek_position = optional<DCPTime> ();
182                 }
183
184                 /* Fill _video and _audio.  Don't try to carry on if a pending seek appears
185                    while lm is unlocked, as in that state nothing will be added to
186                    _video/_audio.
187                 */
188                 while (should_run() && !_pending_seek_position) {
189                         lm.unlock ();
190                         bool const r = _player->pass ();
191                         lm.lock ();
192                         if (r) {
193                                 _finished = true;
194                                 _arrived.notify_all ();
195                                 break;
196                         }
197                         _arrived.notify_all ();
198                 }
199         }
200 } catch (boost::thread_interrupted) {
201         /* The butler thread is being terminated */
202         boost::mutex::scoped_lock lm (_mutex);
203         _finished = true;
204         _arrived.notify_all ();
205 } catch (...) {
206         store_current ();
207         boost::mutex::scoped_lock lm (_mutex);
208         _died = true;
209         _arrived.notify_all ();
210 }
211
212 pair<shared_ptr<PlayerVideo>, DCPTime>
213 Butler::get_video (Error* e)
214 {
215         boost::mutex::scoped_lock lm (_mutex);
216
217         if (_suspended) {
218                 if (e) {
219                         *e = AGAIN;
220                 }
221                 return make_pair(shared_ptr<PlayerVideo>(), DCPTime());
222         }
223
224         /* Wait for data if we have none */
225         while (_video.empty() && !_finished && !_died) {
226                 _arrived.wait (lm);
227         }
228
229         if (_video.empty()) {
230                 if (e) {
231                         *e = NONE;
232                 }
233                 return make_pair(shared_ptr<PlayerVideo>(), DCPTime());
234         }
235
236         pair<shared_ptr<PlayerVideo>, DCPTime> const r = _video.get ();
237         _summon.notify_all ();
238         return r;
239 }
240
241 optional<TextRingBuffers::Data>
242 Butler::get_closed_caption ()
243 {
244         boost::mutex::scoped_lock lm (_mutex);
245         return _closed_caption.get ();
246 }
247
248 void
249 Butler::seek (DCPTime position, bool accurate)
250 {
251         boost::mutex::scoped_lock lm (_mutex);
252         seek_unlocked (position, accurate);
253 }
254
255 void
256 Butler::seek_unlocked (DCPTime position, bool accurate)
257 {
258         if (_died) {
259                 return;
260         }
261
262         _finished = false;
263         _pending_seek_position = position;
264         _pending_seek_accurate = accurate;
265
266         {
267                 boost::mutex::scoped_lock lm (_buffers_mutex);
268                 _video.clear ();
269                 _audio.clear ();
270                 _closed_caption.clear ();
271         }
272
273         _summon.notify_all ();
274 }
275
276 void
277 Butler::prepare (weak_ptr<PlayerVideo> weak_video) const
278 {
279         shared_ptr<PlayerVideo> video = weak_video.lock ();
280         /* If the weak_ptr cannot be locked the video obviously no longer requires any work */
281         if (video) {
282                 if (_log) {
283                         LOG_TIMING("start-prepare in %1", thread_id());
284                 }
285
286                 video->prepare (_pixel_format, _aligned, _fast);
287
288                 if (_log) {
289                         LOG_TIMING("finish-prepare in %1", thread_id());
290                 }
291         }
292 }
293
294 void
295 Butler::video (shared_ptr<PlayerVideo> video, DCPTime time)
296 {
297         boost::mutex::scoped_lock lm (_mutex);
298
299         if (_pending_seek_position) {
300                 /* Don't store any video in this case */
301                 return;
302         }
303
304         _prepare_service.post (bind (&Butler::prepare, this, weak_ptr<PlayerVideo>(video)));
305
306         boost::mutex::scoped_lock lm2 (_buffers_mutex);
307         _video.put (video, time);
308 }
309
310 void
311 Butler::audio (shared_ptr<AudioBuffers> audio, DCPTime time)
312 {
313         {
314                 boost::mutex::scoped_lock lm (_mutex);
315                 if (_pending_seek_position || _disable_audio) {
316                         /* Don't store any audio in these cases */
317                         return;
318                 }
319         }
320
321         boost::mutex::scoped_lock lm2 (_buffers_mutex);
322         _audio.put (remap (audio, _audio_channels, _audio_mapping), time);
323 }
324
325 /** Try to get `frames' frames of audio and copy it into `out'.  Silence
326  *  will be filled if no audio is available.
327  *  @return time of this audio, or unset if there was a buffer underrun.
328  */
329 optional<DCPTime>
330 Butler::get_audio (float* out, Frame frames)
331 {
332         optional<DCPTime> t = _audio.get (out, _audio_channels, frames);
333         _summon.notify_all ();
334         return t;
335 }
336
337 void
338 Butler::disable_audio ()
339 {
340         boost::mutex::scoped_lock lm (_mutex);
341         _disable_audio = true;
342 }
343
344 pair<size_t, string>
345 Butler::memory_used () const
346 {
347         /* XXX: should also look at _audio.memory_used() */
348         return _video.memory_used();
349 }
350
351 void
352 Butler::player_change (ChangeType type, bool frequent)
353 {
354         boost::mutex::scoped_lock lm (_mutex);
355
356         if (type == CHANGE_TYPE_PENDING) {
357                 ++_suspended;
358         } else if (type == CHANGE_TYPE_DONE) {
359                 --_suspended;
360                 if (_died || _pending_seek_position || frequent) {
361                         lm.unlock ();
362                         _summon.notify_all ();
363                         return;
364                 }
365
366                 DCPTime seek_to;
367                 DCPTime next = _video.get().second;
368                 if (_awaiting && _awaiting > next) {
369                         /* We have recently done a player_changed seek and our buffers haven't been refilled yet,
370                            so assume that we're seeking to the same place as last time.
371                         */
372                         seek_to = *_awaiting;
373                 } else {
374                         seek_to = next;
375                 }
376
377                 seek_unlocked (seek_to, true);
378                 _awaiting = seek_to;
379         } else if (type == CHANGE_TYPE_CANCELLED) {
380                 --_suspended;
381         }
382
383         lm.unlock ();
384         _summon.notify_all ();
385 }
386
387 void
388 Butler::text (PlayerText pt, TextType type, optional<DCPTextTrack> track, DCPTimePeriod period)
389 {
390         if (type != TEXT_CLOSED_CAPTION) {
391                 return;
392         }
393
394         DCPOMATIC_ASSERT (track);
395
396         boost::mutex::scoped_lock lm2 (_buffers_mutex);
397         _closed_caption.put (pt, *track, period);
398 }