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