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