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