Don't overlap simultaneous video content in the timeline. Fix keep-aligned for separ...
[dcpomatic.git] / src / lib / writer.cc
1 /*
2     Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <fstream>
21 #include <cerrno>
22 #include <libdcp/mono_picture_asset.h>
23 #include <libdcp/stereo_picture_asset.h>
24 #include <libdcp/sound_asset.h>
25 #include <libdcp/reel.h>
26 #include <libdcp/dcp.h>
27 #include <libdcp/cpl.h>
28 #include "writer.h"
29 #include "compose.hpp"
30 #include "film.h"
31 #include "ratio.h"
32 #include "log.h"
33 #include "dcp_video_frame.h"
34 #include "dcp_content_type.h"
35 #include "player.h"
36 #include "audio_mapping.h"
37 #include "config.h"
38 #include "job.h"
39 #include "cross.h"
40
41 #include "i18n.h"
42
43 /* OS X strikes again */
44 #undef set_key
45
46 using std::make_pair;
47 using std::pair;
48 using std::string;
49 using std::list;
50 using std::cout;
51 using std::stringstream;
52 using boost::shared_ptr;
53 using boost::weak_ptr;
54
55 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
56
57 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
58         : _film (f)
59         , _job (j)
60         , _first_nonexistant_frame (0)
61         , _thread (0)
62         , _finish (false)
63         , _queued_full_in_memory (0)
64         , _last_written_frame (-1)
65         , _last_written_eyes (EYES_RIGHT)
66         , _full_written (0)
67         , _fake_written (0)
68         , _repeat_written (0)
69         , _pushed_to_disk (0)
70 {
71         /* Remove any old DCP */
72         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
73
74         shared_ptr<Job> job = _job.lock ();
75         assert (job);
76
77         job->sub (_("Checking existing image data"));
78         check_existing_picture_mxf ();
79
80         /* Create our picture asset in a subdirectory, named according to those
81            film's parameters which affect the video output.  We will hard-link
82            it into the DCP later.
83         */
84
85         if (_film->three_d ()) {
86                 _picture_asset.reset (new libdcp::StereoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
87         } else {
88                 _picture_asset.reset (new libdcp::MonoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
89         }
90
91         _picture_asset->set_edit_rate (_film->video_frame_rate ());
92         _picture_asset->set_size (_film->frame_size ());
93         _picture_asset->set_interop (_film->interop ());
94
95         if (_film->encrypted ()) {
96                 _picture_asset->set_key (_film->key ());
97         }
98         
99         _picture_asset_writer = _picture_asset->start_write (_first_nonexistant_frame > 0);
100
101         if (_film->audio_channels ()) {
102                 _sound_asset.reset (new libdcp::SoundAsset (_film->directory (), _film->audio_mxf_filename ()));
103                 _sound_asset->set_edit_rate (_film->video_frame_rate ());
104                 _sound_asset->set_channels (_film->audio_channels ());
105                 _sound_asset->set_sampling_rate (_film->audio_frame_rate ());
106                 _sound_asset->set_interop (_film->interop ());
107
108                 if (_film->encrypted ()) {
109                         _sound_asset->set_key (_film->key ());
110                 }
111                 
112                 /* Write the sound asset into the film directory so that we leave the creation
113                    of the DCP directory until the last minute.
114                 */
115                 _sound_asset_writer = _sound_asset->start_write ();
116         }
117
118         _thread = new boost::thread (boost::bind (&Writer::thread, this));
119
120         job->sub (_("Encoding image data"));
121 }
122
123 Writer::~Writer ()
124 {
125         terminate_thread (false);
126 }
127
128 void
129 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
130 {
131         boost::mutex::scoped_lock lock (_mutex);
132
133         while (_queued_full_in_memory > _maximum_frames_in_memory) {
134                 _full_condition.wait (lock);
135         }
136
137         QueueItem qi;
138         qi.type = QueueItem::FULL;
139         qi.encoded = encoded;
140         qi.frame = frame;
141
142         if (_film->three_d() && eyes == EYES_BOTH) {
143                 /* 2D material in a 3D DCP; fake the 3D */
144                 qi.eyes = EYES_LEFT;
145                 _queue.push_back (qi);
146                 ++_queued_full_in_memory;
147                 qi.eyes = EYES_RIGHT;
148                 _queue.push_back (qi);
149                 ++_queued_full_in_memory;
150         } else {
151                 qi.eyes = eyes;
152                 _queue.push_back (qi);
153                 ++_queued_full_in_memory;
154         }
155         
156         _empty_condition.notify_all ();
157 }
158
159 void
160 Writer::fake_write (int frame, Eyes eyes)
161 {
162         boost::mutex::scoped_lock lock (_mutex);
163
164         while (_queued_full_in_memory > _maximum_frames_in_memory) {
165                 _full_condition.wait (lock);
166         }
167         
168         FILE* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
169         libdcp::FrameInfo info (ifi);
170         fclose (ifi);
171         
172         QueueItem qi;
173         qi.type = QueueItem::FAKE;
174         qi.size = info.size;
175         qi.frame = frame;
176         if (_film->three_d() && eyes == EYES_BOTH) {
177                 qi.eyes = EYES_LEFT;
178                 _queue.push_back (qi);
179                 qi.eyes = EYES_RIGHT;
180                 _queue.push_back (qi);
181         } else {
182                 qi.eyes = eyes;
183                 _queue.push_back (qi);
184         }
185
186         _empty_condition.notify_all ();
187 }
188
189 /** This method is not thread safe */
190 void
191 Writer::write (shared_ptr<const AudioBuffers> audio)
192 {
193         if (_sound_asset) {
194                 _sound_asset_writer->write (audio->data(), audio->frames());
195         }
196 }
197
198 /** This must be called from Writer::thread() with an appropriate lock held */
199 bool
200 Writer::have_sequenced_image_at_queue_head ()
201 {
202         if (_queue.empty ()) {
203                 return false;
204         }
205
206         _queue.sort ();
207
208         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
209
210         if (_queue.front().eyes == EYES_BOTH) {
211                 /* 2D */
212                 return _queue.front().frame == (_last_written_frame + 1);
213         }
214
215         /* 3D */
216
217         if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
218                 return true;
219         }
220
221         if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
222                 return true;
223         }
224
225         return false;
226 }
227
228 void
229 Writer::thread ()
230 try
231 {
232         while (1)
233         {
234                 boost::mutex::scoped_lock lock (_mutex);
235
236                 while (1) {
237                         
238                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
239                                 break;
240                         }
241
242                         TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
243                         _empty_condition.wait (lock);
244                         TIMING (N_("writer wakes with a queue of %1"), _queue.size());
245                 }
246
247                 if (_finish && _queue.empty()) {
248                         return;
249                 }
250
251                 /* Write any frames that we can write; i.e. those that are in sequence. */
252                 while (have_sequenced_image_at_queue_head ()) {
253                         QueueItem qi = _queue.front ();
254                         _queue.pop_front ();
255                         if (qi.type == QueueItem::FULL && qi.encoded) {
256                                 --_queued_full_in_memory;
257                         }
258
259                         lock.unlock ();
260                         switch (qi.type) {
261                         case QueueItem::FULL:
262                         {
263                                 _film->log()->log (String::compose (N_("Writer FULL-writes %1 to MXF"), qi.frame));
264                                 if (!qi.encoded) {
265                                         qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
266                                 }
267
268                                 libdcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size());
269                                 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
270                                 _last_written[qi.eyes] = qi.encoded;
271                                 ++_full_written;
272                                 break;
273                         }
274                         case QueueItem::FAKE:
275                                 _film->log()->log (String::compose (N_("Writer FAKE-writes %1 to MXF"), qi.frame));
276                                 _picture_asset_writer->fake_write (qi.size);
277                                 _last_written[qi.eyes].reset ();
278                                 ++_fake_written;
279                                 break;
280                         case QueueItem::REPEAT:
281                         {
282                                 _film->log()->log (String::compose (N_("Writer REPEAT-writes %1 to MXF"), qi.frame));
283                                 libdcp::FrameInfo fin = _picture_asset_writer->write (
284                                         _last_written[qi.eyes]->data(),
285                                         _last_written[qi.eyes]->size()
286                                         );
287                                 
288                                 _last_written[qi.eyes]->write_info (_film, qi.frame, qi.eyes, fin);
289                                 ++_repeat_written;
290                                 break;
291                         }
292                         }
293                         lock.lock ();
294
295                         _last_written_frame = qi.frame;
296                         _last_written_eyes = qi.eyes;
297                         
298                         if (_film->length()) {
299                                 shared_ptr<Job> job = _job.lock ();
300                                 assert (job);
301                                 int total = _film->time_to_video_frames (_film->length ());
302                                 if (_film->three_d ()) {
303                                         /* _full_written and so on are incremented for each eye, so we need to double the total
304                                            frames to get the correct progress.
305                                         */
306                                         total *= 2;
307                                 }
308                                 job->set_progress (float (_full_written + _fake_written + _repeat_written) / total);
309                         }
310                 }
311
312                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
313                         /* Too many frames in memory which can't yet be written to the stream.
314                            Write some FULL frames to disk.
315                         */
316
317                         /* Find one from the back of the queue */
318                         _queue.sort ();
319                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
320                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
321                                 ++i;
322                         }
323
324                         assert (i != _queue.rend());
325                         QueueItem qi = *i;
326
327                         ++_pushed_to_disk;
328                         
329                         lock.unlock ();
330
331                         _film->log()->log (
332                                 String::compose (
333                                         "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
334                                         _last_written_frame + 1,
335                                         _last_written_eyes, qi.frame)
336                                 );
337                         
338                         qi.encoded->write (_film, qi.frame, qi.eyes);
339                         lock.lock ();
340                         qi.encoded.reset ();
341                         --_queued_full_in_memory;
342                 }
343
344                 _full_condition.notify_all ();
345         }
346 }
347 catch (...)
348 {
349         store_current ();
350 }
351
352 void
353 Writer::terminate_thread (bool can_throw)
354 {
355         boost::mutex::scoped_lock lock (_mutex);
356         if (_thread == 0) {
357                 return;
358         }
359         
360         _finish = true;
361         _empty_condition.notify_all ();
362         _full_condition.notify_all ();
363         lock.unlock ();
364
365         _thread->join ();
366         if (can_throw) {
367                 rethrow ();
368         }
369         
370         delete _thread;
371         _thread = 0;
372 }       
373
374 void
375 Writer::finish ()
376 {
377         if (!_thread) {
378                 return;
379         }
380         
381         terminate_thread (true);
382
383         _picture_asset_writer->finalize ();
384         if (_sound_asset_writer) {
385                 _sound_asset_writer->finalize ();
386         }
387         
388         int const frames = _last_written_frame + 1;
389
390         _picture_asset->set_duration (frames);
391
392         /* Hard-link the video MXF into the DCP */
393         boost::filesystem::path video_from;
394         video_from /= _film->internal_video_mxf_dir();
395         video_from /= _film->internal_video_mxf_filename();
396         
397         boost::filesystem::path video_to;
398         video_to /= _film->dir (_film->dcp_name());
399         video_to /= _film->video_mxf_filename ();
400
401         boost::system::error_code ec;
402         boost::filesystem::create_hard_link (video_from, video_to, ec);
403         if (ec) {
404                 /* hard link failed; copy instead */
405                 boost::filesystem::copy_file (video_from, video_to);
406                 _film->log()->log ("Hard-link failed; fell back to copying");
407         }
408
409         /* And update the asset */
410
411         _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
412         _picture_asset->set_file_name (_film->video_mxf_filename ());
413
414         /* Move the audio MXF into the DCP */
415
416         if (_sound_asset) {
417                 boost::filesystem::path audio_to;
418                 audio_to /= _film->dir (_film->dcp_name ());
419                 audio_to /= _film->audio_mxf_filename ();
420                 
421                 boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
422                 if (ec) {
423                         throw FileError (
424                                 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
425                                 );
426                 }
427                 
428                 _sound_asset->set_directory (_film->dir (_film->dcp_name ()));
429                 _sound_asset->set_duration (frames);
430         }
431         
432         libdcp::DCP dcp (_film->dir (_film->dcp_name()));
433
434         shared_ptr<libdcp::CPL> cpl (
435                 new libdcp::CPL (
436                         _film->dir (_film->dcp_name()),
437                         _film->dcp_name(),
438                         _film->dcp_content_type()->libdcp_kind (),
439                         frames,
440                         _film->video_frame_rate ()
441                         )
442                 );
443         
444         dcp.add_cpl (cpl);
445
446         cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
447                                                          _picture_asset,
448                                                          _sound_asset,
449                                                          shared_ptr<libdcp::SubtitleAsset> ()
450                                                          )
451                                ));
452
453         shared_ptr<Job> job = _job.lock ();
454         assert (job);
455
456         job->sub (_("Computing image digest"));
457         _picture_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
458
459         if (_sound_asset) {
460                 job->sub (_("Computing audio digest"));
461                 _sound_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
462         }
463
464         libdcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
465         meta.set_issue_date_now ();
466         dcp.write_xml (_film->interop (), meta, _film->is_signed() ? make_signer () : shared_ptr<const libdcp::Signer> ());
467
468         _film->log()->log (
469                 String::compose (N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT; %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk)
470                 );
471 }
472
473 /** Tell the writer that frame `f' should be a repeat of the frame before it */
474 void
475 Writer::repeat (int f, Eyes e)
476 {
477         boost::mutex::scoped_lock lock (_mutex);
478
479         while (_queued_full_in_memory > _maximum_frames_in_memory) {
480                 _full_condition.wait (lock);
481         }
482         
483         QueueItem qi;
484         qi.type = QueueItem::REPEAT;
485         qi.frame = f;
486         if (_film->three_d() && e == EYES_BOTH) {
487                 qi.eyes = EYES_LEFT;
488                 _queue.push_back (qi);
489                 qi.eyes = EYES_RIGHT;
490                 _queue.push_back (qi);
491         } else {
492                 qi.eyes = e;
493                 _queue.push_back (qi);
494         }
495
496         _empty_condition.notify_all ();
497 }
498
499 bool
500 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
501 {
502         /* Read the frame info as written */
503         FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
504         if (!ifi) {
505                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
506                 return false;
507         }
508         
509         libdcp::FrameInfo info (ifi);
510         fclose (ifi);
511         if (info.size == 0) {
512                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
513                 return false;
514         }
515         
516         /* Read the data from the MXF and hash it */
517         dcpomatic_fseek (mxf, info.offset, SEEK_SET);
518         EncodedData data (info.size);
519         size_t const read = fread (data.data(), 1, data.size(), mxf);
520         if (read != static_cast<size_t> (data.size ())) {
521                 _film->log()->log (String::compose ("Existing frame %1 is incomplete", f));
522                 return false;
523         }
524         
525         string const existing_hash = md5_digest (data.data(), data.size());
526         if (existing_hash != info.hash) {
527                 _film->log()->log (String::compose ("Existing frame %1 failed hash check", f));
528                 return false;
529         }
530
531         return true;
532 }
533
534 void
535 Writer::check_existing_picture_mxf ()
536 {
537         /* Try to open the existing MXF */
538         boost::filesystem::path p;
539         p /= _film->internal_video_mxf_dir ();
540         p /= _film->internal_video_mxf_filename ();
541         FILE* mxf = fopen_boost (p, "rb");
542         if (!mxf) {
543                 _film->log()->log (String::compose ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno));
544                 return;
545         }
546
547         int N = 0;
548         for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
549                 ++N;
550         }
551
552         while (1) {
553
554                 shared_ptr<Job> job = _job.lock ();
555                 assert (job);
556
557                 if (N > 0) {
558                         job->set_progress (float (_first_nonexistant_frame) / N);
559                 }
560
561                 if (_film->three_d ()) {
562                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
563                                 break;
564                         }
565                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
566                                 break;
567                         }
568                 } else {
569                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
570                                 break;
571                         }
572                 }
573
574                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
575                 ++_first_nonexistant_frame;
576         }
577
578         fclose (mxf);
579 }
580
581 /** @param frame Frame index.
582  *  @return true if we can fake-write this frame.
583  */
584 bool
585 Writer::can_fake_write (int frame) const
586 {
587         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
588            parameters in the MXF writer.
589         */
590         return (frame != 0 && frame < _first_nonexistant_frame);
591 }
592
593 bool
594 operator< (QueueItem const & a, QueueItem const & b)
595 {
596         if (a.frame != b.frame) {
597                 return a.frame < b.frame;
598         }
599
600         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
601 }
602
603 bool
604 operator== (QueueItem const & a, QueueItem const & b)
605 {
606         return a.frame == b.frame && a.eyes == b.eyes;
607 }