Merge master.
[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 <dcp/mono_picture_mxf.h>
23 #include <dcp/stereo_picture_mxf.h>
24 #include <dcp/sound_mxf.h>
25 #include <dcp/sound_mxf_writer.h>
26 #include <dcp/reel.h>
27 #include <dcp/reel_mono_picture_asset.h>
28 #include <dcp/reel_stereo_picture_asset.h>
29 #include <dcp/reel_sound_asset.h>
30 #include <dcp/dcp.h>
31 #include <dcp/cpl.h>
32 #include "writer.h"
33 #include "compose.hpp"
34 #include "film.h"
35 #include "ratio.h"
36 #include "log.h"
37 #include "dcp_video_frame.h"
38 #include "dcp_content_type.h"
39 #include "player.h"
40 #include "audio_mapping.h"
41 #include "config.h"
42 #include "job.h"
43 #include "cross.h"
44 #include "audio_buffers.h"
45
46 #include "i18n.h"
47
48 /* OS X strikes again */
49 #undef set_key
50
51 using std::make_pair;
52 using std::pair;
53 using std::string;
54 using std::list;
55 using std::cout;
56 using std::stringstream;
57 using boost::shared_ptr;
58 using boost::weak_ptr;
59 using boost::dynamic_pointer_cast;
60
61 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
62
63 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
64         : _film (f)
65         , _job (j)
66         , _first_nonexistant_frame (0)
67         , _thread (0)
68         , _finish (false)
69         , _queued_full_in_memory (0)
70         , _last_written_frame (-1)
71         , _last_written_eyes (EYES_RIGHT)
72         , _full_written (0)
73         , _fake_written (0)
74         , _repeat_written (0)
75         , _pushed_to_disk (0)
76 {
77         /* Remove any old DCP */
78         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
79
80         shared_ptr<Job> job = _job.lock ();
81         assert (job);
82
83         job->sub (_("Checking existing image data"));
84         check_existing_picture_mxf ();
85
86         /* Create our picture asset in a subdirectory, named according to those
87            film's parameters which affect the video output.  We will hard-link
88            it into the DCP later.
89         */
90
91         if (_film->three_d ()) {
92                 _picture_mxf.reset (new dcp::StereoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
93         } else {
94                 _picture_mxf.reset (new dcp::MonoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
95         }
96
97         _picture_mxf->set_size (_film->frame_size ());
98
99         if (_film->encrypted ()) {
100                 _picture_mxf->set_key (_film->key ());
101         }
102         
103         _picture_mxf_writer = _picture_mxf->start_write (
104                 _film->internal_video_mxf_dir() / _film->internal_video_mxf_filename(),
105                 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
106                 _first_nonexistant_frame > 0
107                 );
108
109         _sound_mxf.reset (new dcp::SoundMXF (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ()));
110
111         if (_film->encrypted ()) {
112                 _sound_mxf->set_key (_film->key ());
113         }
114         
115         /* Write the sound MXF into the film directory so that we leave the creation
116            of the DCP directory until the last minute.
117         */
118         _sound_mxf_writer = _sound_mxf->start_write (_film->directory() / _film->audio_mxf_filename(), _film->interop() ? dcp::INTEROP : dcp::SMPTE);
119
120         _thread = new boost::thread (boost::bind (&Writer::thread, this));
121
122         job->sub (_("Encoding image data"));
123 }
124
125 Writer::~Writer ()
126 {
127         terminate_thread (false);
128 }
129
130 void
131 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
132 {
133         boost::mutex::scoped_lock lock (_mutex);
134
135         while (_queued_full_in_memory > _maximum_frames_in_memory) {
136                 _full_condition.wait (lock);
137         }
138
139         QueueItem qi;
140         qi.type = QueueItem::FULL;
141         qi.encoded = encoded;
142         qi.frame = frame;
143
144         if (_film->three_d() && eyes == EYES_BOTH) {
145                 /* 2D material in a 3D DCP; fake the 3D */
146                 qi.eyes = EYES_LEFT;
147                 _queue.push_back (qi);
148                 ++_queued_full_in_memory;
149                 qi.eyes = EYES_RIGHT;
150                 _queue.push_back (qi);
151                 ++_queued_full_in_memory;
152         } else {
153                 qi.eyes = eyes;
154                 _queue.push_back (qi);
155                 ++_queued_full_in_memory;
156         }
157         
158         _empty_condition.notify_all ();
159 }
160
161 void
162 Writer::fake_write (int frame, Eyes eyes)
163 {
164         boost::mutex::scoped_lock lock (_mutex);
165
166         while (_queued_full_in_memory > _maximum_frames_in_memory) {
167                 _full_condition.wait (lock);
168         }
169         
170         FILE* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
171         dcp::FrameInfo info (ifi);
172         fclose (ifi);
173         
174         QueueItem qi;
175         qi.type = QueueItem::FAKE;
176         qi.size = info.size;
177         qi.frame = frame;
178         if (_film->three_d() && eyes == EYES_BOTH) {
179                 qi.eyes = EYES_LEFT;
180                 _queue.push_back (qi);
181                 qi.eyes = EYES_RIGHT;
182                 _queue.push_back (qi);
183         } else {
184                 qi.eyes = eyes;
185                 _queue.push_back (qi);
186         }
187
188         _empty_condition.notify_all ();
189 }
190
191 /** This method is not thread safe */
192 void
193 Writer::write (shared_ptr<const AudioBuffers> audio)
194 {
195         _sound_mxf_writer->write (audio->data(), audio->frames());
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                                 dcp::FrameInfo fin = _picture_mxf_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_mxf_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                                 dcp::FrameInfo fin = _picture_mxf_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                         shared_ptr<Job> job = _job.lock ();
299                         assert (job);
300                         int64_t total = _film->length().frames (_film->video_frame_rate ());
301                         if (_film->three_d ()) {
302                                 /* _full_written and so on are incremented for each eye, so we need to double the total
303                                    frames to get the correct progress.
304                                 */
305                                 total *= 2;
306                         }
307                         if (total) {
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_mxf_writer->finalize ();
384         _sound_mxf_writer->finalize ();
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         /* Move the audio MXF into the DCP */
404
405         boost::filesystem::path audio_to;
406         audio_to /= _film->dir (_film->dcp_name ());
407         audio_to /= _film->audio_mxf_filename ();
408         
409         boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
410         if (ec) {
411                 throw FileError (
412                         String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
413                         );
414         }
415
416         dcp::DCP dcp (_film->dir (_film->dcp_name()));
417
418         shared_ptr<dcp::CPL> cpl (
419                 new dcp::CPL (
420                         _film->dcp_name(),
421                         _film->dcp_content_type()->libdcp_kind ()
422                         )
423                 );
424         
425         dcp.add (cpl);
426
427         shared_ptr<dcp::Reel> reel (new dcp::Reel ());
428
429         shared_ptr<dcp::MonoPictureMXF> mono = dynamic_pointer_cast<dcp::MonoPictureMXF> (_picture_mxf);
430         if (mono) {
431                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
432         }
433
434         shared_ptr<dcp::StereoPictureMXF> stereo = dynamic_pointer_cast<dcp::StereoPictureMXF> (_picture_mxf);
435         if (stereo) {
436                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
437         }
438
439         reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_mxf, 0)));
440         
441         cpl->add (reel);
442
443         shared_ptr<Job> job = _job.lock ();
444         assert (job);
445
446         job->sub (_("Computing image digest"));
447         _picture_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
448
449         job->sub (_("Computing audio digest"));
450         _sound_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
451
452         dcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
453         meta.set_issue_date_now ();
454         dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, _film->is_signed() ? make_signer () : shared_ptr<const dcp::Signer> ());
455
456         _film->log()->log (
457                 String::compose (N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT; %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk)
458                 );
459 }
460
461 /** Tell the writer that frame `f' should be a repeat of the frame before it */
462 void
463 Writer::repeat (int f, Eyes e)
464 {
465         boost::mutex::scoped_lock lock (_mutex);
466
467         while (_queued_full_in_memory > _maximum_frames_in_memory) {
468                 _full_condition.wait (lock);
469         }
470         
471         QueueItem qi;
472         qi.type = QueueItem::REPEAT;
473         qi.frame = f;
474         if (_film->three_d() && e == EYES_BOTH) {
475                 qi.eyes = EYES_LEFT;
476                 _queue.push_back (qi);
477                 qi.eyes = EYES_RIGHT;
478                 _queue.push_back (qi);
479         } else {
480                 qi.eyes = e;
481                 _queue.push_back (qi);
482         }
483
484         _empty_condition.notify_all ();
485 }
486
487 bool
488 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
489 {
490         /* Read the frame info as written */
491         FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
492         if (!ifi) {
493                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
494                 return false;
495         }
496         
497         dcp::FrameInfo info (ifi);
498         fclose (ifi);
499         if (info.size == 0) {
500                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
501                 return false;
502         }
503         
504         /* Read the data from the MXF and hash it */
505         dcpomatic_fseek (mxf, info.offset, SEEK_SET);
506         EncodedData data (info.size);
507         size_t const read = fread (data.data(), 1, data.size(), mxf);
508         if (read != static_cast<size_t> (data.size ())) {
509                 _film->log()->log (String::compose ("Existing frame %1 is incomplete", f));
510                 return false;
511         }
512         
513         string const existing_hash = md5_digest (data.data(), data.size());
514         if (existing_hash != info.hash) {
515                 _film->log()->log (String::compose ("Existing frame %1 failed hash check", f));
516                 return false;
517         }
518
519         return true;
520 }
521
522 void
523 Writer::check_existing_picture_mxf ()
524 {
525         /* Try to open the existing MXF */
526         boost::filesystem::path p;
527         p /= _film->internal_video_mxf_dir ();
528         p /= _film->internal_video_mxf_filename ();
529         FILE* mxf = fopen_boost (p, "rb");
530         if (!mxf) {
531                 _film->log()->log (String::compose ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno));
532                 return;
533         }
534
535         int N = 0;
536         for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
537                 ++N;
538         }
539
540         while (1) {
541
542                 shared_ptr<Job> job = _job.lock ();
543                 assert (job);
544
545                 if (N > 0) {
546                         job->set_progress (float (_first_nonexistant_frame) / N);
547                 }
548
549                 if (_film->three_d ()) {
550                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
551                                 break;
552                         }
553                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
554                                 break;
555                         }
556                 } else {
557                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
558                                 break;
559                         }
560                 }
561
562                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
563                 ++_first_nonexistant_frame;
564         }
565
566         fclose (mxf);
567 }
568
569 /** @param frame Frame index.
570  *  @return true if we can fake-write this frame.
571  */
572 bool
573 Writer::can_fake_write (int frame) const
574 {
575         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
576            parameters in the MXF writer.
577         */
578         return (frame != 0 && frame < _first_nonexistant_frame);
579 }
580
581 bool
582 operator< (QueueItem const & a, QueueItem const & b)
583 {
584         if (a.frame != b.frame) {
585                 return a.frame < b.frame;
586         }
587
588         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
589 }
590
591 bool
592 operator== (QueueItem const & a, QueueItem const & b)
593 {
594         return a.frame == b.frame && a.eyes == b.eyes;
595 }