Throw exceptions when things in the butler get really out of hand.
[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 "compose.hpp"
26 #include "exceptions.h"
27 #include <boost/weak_ptr.hpp>
28 #include <boost/shared_ptr.hpp>
29
30 using std::cout;
31 using std::pair;
32 using std::make_pair;
33 using std::string;
34 using boost::weak_ptr;
35 using boost::shared_ptr;
36 using boost::bind;
37 using boost::optional;
38
39 /** Minimum video readahead in frames */
40 #define MINIMUM_VIDEO_READAHEAD 10
41 /** Maximum video readahead in frames; should never be reached unless there are bugs in Player */
42 #define MAXIMUM_VIDEO_READAHEAD 24
43 /** Minimum audio readahead in frames */
44 #define MINIMUM_AUDIO_READAHEAD (48000 * MINIMUM_VIDEO_READAHEAD / 24)
45 /** Minimum audio readahead in frames; should never be reached unless there are bugs in Player */
46 #define MAXIMUM_AUDIO_READAHEAD (48000 * MAXIMUM_VIDEO_READAHEAD / 24)
47
48 #define LOG_WARNING(...) _log->log (String::compose(__VA_ARGS__), LogEntry::TYPE_WARNING);
49
50 Butler::Butler (shared_ptr<Player> player, shared_ptr<Log> log, AudioMapping audio_mapping, int audio_channels)
51         : _player (player)
52         , _log (log)
53         , _prepare_work (new boost::asio::io_service::work (_prepare_service))
54         , _pending_seek_accurate (false)
55         , _finished (false)
56         , _died (false)
57         , _stop_thread (false)
58         , _audio_mapping (audio_mapping)
59         , _audio_channels (audio_channels)
60         , _disable_audio (false)
61 {
62         _player_video_connection = _player->Video.connect (bind (&Butler::video, this, _1, _2));
63         _player_audio_connection = _player->Audio.connect (bind (&Butler::audio, this, _1));
64         _thread = new boost::thread (bind (&Butler::thread, this));
65 #ifdef DCPOMATIC_LINUX
66         pthread_setname_np (_thread->native_handle(), "butler");
67 #endif
68
69         /* Create some threads to do work on the PlayerVideos we are creating; at present this is used to
70            multi-thread JPEG2000 decoding.
71         */
72         for (size_t i = 0; i < boost::thread::hardware_concurrency(); ++i) {
73                 _prepare_pool.create_thread (bind (&boost::asio::io_service::run, &_prepare_service));
74         }
75 }
76
77 Butler::~Butler ()
78 {
79         {
80                 boost::mutex::scoped_lock lm (_mutex);
81                 _stop_thread = true;
82         }
83
84         _prepare_work.reset ();
85         _prepare_pool.join_all ();
86         _prepare_service.stop ();
87
88         _thread->interrupt ();
89         try {
90                 _thread->join ();
91         } catch (boost::thread_interrupted& e) {
92                 /* No problem */
93         }
94         delete _thread;
95 }
96
97 /** Caller must hold a lock on _mutex */
98 bool
99 Butler::should_run () const
100 {
101         if (_video.size() >= MAXIMUM_VIDEO_READAHEAD * 10) {
102                 /* This is way too big */
103                 throw ProgrammingError
104                         (__FILE__, __LINE__, String::compose ("Butler video buffers reached %1 frames (audio is %2)", _video.size(), _audio.size()));
105         }
106
107         if (_audio.size() >= MAXIMUM_AUDIO_READAHEAD * 10) {
108                 /* This is way too big */
109                 throw ProgrammingError
110                         (__FILE__, __LINE__, String::compose ("Butler audio buffers reached %1 frames (video is %2)", _audio.size(), _video.size()));
111         }
112
113         if (_video.size() >= MAXIMUM_VIDEO_READAHEAD * 2) {
114                 LOG_WARNING ("Butler video buffers reached %1 frames (audio is %2)", _video.size(), _audio.size());
115         }
116
117         if (_audio.size() >= MAXIMUM_AUDIO_READAHEAD * 2) {
118                 LOG_WARNING ("Butler audio buffers reached %1 frames (video is %2)", _audio.size(), _video.size());
119         }
120
121         if (_stop_thread || _finished || _died) {
122                 /* Definitely do not run */
123                 return false;
124         }
125
126         if (_video.size() < MINIMUM_VIDEO_READAHEAD || (!_disable_audio && _audio.size() < MINIMUM_AUDIO_READAHEAD)) {
127                 /* Definitely do run: we need data */
128                 return true;
129         }
130
131         /* Run if we aren't full of video or audio */
132         return (_video.size() < MAXIMUM_VIDEO_READAHEAD) && (_audio.size() < MAXIMUM_AUDIO_READAHEAD);
133 }
134
135 void
136 Butler::thread ()
137 try
138 {
139         while (true) {
140                 boost::mutex::scoped_lock lm (_mutex);
141
142                 /* Wait until we have something to do */
143                 while (!should_run() && !_pending_seek_position) {
144                         _summon.wait (lm);
145                 }
146
147                 /* Do any seek that has been requested */
148                 if (_pending_seek_position) {
149                         _finished = false;
150                         _player->seek (*_pending_seek_position, _pending_seek_accurate);
151                         _pending_seek_position = optional<DCPTime> ();
152                 }
153
154                 /* Fill _video and _audio.  Don't try to carry on if a pending seek appears
155                    while lm is unlocked, as in that state nothing will be added to
156                    _video/_audio.
157                 */
158                 while (should_run() && !_pending_seek_position) {
159                         lm.unlock ();
160                         bool const r = _player->pass ();
161                         lm.lock ();
162                         if (r) {
163                                 _finished = true;
164                                 _arrived.notify_all ();
165                                 break;
166                         }
167                         _arrived.notify_all ();
168                 }
169         }
170 } catch (boost::thread_interrupted) {
171         /* The butler thread is being terminated */
172         boost::mutex::scoped_lock lm (_mutex);
173         _finished = true;
174         _arrived.notify_all ();
175 } catch (...) {
176         store_current ();
177         boost::mutex::scoped_lock lm (_mutex);
178         _died = true;
179         _arrived.notify_all ();
180 }
181
182 pair<shared_ptr<PlayerVideo>, DCPTime>
183 Butler::get_video ()
184 {
185         boost::mutex::scoped_lock lm (_mutex);
186
187         /* Wait for data if we have none */
188         while (_video.empty() && !_finished && !_died) {
189                 _arrived.wait (lm);
190         }
191
192         if (_video.empty()) {
193                 return make_pair (shared_ptr<PlayerVideo>(), DCPTime());
194         }
195
196         pair<shared_ptr<PlayerVideo>, DCPTime> const r = _video.get ();
197         _summon.notify_all ();
198         return r;
199 }
200
201 void
202 Butler::seek (DCPTime position, bool accurate)
203 {
204         boost::mutex::scoped_lock lm (_mutex);
205         if (_died) {
206                 return;
207         }
208
209         _video.clear ();
210         _audio.clear ();
211         _finished = false;
212         _pending_seek_position = position;
213         _pending_seek_accurate = accurate;
214         _summon.notify_all ();
215 }
216
217 void
218 Butler::prepare (weak_ptr<PlayerVideo> weak_video) const
219 {
220         shared_ptr<PlayerVideo> video = weak_video.lock ();
221         /* If the weak_ptr cannot be locked the video obviously no longer requires any work */
222         if (video) {
223                 video->prepare ();
224         }
225 }
226
227 void
228 Butler::video (shared_ptr<PlayerVideo> video, DCPTime time)
229 {
230         boost::mutex::scoped_lock lm (_mutex);
231         if (_pending_seek_position) {
232                 /* Don't store any video while a seek is pending */
233                 return;
234         }
235
236         _prepare_service.post (bind (&Butler::prepare, this, weak_ptr<PlayerVideo>(video)));
237         _video.put (video, time);
238 }
239
240 void
241 Butler::audio (shared_ptr<AudioBuffers> audio)
242 {
243         {
244                 boost::mutex::scoped_lock lm (_mutex);
245                 if (_pending_seek_position || _disable_audio) {
246                         /* Don't store any audio while a seek is pending, or if audio is disabled */
247                         return;
248                 }
249         }
250
251         _audio.put (remap (audio, _audio_channels, _audio_mapping));
252 }
253
254 /** Try to get `frames' frames of audio and copy it into `out'.  Silence
255  *  will be filled if no audio is available.
256  *  @return true if there was a buffer underrun, otherwise false.
257  */
258 bool
259 Butler::get_audio (float* out, Frame frames)
260 {
261         bool const underrun = _audio.get (out, _audio_channels, frames);
262         _summon.notify_all ();
263         return underrun;
264 }
265
266 void
267 Butler::disable_audio ()
268 {
269         boost::mutex::scoped_lock lm (_mutex);
270         _disable_audio = true;
271 }
272
273 pair<size_t, string>
274 Butler::memory_used () const
275 {
276         /* XXX: should also look at _audio.memory_used() */
277         return _video.memory_used();
278 }