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