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