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