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