It builds again.
[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_mxf.h>
23 #include <libdcp/stereo_picture_mxf.h>
24 #include <libdcp/sound_mxf.h>
25 #include <libdcp/sound_mxf_writer.h>
26 #include <libdcp/reel.h>
27 #include <libdcp/reel_mono_picture_asset.h>
28 #include <libdcp/reel_stereo_picture_asset.h>
29 #include <libdcp/reel_sound_asset.h>
30 #include <libdcp/dcp.h>
31 #include <libdcp/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
45 #include "i18n.h"
46
47 using std::make_pair;
48 using std::pair;
49 using std::string;
50 using std::list;
51 using std::cout;
52 using std::stringstream;
53 using boost::shared_ptr;
54 using boost::weak_ptr;
55 using boost::dynamic_pointer_cast;
56
57 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
58
59 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
60         : _film (f)
61         , _job (j)
62         , _first_nonexistant_frame (0)
63         , _thread (0)
64         , _finish (false)
65         , _queued_full_in_memory (0)
66         , _last_written_frame (-1)
67         , _last_written_eyes (EYES_RIGHT)
68         , _full_written (0)
69         , _fake_written (0)
70         , _repeat_written (0)
71         , _pushed_to_disk (0)
72 {
73         /* Remove any old DCP */
74         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
75
76         shared_ptr<Job> job = _job.lock ();
77         assert (job);
78
79         job->sub (_("Checking existing image data"));
80         check_existing_picture_mxf ();
81
82         /* Create our picture asset in a subdirectory, named according to those
83            film's parameters which affect the video output.  We will hard-link
84            it into the DCP later.
85         */
86
87         if (_film->three_d ()) {
88                 _picture_mxf.reset (new dcp::StereoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
89         } else {
90                 _picture_mxf.reset (new dcp::MonoPictureMXF (dcp::Fraction (_film->video_frame_rate (), 1)));
91         }
92
93         _picture_mxf->set_size (fit_ratio_within (_film->container()->ratio(), _film->full_frame ()));
94
95         if (_film->encrypted ()) {
96                 _picture_mxf->set_key (_film->key ());
97         }
98         
99         _picture_mxf_writer = _picture_mxf->start_write (
100                 _film->internal_video_mxf_dir() / _film->internal_video_mxf_filename(),
101                 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
102                 _first_nonexistant_frame > 0
103                 );
104
105         _sound_mxf.reset (new dcp::SoundMXF (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ()));
106
107         if (_film->encrypted ()) {
108                 _sound_mxf->set_key (_film->key ());
109         }
110         
111         /* Write the sound MXF into the film directory so that we leave the creation
112            of the DCP directory until the last minute.
113         */
114         _sound_mxf_writer = _sound_mxf->start_write (_film->directory() / _film->audio_mxf_filename(), _film->interop() ? dcp::INTEROP : dcp::SMPTE);
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         dcp::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_mxf_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                                 dcp::FrameInfo fin = _picture_mxf_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_mxf_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                                 dcp::FrameInfo fin = _picture_mxf_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_mxf_writer->finalize ();
380         _sound_mxf_writer->finalize ();
381         
382         /* Hard-link the video MXF into the DCP */
383         boost::filesystem::path video_from;
384         video_from /= _film->internal_video_mxf_dir();
385         video_from /= _film->internal_video_mxf_filename();
386         
387         boost::filesystem::path video_to;
388         video_to /= _film->dir (_film->dcp_name());
389         video_to /= _film->video_mxf_filename ();
390
391         boost::system::error_code ec;
392         boost::filesystem::create_hard_link (video_from, video_to, ec);
393         if (ec) {
394                 /* hard link failed; copy instead */
395                 boost::filesystem::copy_file (video_from, video_to);
396                 _film->log()->log ("Hard-link failed; fell back to copying");
397         }
398
399         /* Move the audio MXF into the DCP */
400
401         boost::filesystem::path audio_to;
402         audio_to /= _film->dir (_film->dcp_name ());
403         audio_to /= _film->audio_mxf_filename ();
404         
405         boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
406         if (ec) {
407                 throw FileError (
408                         String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
409                         );
410         }
411
412         dcp::DCP dcp (_film->dir (_film->dcp_name()));
413
414         shared_ptr<dcp::CPL> cpl (
415                 new dcp::CPL (
416                         _film->dcp_name(),
417                         _film->dcp_content_type()->libdcp_kind ()
418                         )
419                 );
420         
421         dcp.add (cpl);
422
423         shared_ptr<dcp::Reel> reel (new dcp::Reel ());
424
425         shared_ptr<dcp::MonoPictureMXF> mono = dynamic_pointer_cast<dcp::MonoPictureMXF> (_picture_mxf);
426         if (mono) {
427                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelMonoPictureAsset (mono, 0)));
428         }
429
430         shared_ptr<dcp::StereoPictureMXF> stereo = dynamic_pointer_cast<dcp::StereoPictureMXF> (_picture_mxf);
431         if (stereo) {
432                 reel->add (shared_ptr<dcp::ReelPictureAsset> (new dcp::ReelStereoPictureAsset (stereo, 0)));
433         }
434
435         reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_mxf, 0)));
436         
437         cpl->add (reel);
438
439         shared_ptr<Job> job = _job.lock ();
440         assert (job);
441
442         job->sub (_("Computing image digest"));
443         _picture_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
444
445         job->sub (_("Computing audio digest"));
446         _sound_mxf->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
447
448         dcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
449         meta.set_issue_date_now ();
450         dcp.write_xml (_film->interop () ? dcp::INTEROP : dcp::SMPTE, meta, _film->is_signed() ? make_signer () : shared_ptr<const dcp::Signer> ());
451
452         _film->log()->log (
453                 String::compose (N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT; %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk)
454                 );
455 }
456
457 /** Tell the writer that frame `f' should be a repeat of the frame before it */
458 void
459 Writer::repeat (int f, Eyes e)
460 {
461         boost::mutex::scoped_lock lock (_mutex);
462
463         while (_queued_full_in_memory > _maximum_frames_in_memory) {
464                 _full_condition.wait (lock);
465         }
466         
467         QueueItem qi;
468         qi.type = QueueItem::REPEAT;
469         qi.frame = f;
470         if (_film->three_d() && e == EYES_BOTH) {
471                 qi.eyes = EYES_LEFT;
472                 _queue.push_back (qi);
473                 qi.eyes = EYES_RIGHT;
474                 _queue.push_back (qi);
475         } else {
476                 qi.eyes = e;
477                 _queue.push_back (qi);
478         }
479
480         _empty_condition.notify_all ();
481 }
482
483 bool
484 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
485 {
486         /* Read the frame info as written */
487         FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
488         if (!ifi) {
489                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
490                 return false;
491         }
492         
493         dcp::FrameInfo info (ifi);
494         fclose (ifi);
495         if (info.size == 0) {
496                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
497                 return false;
498         }
499         
500         /* Read the data from the MXF and hash it */
501         dcpomatic_fseek (mxf, info.offset, SEEK_SET);
502         EncodedData data (info.size);
503         size_t const read = fread (data.data(), 1, data.size(), mxf);
504         if (read != static_cast<size_t> (data.size ())) {
505                 _film->log()->log (String::compose ("Existing frame %1 is incomplete", f));
506                 return false;
507         }
508         
509         string const existing_hash = md5_digest (data.data(), data.size());
510         if (existing_hash != info.hash) {
511                 _film->log()->log (String::compose ("Existing frame %1 failed hash check", f));
512                 return false;
513         }
514
515         return true;
516 }
517
518 void
519 Writer::check_existing_picture_mxf ()
520 {
521         /* Try to open the existing MXF */
522         boost::filesystem::path p;
523         p /= _film->internal_video_mxf_dir ();
524         p /= _film->internal_video_mxf_filename ();
525         FILE* mxf = fopen_boost (p, "rb");
526         if (!mxf) {
527                 _film->log()->log (String::compose ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno));
528                 return;
529         }
530
531         int N = 0;
532         for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
533                 ++N;
534         }
535
536         while (1) {
537
538                 shared_ptr<Job> job = _job.lock ();
539                 assert (job);
540
541                 if (N > 0) {
542                         job->set_progress (float (_first_nonexistant_frame) / N);
543                 }
544
545                 if (_film->three_d ()) {
546                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
547                                 break;
548                         }
549                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
550                                 break;
551                         }
552                 } else {
553                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
554                                 break;
555                         }
556                 }
557
558                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
559                 ++_first_nonexistant_frame;
560         }
561
562         fclose (mxf);
563 }
564
565 /** @param frame Frame index.
566  *  @return true if we can fake-write this frame.
567  */
568 bool
569 Writer::can_fake_write (int frame) const
570 {
571         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
572            parameters in the MXF writer.
573         */
574         return (frame != 0 && frame < _first_nonexistant_frame);
575 }
576
577 bool
578 operator< (QueueItem const & a, QueueItem const & b)
579 {
580         if (a.frame != b.frame) {
581                 return a.frame < b.frame;
582         }
583
584         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
585 }
586
587 bool
588 operator== (QueueItem const & a, QueueItem const & b)
589 {
590         return a.frame == b.frame && a.eyes == b.eyes;
591 }