Fix pull timing; fix units of ReelWriter::total_written_audio_frames.
[dcpomatic.git] / src / lib / writer.cc
1 /*
2     Copyright (C) 2012-2016 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 "writer.h"
22 #include "compose.hpp"
23 #include "film.h"
24 #include "ratio.h"
25 #include "log.h"
26 #include "dcp_video.h"
27 #include "dcp_content_type.h"
28 #include "audio_mapping.h"
29 #include "config.h"
30 #include "job.h"
31 #include "cross.h"
32 #include "audio_buffers.h"
33 #include "version.h"
34 #include "font.h"
35 #include "util.h"
36 #include "reel_writer.h"
37 #include <dcp/cpl.h>
38 #include <boost/foreach.hpp>
39 #include <fstream>
40 #include <cerrno>
41 #include <iostream>
42 #include <cfloat>
43
44 #include "i18n.h"
45
46 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_GENERAL);
47 #define LOG_GENERAL_NC(...) _film->log()->log (__VA_ARGS__, LogEntry::TYPE_GENERAL);
48 #define LOG_DEBUG_ENCODE(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_DEBUG_ENCODE);
49 #define LOG_TIMING(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_TIMING);
50 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, LogEntry::TYPE_WARNING);
51 #define LOG_WARNING(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_WARNING);
52 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_ERROR);
53
54 /* OS X strikes again */
55 #undef set_key
56
57 using std::make_pair;
58 using std::pair;
59 using std::string;
60 using std::list;
61 using std::cout;
62 using std::map;
63 using std::min;
64 using std::max;
65 using boost::shared_ptr;
66 using boost::weak_ptr;
67 using boost::dynamic_pointer_cast;
68 using dcp::Data;
69
70 Writer::Writer (shared_ptr<const Film> film, weak_ptr<Job> j)
71         : _film (film)
72         , _job (j)
73         , _thread (0)
74         , _finish (false)
75         , _queued_full_in_memory (0)
76         , _maximum_frames_in_memory (0)
77         , _full_written (0)
78         , _fake_written (0)
79         , _repeat_written (0)
80         , _pushed_to_disk (0)
81 {
82         shared_ptr<Job> job = _job.lock ();
83         DCPOMATIC_ASSERT (job);
84
85         int reel_index = 0;
86         list<DCPTimePeriod> const reels = _film->reels ();
87         BOOST_FOREACH (DCPTimePeriod p, reels) {
88                 _reels.push_back (ReelWriter (film, p, job, reel_index++, reels.size(), _film->content_summary(p)));
89         }
90
91         /* We can keep track of the current audio and subtitle reels easily because audio
92            and subs arrive to the Writer in sequence.  This is not so for video.
93         */
94         _audio_reel = _reels.begin ();
95         _subtitle_reel = _reels.begin ();
96
97         /* Check that the signer is OK if we need one */
98         string reason;
99         if (_film->is_signed() && !Config::instance()->signer_chain()->valid(&reason)) {
100                 throw InvalidSignerError (reason);
101         }
102 }
103
104 void
105 Writer::start ()
106 {
107         _thread = new boost::thread (boost::bind (&Writer::thread, this));
108 }
109
110 Writer::~Writer ()
111 {
112         terminate_thread (false);
113 }
114
115 /** Pass a video frame to the writer for writing to disk at some point.
116  *  This method can be called with frames out of order.
117  *  @param encoded JPEG2000-encoded data.
118  *  @param frame Frame index within the DCP.
119  *  @param eyes Eyes that this frame image is for.
120  */
121 void
122 Writer::write (Data encoded, Frame frame, Eyes eyes)
123 {
124         boost::mutex::scoped_lock lock (_state_mutex);
125
126         while (_queued_full_in_memory > _maximum_frames_in_memory) {
127                 /* The queue is too big; wait until that is sorted out */
128                 _full_condition.wait (lock);
129         }
130
131         QueueItem qi;
132         qi.type = QueueItem::FULL;
133         qi.encoded = encoded;
134         qi.reel = video_reel (frame);
135         qi.frame = frame - _reels[qi.reel].start ();
136
137         if (_film->three_d() && eyes == EYES_BOTH) {
138                 /* 2D material in a 3D DCP; fake the 3D */
139                 qi.eyes = EYES_LEFT;
140                 _queue.push_back (qi);
141                 ++_queued_full_in_memory;
142                 qi.eyes = EYES_RIGHT;
143                 _queue.push_back (qi);
144                 ++_queued_full_in_memory;
145         } else {
146                 qi.eyes = eyes;
147                 _queue.push_back (qi);
148                 ++_queued_full_in_memory;
149         }
150
151         /* Now there's something to do: wake anything wait()ing on _empty_condition */
152         _empty_condition.notify_all ();
153 }
154
155 bool
156 Writer::can_repeat (Frame frame) const
157 {
158         return frame > _reels[video_reel(frame)].start();
159 }
160
161 /** Repeat the last frame that was written to a reel as a new frame.
162  *  @param frame Frame index within the DCP of the new (repeated) frame.
163  *  @param eyes Eyes that this repeated frame image is for.
164  */
165 void
166 Writer::repeat (Frame frame, Eyes eyes)
167 {
168         boost::mutex::scoped_lock lock (_state_mutex);
169
170         while (_queued_full_in_memory > _maximum_frames_in_memory) {
171                 /* The queue is too big; wait until that is sorted out */
172                 _full_condition.wait (lock);
173         }
174
175         QueueItem qi;
176         qi.type = QueueItem::REPEAT;
177         qi.reel = video_reel (frame);
178         qi.frame = frame - _reels[qi.reel].start ();
179         if (_film->three_d() && eyes == EYES_BOTH) {
180                 qi.eyes = EYES_LEFT;
181                 _queue.push_back (qi);
182                 qi.eyes = EYES_RIGHT;
183                 _queue.push_back (qi);
184         } else {
185                 qi.eyes = eyes;
186                 _queue.push_back (qi);
187         }
188
189         /* Now there's something to do: wake anything wait()ing on _empty_condition */
190         _empty_condition.notify_all ();
191 }
192
193 void
194 Writer::fake_write (Frame frame, Eyes eyes)
195 {
196         boost::mutex::scoped_lock lock (_state_mutex);
197
198         while (_queued_full_in_memory > _maximum_frames_in_memory) {
199                 /* The queue is too big; wait until that is sorted out */
200                 _full_condition.wait (lock);
201         }
202
203         size_t const reel = video_reel (frame);
204         Frame const reel_frame = frame - _reels[reel].start ();
205
206         FILE* file = fopen_boost (_film->info_file(_reels[reel].period()), "rb");
207         if (!file) {
208                 throw ReadFileError (_film->info_file(_reels[reel].period()));
209         }
210         dcp::FrameInfo info = _reels[reel].read_frame_info (file, reel_frame, eyes);
211         fclose (file);
212
213         QueueItem qi;
214         qi.type = QueueItem::FAKE;
215         qi.size = info.size;
216         qi.reel = reel;
217         qi.frame = reel_frame;
218         if (_film->three_d() && eyes == EYES_BOTH) {
219                 qi.eyes = EYES_LEFT;
220                 _queue.push_back (qi);
221                 qi.eyes = EYES_RIGHT;
222                 _queue.push_back (qi);
223         } else {
224                 qi.eyes = eyes;
225                 _queue.push_back (qi);
226         }
227
228         /* Now there's something to do: wake anything wait()ing on _empty_condition */
229         _empty_condition.notify_all ();
230 }
231
232 /** Write some audio frames to the DCP.
233  *  @param audio Audio data or 0 if there is no audio to be written here (i.e. it is referenced).
234  *  This method is not thread safe.
235  */
236 void
237 Writer::write (shared_ptr<const AudioBuffers> audio)
238 {
239         if (_audio_reel == _reels.end ()) {
240                 /* This audio is off the end of the last reel; ignore it */
241                 return;
242         }
243
244         _audio_reel->write (audio);
245
246         if (_audio_reel->total_written_audio_frames() >= _audio_reel->period().duration().frames_floor (_film->audio_frame_rate())) {
247                 ++_audio_reel;
248         }
249 }
250
251 /** This must be called from Writer::thread() with an appropriate lock held */
252 bool
253 Writer::have_sequenced_image_at_queue_head ()
254 {
255         if (_queue.empty ()) {
256                 return false;
257         }
258
259         _queue.sort ();
260
261         QueueItem const & f = _queue.front();
262         ReelWriter const & reel = _reels[f.reel];
263
264         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
265
266         if (f.eyes == EYES_BOTH) {
267                 /* 2D */
268                 return f.frame == (reel.last_written_video_frame() + 1);
269         }
270
271         /* 3D */
272
273         if (reel.last_written_eyes() == EYES_LEFT && f.frame == reel.last_written_video_frame() && f.eyes == EYES_RIGHT) {
274                 return true;
275         }
276
277         if (reel.last_written_eyes() == EYES_RIGHT && f.frame == (reel.last_written_video_frame() + 1) && f.eyes == EYES_LEFT) {
278                 return true;
279         }
280
281         return false;
282 }
283
284 void
285 Writer::thread ()
286 try
287 {
288         while (true)
289         {
290                 boost::mutex::scoped_lock lock (_state_mutex);
291
292                 while (true) {
293
294                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
295                                 /* We've got something to do: go and do it */
296                                 break;
297                         }
298
299                         /* Nothing to do: wait until something happens which may indicate that we do */
300                         LOG_TIMING (N_("writer-sleep queue=%1"), _queue.size());
301                         _empty_condition.wait (lock);
302                         LOG_TIMING (N_("writer-wake queue=%1"), _queue.size());
303                 }
304
305                 if (_finish && _queue.empty()) {
306                         return;
307                 }
308
309                 /* We stop here if we have been asked to finish, and if either the queue
310                    is empty or we do not have a sequenced image at its head (if this is the
311                    case we will never terminate as no new frames will be sent once
312                    _finish is true).
313                 */
314                 if (_finish && (!have_sequenced_image_at_queue_head() || _queue.empty())) {
315                         /* (Hopefully temporarily) log anything that was not written */
316                         if (!_queue.empty() && !have_sequenced_image_at_queue_head()) {
317                                 LOG_WARNING (N_("Finishing writer with a left-over queue of %1:"), _queue.size());
318                                 for (list<QueueItem>::const_iterator i = _queue.begin(); i != _queue.end(); ++i) {
319                                         if (i->type == QueueItem::FULL) {
320                                                 LOG_WARNING (N_("- type FULL, frame %1, eyes %2"), i->frame, (int) i->eyes);
321                                         } else {
322                                                 LOG_WARNING (N_("- type FAKE, size %1, frame %2, eyes %3"), i->size, i->frame, (int) i->eyes);
323                                         }
324                                 }
325                         }
326                         return;
327                 }
328
329                 /* Write any frames that we can write; i.e. those that are in sequence. */
330                 while (have_sequenced_image_at_queue_head ()) {
331                         QueueItem qi = _queue.front ();
332                         _queue.pop_front ();
333                         if (qi.type == QueueItem::FULL && qi.encoded) {
334                                 --_queued_full_in_memory;
335                         }
336
337                         lock.unlock ();
338
339                         ReelWriter& reel = _reels[qi.reel];
340
341                         switch (qi.type) {
342                         case QueueItem::FULL:
343                                 LOG_DEBUG_ENCODE (N_("Writer FULL-writes %1 (%2)"), qi.frame, (int) qi.eyes);
344                                 if (!qi.encoded) {
345                                         qi.encoded = Data (_film->j2c_path (qi.reel, qi.frame, qi.eyes, false));
346                                 }
347                                 reel.write (qi.encoded, qi.frame, qi.eyes);
348                                 ++_full_written;
349                                 break;
350                         case QueueItem::FAKE:
351                                 LOG_DEBUG_ENCODE (N_("Writer FAKE-writes %1"), qi.frame);
352                                 reel.fake_write (qi.frame, qi.eyes, qi.size);
353                                 ++_fake_written;
354                                 break;
355                         case QueueItem::REPEAT:
356                                 LOG_DEBUG_ENCODE (N_("Writer REPEAT-writes %1"), qi.frame);
357                                 reel.repeat_write (qi.frame, qi.eyes);
358                                 ++_repeat_written;
359                                 break;
360                         }
361
362                         lock.lock ();
363                 }
364
365                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
366                         /* Too many frames in memory which can't yet be written to the stream.
367                            Write some FULL frames to disk.
368                         */
369
370                         /* Find one from the back of the queue */
371                         _queue.sort ();
372                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
373                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
374                                 ++i;
375                         }
376
377                         DCPOMATIC_ASSERT (i != _queue.rend());
378                         ++_pushed_to_disk;
379                         /* For the log message below */
380                         int const awaiting = _reels[_queue.front().reel].last_written_video_frame();
381                         lock.unlock ();
382
383                         /* i is valid here, even though we don't hold a lock on the mutex,
384                            since list iterators are unaffected by insertion and only this
385                            thread could erase the last item in the list.
386                         */
387
388                         LOG_GENERAL ("Writer full; pushes %1 to disk while awaiting %2", i->frame, awaiting);
389
390                         i->encoded->write_via_temp (
391                                 _film->j2c_path (i->reel, i->frame, i->eyes, true),
392                                 _film->j2c_path (i->reel, i->frame, i->eyes, false)
393                                 );
394
395                         lock.lock ();
396                         i->encoded.reset ();
397                         --_queued_full_in_memory;
398                 }
399
400                 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
401                 _full_condition.notify_all ();
402         }
403 }
404 catch (...)
405 {
406         store_current ();
407 }
408
409 void
410 Writer::terminate_thread (bool can_throw)
411 {
412         boost::mutex::scoped_lock lock (_state_mutex);
413         if (_thread == 0) {
414                 return;
415         }
416
417         _finish = true;
418         _empty_condition.notify_all ();
419         _full_condition.notify_all ();
420         lock.unlock ();
421
422         if (_thread->joinable ()) {
423                 _thread->join ();
424         }
425
426         if (can_throw) {
427                 rethrow ();
428         }
429
430         delete _thread;
431         _thread = 0;
432 }
433
434 void
435 Writer::finish ()
436 {
437         if (!_thread) {
438                 return;
439         }
440
441         LOG_GENERAL_NC ("Terminating writer thread");
442
443         terminate_thread (true);
444
445         LOG_GENERAL_NC ("Finishing ReelWriters");
446
447         BOOST_FOREACH (ReelWriter& i, _reels) {
448                 i.finish ();
449         }
450
451         LOG_GENERAL_NC ("Writing XML");
452
453         dcp::DCP dcp (_film->dir (_film->dcp_name()));
454
455         shared_ptr<dcp::CPL> cpl (
456                 new dcp::CPL (
457                         _film->dcp_name(),
458                         _film->dcp_content_type()->libdcp_kind ()
459                         )
460                 );
461
462         dcp.add (cpl);
463
464         /* Calculate digests for each reel in parallel */
465
466         shared_ptr<Job> job = _job.lock ();
467         job->sub (_("Computing digests"));
468
469         boost::asio::io_service service;
470         boost::thread_group pool;
471
472         shared_ptr<boost::asio::io_service::work> work (new boost::asio::io_service::work (service));
473
474         int const threads = max (1, Config::instance()->num_local_encoding_threads ());
475
476         for (int i = 0; i < threads; ++i) {
477                 pool.create_thread (boost::bind (&boost::asio::io_service::run, &service));
478         }
479
480         BOOST_FOREACH (ReelWriter& i, _reels) {
481                 boost::function<void (float)> set_progress = boost::bind (&Writer::set_digest_progress, this, job.get(), _1);
482                 service.post (boost::bind (&ReelWriter::calculate_digests, &i, set_progress));
483         }
484
485         work.reset ();
486         pool.join_all ();
487         service.stop ();
488
489         /* Add reels to CPL */
490
491         BOOST_FOREACH (ReelWriter& i, _reels) {
492                 cpl->add (i.create_reel (_reel_assets, _fonts));
493         }
494
495         dcp::XMLMetadata meta;
496         meta.annotation_text = cpl->annotation_text ();
497         meta.creator = Config::instance()->dcp_creator ();
498         if (meta.creator.empty ()) {
499                 meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
500         }
501         meta.issuer = Config::instance()->dcp_issuer ();
502         if (meta.issuer.empty ()) {
503                 meta.issuer = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
504         }
505         meta.set_issue_date_now ();
506
507         cpl->set_metadata (meta);
508
509         shared_ptr<const dcp::CertificateChain> signer;
510         if (_film->is_signed ()) {
511                 signer = Config::instance()->signer_chain ();
512                 /* We did check earlier, but check again here to be on the safe side */
513                 string reason;
514                 if (!signer->valid (&reason)) {
515                         throw InvalidSignerError (reason);
516                 }
517         }
518
519         dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, signer, Config::instance()->dcp_metadata_filename_format());
520
521         LOG_GENERAL (
522                 N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT, %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk
523                 );
524 }
525
526 /** @param frame Frame index within the whole DCP.
527  *  @return true if we can fake-write this frame.
528  */
529 bool
530 Writer::can_fake_write (Frame frame) const
531 {
532         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
533            parameters in the asset writer.
534         */
535
536         ReelWriter const & reel = _reels[video_reel(frame)];
537
538         /* Make frame relative to the start of the reel */
539         frame -= reel.start ();
540         return (frame != 0 && frame < reel.first_nonexistant_frame());
541 }
542
543 void
544 Writer::write (PlayerSubtitles subs, DCPTimePeriod period)
545 {
546         if (subs.text.empty ()) {
547                 return;
548         }
549
550         if (_subtitle_reel->period().to <= period.from) {
551                 ++_subtitle_reel;
552         }
553
554         _subtitle_reel->write (subs);
555 }
556
557 void
558 Writer::write (list<shared_ptr<Font> > fonts)
559 {
560         /* Just keep a list of unique fonts and we'll deal with them in ::finish */
561
562         BOOST_FOREACH (shared_ptr<Font> i, fonts) {
563                 bool got = false;
564                 BOOST_FOREACH (shared_ptr<Font> j, _fonts) {
565                         if (*i == *j) {
566                                 got = true;
567                         }
568                 }
569
570                 if (!got) {
571                         _fonts.push_back (i);
572                 }
573         }
574 }
575
576 bool
577 operator< (QueueItem const & a, QueueItem const & b)
578 {
579         if (a.reel != b.reel) {
580                 return a.reel < b.reel;
581         }
582
583         if (a.frame != b.frame) {
584                 return a.frame < b.frame;
585         }
586
587         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
588 }
589
590 bool
591 operator== (QueueItem const & a, QueueItem const & b)
592 {
593         return a.reel == b.reel && a.frame == b.frame && a.eyes == b.eyes;
594 }
595
596 void
597 Writer::set_encoder_threads (int threads)
598 {
599         /* I think the scaling factor here should be the ratio of the longest frame
600            encode time to the shortest; if the thread count is T, longest time is L
601            and the shortest time S we could encode L/S frames per thread whilst waiting
602            for the L frame to encode so we might have to store LT/S frames.
603
604            However we don't want to use too much memory, so keep it a bit lower than we'd
605            perhaps like.  A J2K frame is typically about 1Mb so 3 here will mean we could
606            use about 240Mb with 72 encoding threads.
607         */
608         _maximum_frames_in_memory = lrint (threads * 3);
609 }
610
611 void
612 Writer::write (ReferencedReelAsset asset)
613 {
614         _reel_assets.push_back (asset);
615 }
616
617 size_t
618 Writer::video_reel (int frame) const
619 {
620         DCPTime t = DCPTime::from_frames (frame, _film->video_frame_rate ());
621         size_t i = 0;
622         while (i < _reels.size() && !_reels[i].period().contains (t)) {
623                 ++i;
624         }
625
626         DCPOMATIC_ASSERT (i < _reels.size ());
627         return i;
628 }
629
630 void
631 Writer::set_digest_progress (Job* job, float progress)
632 {
633         /* I believe this is thread-safe */
634         _digest_progresses[boost::this_thread::get_id()] = progress;
635
636         boost::mutex::scoped_lock lm (_digest_progresses_mutex);
637         float min_progress = FLT_MAX;
638         for (map<boost::thread::id, float>::const_iterator i = _digest_progresses.begin(); i != _digest_progresses.end(); ++i) {
639                 min_progress = min (min_progress, i->second);
640         }
641
642         job->set_progress (min_progress);
643 }