Merge master.
[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 <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 #include "md5_digester.h"
46
47 #include "i18n.h"
48
49 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
50 #define LOG_TIMING(...) _film->log()->microsecond_log (String::compose (__VA_ARGS__), Log::TYPE_TIMING);
51 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_WARNING);
52
53 /* OS X strikes again */
54 #undef set_key
55
56 using std::make_pair;
57 using std::pair;
58 using std::string;
59 using std::list;
60 using std::cout;
61 using std::stringstream;
62 using boost::shared_ptr;
63 using boost::weak_ptr;
64 using boost::dynamic_pointer_cast;
65
66 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
67
68 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
69         : _film (f)
70         , _job (j)
71         , _first_nonexistant_frame (0)
72         , _thread (0)
73         , _finish (false)
74         , _queued_full_in_memory (0)
75         , _last_written_frame (-1)
76         , _last_written_eyes (EYES_RIGHT)
77         , _full_written (0)
78         , _fake_written (0)
79         , _pushed_to_disk (0)
80 {
81         /* Remove any old DCP */
82         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
83
84         shared_ptr<Job> job = _job.lock ();
85         assert (job);
86
87         job->sub (_("Checking existing image data"));
88         check_existing_picture_mxf ();
89
90         /* Create our picture asset in a subdirectory, named according to those
91            film's parameters which affect the video output.  We will hard-link
92            it into the DCP later.
93         */
94
95         if (_film->three_d ()) {
96                 _picture_mxf.reset (new dcp::StereoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
97         } else {
98                 _picture_mxf.reset (new dcp::MonoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
99         }
100
101         _picture_mxf->set_size (_film->frame_size ());
102
103         if (_film->encrypted ()) {
104                 _picture_mxf->set_key (_film->key ());
105         }
106         
107         _picture_mxf_writer = _picture_mxf->start_write (
108                 _film->internal_video_mxf_dir() / _film->internal_video_mxf_filename(),
109                 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
110                 _first_nonexistant_frame > 0
111                 );
112
113         if (_film->audio_channels ()) {
114                 _sound_mxf.reset (new dcp::SoundMXF (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ()));
115
116                 if (_film->encrypted ()) {
117                         _sound_mxf->set_key (_film->key ());
118                 }
119         
120                 /* Write the sound MXF into the film directory so that we leave the creation
121                    of the DCP directory until the last minute.
122                 */
123                 _sound_mxf_writer = _sound_mxf->start_write (_film->directory() / _film->audio_mxf_filename(), _film->interop() ? dcp::INTEROP : dcp::SMPTE);
124         }
125
126         _thread = new boost::thread (boost::bind (&Writer::thread, this));
127
128         job->sub (_("Encoding image data"));
129 }
130
131 Writer::~Writer ()
132 {
133         terminate_thread (false);
134 }
135
136 void
137 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
138 {
139         boost::mutex::scoped_lock lock (_mutex);
140
141         while (_queued_full_in_memory > _maximum_frames_in_memory) {
142                 _full_condition.wait (lock);
143         }
144
145         QueueItem qi;
146         qi.type = QueueItem::FULL;
147         qi.encoded = encoded;
148         qi.frame = frame;
149
150         if (_film->three_d() && eyes == EYES_BOTH) {
151                 /* 2D material in a 3D DCP; fake the 3D */
152                 qi.eyes = EYES_LEFT;
153                 _queue.push_back (qi);
154                 ++_queued_full_in_memory;
155                 qi.eyes = EYES_RIGHT;
156                 _queue.push_back (qi);
157                 ++_queued_full_in_memory;
158         } else {
159                 qi.eyes = eyes;
160                 _queue.push_back (qi);
161                 ++_queued_full_in_memory;
162         }
163         
164         _empty_condition.notify_all ();
165 }
166
167 void
168 Writer::fake_write (int frame, Eyes eyes)
169 {
170         boost::mutex::scoped_lock lock (_mutex);
171
172         while (_queued_full_in_memory > _maximum_frames_in_memory) {
173                 _full_condition.wait (lock);
174         }
175         
176         FILE* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
177         dcp::FrameInfo info (ifi);
178         fclose (ifi);
179         
180         QueueItem qi;
181         qi.type = QueueItem::FAKE;
182         qi.size = info.size;
183         qi.frame = frame;
184         if (_film->three_d() && eyes == EYES_BOTH) {
185                 qi.eyes = EYES_LEFT;
186                 _queue.push_back (qi);
187                 qi.eyes = EYES_RIGHT;
188                 _queue.push_back (qi);
189         } else {
190                 qi.eyes = eyes;
191                 _queue.push_back (qi);
192         }
193
194         _empty_condition.notify_all ();
195 }
196
197 /** This method is not thread safe */
198 void
199 Writer::write (shared_ptr<const AudioBuffers> audio)
200 {
201         if (_sound_mxf_writer) {
202                 _sound_mxf_writer->write (audio->data(), audio->frames());
203         }
204 }
205
206 /** This must be called from Writer::thread() with an appropriate lock held */
207 bool
208 Writer::have_sequenced_image_at_queue_head ()
209 {
210         if (_queue.empty ()) {
211                 return false;
212         }
213
214         _queue.sort ();
215
216         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
217
218         if (_queue.front().eyes == EYES_BOTH) {
219                 /* 2D */
220                 return _queue.front().frame == (_last_written_frame + 1);
221         }
222
223         /* 3D */
224
225         if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
226                 return true;
227         }
228
229         if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
230                 return true;
231         }
232
233         return false;
234 }
235
236 void
237 Writer::thread ()
238 try
239 {
240         while (1)
241         {
242                 boost::mutex::scoped_lock lock (_mutex);
243
244                 while (1) {
245                         
246                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
247                                 break;
248                         }
249
250                         LOG_TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
251                         _empty_condition.wait (lock);
252                         LOG_TIMING (N_("writer wakes with a queue of %1"), _queue.size());
253                 }
254
255                 if (_finish && _queue.empty()) {
256                         return;
257                 }
258
259                 /* Write any frames that we can write; i.e. those that are in sequence. */
260                 while (have_sequenced_image_at_queue_head ()) {
261                         QueueItem qi = _queue.front ();
262                         _queue.pop_front ();
263                         if (qi.type == QueueItem::FULL && qi.encoded) {
264                                 --_queued_full_in_memory;
265                         }
266
267                         lock.unlock ();
268                         switch (qi.type) {
269                         case QueueItem::FULL:
270                         {
271                                 LOG_GENERAL (N_("Writer FULL-writes %1 to MXF"), qi.frame);
272                                 if (!qi.encoded) {
273                                         qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
274                                 }
275
276                                 dcp::FrameInfo fin = _picture_mxf_writer->write (qi.encoded->data(), qi.encoded->size());
277                                 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
278                                 _last_written[qi.eyes] = qi.encoded;
279                                 ++_full_written;
280                                 break;
281                         }
282                         case QueueItem::FAKE:
283                                 LOG_GENERAL (N_("Writer FAKE-writes %1 to MXF"), qi.frame);
284                                 _picture_mxf_writer->fake_write (qi.size);
285                                 _last_written[qi.eyes].reset ();
286                                 ++_fake_written;
287                                 break;
288                         }
289                         lock.lock ();
290
291                         _last_written_frame = qi.frame;
292                         _last_written_eyes = qi.eyes;
293                         
294                         shared_ptr<Job> job = _job.lock ();
295                         assert (job);
296                         int64_t total = _film->length().frames (_film->video_frame_rate ());
297                         if (_film->three_d ()) {
298                                 /* _full_written and so on are incremented for each eye, so we need to double the total
299                                    frames to get the correct progress.
300                                 */
301                                 total *= 2;
302                         }
303                         if (total) {
304                                 job->set_progress (float (_full_written + _fake_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                         LOG_GENERAL (
328                                 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
329                                 _last_written_frame + 1,
330                                 _last_written_eyes, qi.frame
331                                 );
332                         
333                         qi.encoded->write (_film, qi.frame, qi.eyes);
334                         lock.lock ();
335                         qi.encoded.reset ();
336                         --_queued_full_in_memory;
337                 }
338
339                 _full_condition.notify_all ();
340         }
341 }
342 catch (...)
343 {
344         store_current ();
345 }
346
347 void
348 Writer::terminate_thread (bool can_throw)
349 {
350         boost::mutex::scoped_lock lock (_mutex);
351         if (_thread == 0) {
352                 return;
353         }
354         
355         _finish = true;
356         _empty_condition.notify_all ();
357         _full_condition.notify_all ();
358         lock.unlock ();
359
360         _thread->join ();
361         if (can_throw) {
362                 rethrow ();
363         }
364         
365         delete _thread;
366         _thread = 0;
367 }       
368
369 void
370 Writer::finish ()
371 {
372         if (!_thread) {
373                 return;
374         }
375         
376         terminate_thread (true);
377
378         _picture_mxf_writer->finalize ();
379         if (_sound_mxf_writer) {
380                 _sound_mxf_writer->finalize ();
381         }
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                 LOG_WARNING_NC ("Hard-link failed; fell back to copying");
398         }
399
400         _picture_mxf->set_file (video_to);
401
402         /* Move the audio MXF into the DCP */
403
404         if (_sound_mxf) {
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                 _sound_mxf->set_file (audio_to);
417         }
418
419         dcp::DCP dcp (_film->dir (_film->dcp_name()));
420
421         shared_ptr<dcp::CPL> cpl (
422                 new dcp::CPL (
423                         _film->dcp_name(),
424                         _film->dcp_content_type()->libdcp_kind ()
425                         )
426                 );
427         
428         dcp.add (cpl);
429
430         shared_ptr<dcp::Reel> reel (new dcp::Reel ());
431
432         shared_ptr<dcp::MonoPictureMXF> mono = dynamic_pointer_cast<dcp::MonoPictureMXF> (_picture_mxf);
433         if (mono) {
434                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
435                 dcp.add (mono);
436         }
437
438         shared_ptr<dcp::StereoPictureMXF> stereo = dynamic_pointer_cast<dcp::StereoPictureMXF> (_picture_mxf);
439         if (stereo) {
440                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
441                 dcp.add (stereo);
442         }
443
444         if (_sound_mxf) {
445                 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_mxf, 0)));
446                 dcp.add (_sound_mxf);
447         }
448         
449         cpl->add (reel);
450
451         shared_ptr<Job> job = _job.lock ();
452         assert (job);
453
454         job->sub (_("Computing image digest"));
455         _picture_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
456
457         if (_sound_mxf) {
458                 job->sub (_("Computing audio digest"));
459                 _sound_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
460         }
461
462         dcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
463         meta.set_issue_date_now ();
464
465         dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, _film->is_signed() ? make_signer () : shared_ptr<const dcp::Signer> ());
466
467         LOG_GENERAL (
468                 N_("Wrote %1 FULL, %2 FAKE, %3 pushed to disk"), _full_written, _fake_written, _pushed_to_disk
469                 );
470 }
471
472 bool
473 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
474 {
475         /* Read the frame info as written */
476         FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
477         if (!ifi) {
478                 LOG_GENERAL ("Existing frame %1 has no info file", f);
479                 return false;
480         }
481         
482         dcp::FrameInfo info (ifi);
483         fclose (ifi);
484         if (info.size == 0) {
485                 LOG_GENERAL ("Existing frame %1 has no info file", f);
486                 return false;
487         }
488         
489         /* Read the data from the MXF and hash it */
490         dcpomatic_fseek (mxf, info.offset, SEEK_SET);
491         EncodedData data (info.size);
492         size_t const read = fread (data.data(), 1, data.size(), mxf);
493         if (read != static_cast<size_t> (data.size ())) {
494                 LOG_GENERAL ("Existing frame %1 is incomplete", f);
495                 return false;
496         }
497
498         MD5Digester digester;
499         digester.add (data.data(), data.size());
500         if (digester.get() != info.hash) {
501                 LOG_GENERAL ("Existing frame %1 failed hash check", f);
502                 return false;
503         }
504
505         return true;
506 }
507
508 void
509 Writer::check_existing_picture_mxf ()
510 {
511         /* Try to open the existing MXF */
512         boost::filesystem::path p;
513         p /= _film->internal_video_mxf_dir ();
514         p /= _film->internal_video_mxf_filename ();
515         FILE* mxf = fopen_boost (p, "rb");
516         if (!mxf) {
517                 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno);
518                 return;
519         }
520
521         int N = 0;
522         for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
523                 ++N;
524         }
525
526         while (1) {
527
528                 shared_ptr<Job> job = _job.lock ();
529                 assert (job);
530
531                 if (N > 0) {
532                         job->set_progress (float (_first_nonexistant_frame) / N);
533                 }
534
535                 if (_film->three_d ()) {
536                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
537                                 break;
538                         }
539                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
540                                 break;
541                         }
542                 } else {
543                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
544                                 break;
545                         }
546                 }
547
548                 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
549                 ++_first_nonexistant_frame;
550         }
551
552         fclose (mxf);
553 }
554
555 /** @param frame Frame index.
556  *  @return true if we can fake-write this frame.
557  */
558 bool
559 Writer::can_fake_write (int frame) const
560 {
561         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
562            parameters in the MXF writer.
563         */
564         return (frame != 0 && frame < _first_nonexistant_frame);
565 }
566
567 bool
568 operator< (QueueItem const & a, QueueItem const & b)
569 {
570         if (a.frame != b.frame) {
571                 return a.frame < b.frame;
572         }
573
574         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
575 }
576
577 bool
578 operator== (QueueItem const & a, QueueItem const & b)
579 {
580         return a.frame == b.frame && a.eyes == b.eyes;
581 }