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