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