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