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