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