Another shortcut.
[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 <libdcp/mono_picture_asset.h>
23 #include <libdcp/stereo_picture_asset.h>
24 #include <libdcp/sound_asset.h>
25 #include <libdcp/reel.h>
26 #include <libdcp/dcp.h>
27 #include <libdcp/cpl.h>
28 #include "writer.h"
29 #include "compose.hpp"
30 #include "film.h"
31 #include "ratio.h"
32 #include "log.h"
33 #include "dcp_video_frame.h"
34 #include "dcp_content_type.h"
35 #include "player.h"
36 #include "audio_mapping.h"
37 #include "config.h"
38 #include "job.h"
39 #include "cross.h"
40 #include "md5_digester.h"
41 #include "version.h"
42
43 #include "i18n.h"
44
45 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_GENERAL);
46 #define LOG_TIMING(...) _film->log()->microsecond_log (String::compose (__VA_ARGS__), Log::TYPE_TIMING);
47 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, Log::TYPE_WARNING);
48 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), Log::TYPE_ERROR);
49
50 /* OS X strikes again */
51 #undef set_key
52
53 using std::make_pair;
54 using std::pair;
55 using std::string;
56 using std::list;
57 using std::cout;
58 using boost::shared_ptr;
59 using boost::weak_ptr;
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         , _repeat_written (0)
75         , _pushed_to_disk (0)
76 {
77         /* Remove any old DCP */
78         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
79
80         shared_ptr<Job> job = _job.lock ();
81         assert (job);
82
83         job->sub (_("Checking existing image data"));
84         check_existing_picture_mxf ();
85
86         /* Create our picture asset in a subdirectory, named according to those
87            film's parameters which affect the video output.  We will hard-link
88            it into the DCP later.
89         */
90
91         if (_film->three_d ()) {
92                 _picture_asset.reset (new libdcp::StereoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
93         } else {
94                 _picture_asset.reset (new libdcp::MonoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
95         }
96
97         _picture_asset->set_edit_rate (_film->video_frame_rate ());
98         _picture_asset->set_size (_film->frame_size ());
99         _picture_asset->set_interop (_film->interop ());
100
101         if (_film->encrypted ()) {
102                 _picture_asset->set_key (_film->key ());
103         }
104         
105         _picture_asset_writer = _picture_asset->start_write (_first_nonexistant_frame > 0);
106
107         if (_film->audio_channels ()) {
108                 _sound_asset.reset (new libdcp::SoundAsset (_film->directory (), _film->audio_mxf_filename ()));
109                 _sound_asset->set_edit_rate (_film->video_frame_rate ());
110                 _sound_asset->set_channels (_film->audio_channels ());
111                 _sound_asset->set_sampling_rate (_film->audio_frame_rate ());
112                 _sound_asset->set_interop (_film->interop ());
113
114                 if (_film->encrypted ()) {
115                         _sound_asset->set_key (_film->key ());
116                 }
117                 
118                 /* Write the sound asset into the film directory so that we leave the creation
119                    of the DCP directory until the last minute.
120                 */
121                 _sound_asset_writer = _sound_asset->start_write ();
122         }
123
124         _thread = new boost::thread (boost::bind (&Writer::thread, this));
125
126         job->sub (_("Encoding image data"));
127 }
128
129 Writer::~Writer ()
130 {
131         terminate_thread (false);
132 }
133
134 void
135 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
136 {
137         boost::mutex::scoped_lock lock (_mutex);
138
139         while (_queued_full_in_memory > _maximum_frames_in_memory) {
140                 /* The queue is too big; wait until that is sorted out */
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         /* Now there's something to do: wake anything wait()ing on _empty_condition */
164         _empty_condition.notify_all ();
165 }
166
167 void
168 Writer::fake_write (int frame, Eyes eyes)
169 {
170         boost::mutex::scoped_lock lock (_mutex);
171
172         while (_queued_full_in_memory > _maximum_frames_in_memory) {
173                 /* The queue is too big; wait until that is sorted out */
174                 _full_condition.wait (lock);
175         }
176         
177         FILE* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
178         libdcp::FrameInfo info (ifi);
179         fclose (ifi);
180         
181         QueueItem qi;
182         qi.type = QueueItem::FAKE;
183         qi.size = info.size;
184         qi.frame = frame;
185         if (_film->three_d() && eyes == EYES_BOTH) {
186                 qi.eyes = EYES_LEFT;
187                 _queue.push_back (qi);
188                 qi.eyes = EYES_RIGHT;
189                 _queue.push_back (qi);
190         } else {
191                 qi.eyes = eyes;
192                 _queue.push_back (qi);
193         }
194
195         /* Now there's something to do: wake anything wait()ing on _empty_condition */
196         _empty_condition.notify_all ();
197 }
198
199 /** This method is not thread safe */
200 void
201 Writer::write (shared_ptr<const AudioBuffers> audio)
202 {
203         if (_sound_asset) {
204                 _sound_asset_writer->write (audio->data(), audio->frames());
205         }
206 }
207
208 /** This must be called from Writer::thread() with an appropriate lock held */
209 bool
210 Writer::have_sequenced_image_at_queue_head ()
211 {
212         if (_queue.empty ()) {
213                 return false;
214         }
215
216         _queue.sort ();
217
218         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
219
220         if (_queue.front().eyes == EYES_BOTH) {
221                 /* 2D */
222                 return _queue.front().frame == (_last_written_frame + 1);
223         }
224
225         /* 3D */
226
227         if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
228                 return true;
229         }
230
231         if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
232                 return true;
233         }
234
235         return false;
236 }
237
238 void
239 Writer::thread ()
240 try
241 {
242         while (true)
243         {
244                 boost::mutex::scoped_lock lock (_mutex);
245
246                 while (true) {
247                         
248                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
249                                 /* We've got something to do: go and do it */
250                                 break;
251                         }
252
253                         /* Nothing to do: wait until something happens which may indicate that we do */
254                         LOG_TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
255                         _empty_condition.wait (lock);
256                         LOG_TIMING (N_("writer wakes with a queue of %1"), _queue.size());
257                 }
258
259                 if (_finish && _queue.empty()) {
260                         return;
261                 }
262
263                 /* Write any frames that we can write; i.e. those that are in sequence. */
264                 while (have_sequenced_image_at_queue_head ()) {
265                         QueueItem qi = _queue.front ();
266                         _queue.pop_front ();
267                         if (qi.type == QueueItem::FULL && qi.encoded) {
268                                 --_queued_full_in_memory;
269                         }
270
271                         lock.unlock ();
272                         switch (qi.type) {
273                         case QueueItem::FULL:
274                         {
275                                 LOG_GENERAL (N_("Writer FULL-writes %1 to MXF"), qi.frame);
276                                 if (!qi.encoded) {
277                                         qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
278                                 }
279
280                                 libdcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size());
281                                 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
282                                 _last_written[qi.eyes] = qi.encoded;
283                                 ++_full_written;
284                                 break;
285                         }
286                         case QueueItem::FAKE:
287                                 LOG_GENERAL (N_("Writer FAKE-writes %1 to MXF"), qi.frame);
288                                 _picture_asset_writer->fake_write (qi.size);
289                                 _last_written[qi.eyes].reset ();
290                                 ++_fake_written;
291                                 break;
292                         case QueueItem::REPEAT:
293                         {
294                                 LOG_GENERAL (N_("Writer REPEAT-writes %1 to MXF"), qi.frame);
295                                 libdcp::FrameInfo fin = _picture_asset_writer->write (
296                                         _last_written[qi.eyes]->data(),
297                                         _last_written[qi.eyes]->size()
298                                         );
299                                 
300                                 _last_written[qi.eyes]->write_info (_film, qi.frame, qi.eyes, fin);
301                                 ++_repeat_written;
302                                 break;
303                         }
304                         }
305                         lock.lock ();
306
307                         _last_written_frame = qi.frame;
308                         _last_written_eyes = qi.eyes;
309                         
310                         if (_film->length()) {
311                                 shared_ptr<Job> job = _job.lock ();
312                                 assert (job);
313                                 int total = _film->time_to_video_frames (_film->length ());
314                                 if (_film->three_d ()) {
315                                         /* _full_written and so on are incremented for each eye, so we need to double the total
316                                            frames to get the correct progress.
317                                         */
318                                         total *= 2;
319                                 }
320                                 job->set_progress (float (_full_written + _fake_written + _repeat_written) / total);
321                         }
322                 }
323
324                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
325                         /* Too many frames in memory which can't yet be written to the stream.
326                            Write some FULL frames to disk.
327                         */
328
329                         /* Find one from the back of the queue */
330                         _queue.sort ();
331                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
332                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
333                                 ++i;
334                         }
335
336                         assert (i != _queue.rend());
337                         QueueItem qi = *i;
338
339                         ++_pushed_to_disk;
340                         
341                         lock.unlock ();
342
343                         LOG_GENERAL (
344                                 "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
345                                 _last_written_frame + 1,
346                                 _last_written_eyes, qi.frame
347                                 );
348                         
349                         qi.encoded->write (_film, qi.frame, qi.eyes);
350                         lock.lock ();
351                         qi.encoded.reset ();
352                         --_queued_full_in_memory;
353                 }
354
355                 /* The queue has probably just gone down a bit; notify anything wait()ing on _full_condition */
356                 _full_condition.notify_all ();
357         }
358 }
359 catch (...)
360 {
361         store_current ();
362 }
363
364 void
365 Writer::terminate_thread (bool can_throw)
366 {
367         boost::mutex::scoped_lock lock (_mutex);
368         if (_thread == 0) {
369                 return;
370         }
371         
372         _finish = true;
373         _empty_condition.notify_all ();
374         _full_condition.notify_all ();
375         lock.unlock ();
376
377         _thread->join ();
378         if (can_throw) {
379                 rethrow ();
380         }
381         
382         delete _thread;
383         _thread = 0;
384 }       
385
386 void
387 Writer::finish ()
388 {
389         if (!_thread) {
390                 return;
391         }
392         
393         terminate_thread (true);
394
395         _picture_asset_writer->finalize ();
396         if (_sound_asset_writer) {
397                 _sound_asset_writer->finalize ();
398         }
399         
400         int const frames = _last_written_frame + 1;
401
402         _picture_asset->set_duration (frames);
403
404         /* Hard-link the video MXF into the DCP */
405         boost::filesystem::path video_from;
406         video_from /= _film->internal_video_mxf_dir();
407         video_from /= _film->internal_video_mxf_filename();
408         
409         boost::filesystem::path video_to;
410         video_to /= _film->dir (_film->dcp_name());
411         video_to /= _film->video_mxf_filename ();
412
413         boost::system::error_code ec;
414         boost::filesystem::create_hard_link (video_from, video_to, ec);
415         if (ec) {
416                 LOG_WARNING_NC ("Hard-link failed; copying instead");
417                 boost::filesystem::copy_file (video_from, video_to, ec);
418                 if (ec) {
419                         LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
420                         throw FileError (ec.message(), video_from);
421                 }
422         }
423
424         /* And update the asset */
425
426         _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
427         _picture_asset->set_file_name (_film->video_mxf_filename ());
428
429         /* Move the audio MXF into the DCP */
430
431         if (_sound_asset) {
432                 boost::filesystem::path audio_to;
433                 audio_to /= _film->dir (_film->dcp_name ());
434                 audio_to /= _film->audio_mxf_filename ();
435                 
436                 boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
437                 if (ec) {
438                         throw FileError (
439                                 String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
440                                 );
441                 }
442                 
443                 _sound_asset->set_directory (_film->dir (_film->dcp_name ()));
444                 _sound_asset->set_duration (frames);
445         }
446         
447         libdcp::DCP dcp (_film->dir (_film->dcp_name()));
448
449         shared_ptr<libdcp::CPL> cpl (
450                 new libdcp::CPL (
451                         _film->dir (_film->dcp_name()),
452                         _film->dcp_name(),
453                         _film->dcp_content_type()->libdcp_kind (),
454                         frames,
455                         _film->video_frame_rate ()
456                         )
457                 );
458         
459         dcp.add_cpl (cpl);
460
461         cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
462                                                          _picture_asset,
463                                                          _sound_asset,
464                                                          shared_ptr<libdcp::SubtitleAsset> ()
465                                                          )
466                                ));
467
468         shared_ptr<Job> job = _job.lock ();
469         assert (job);
470
471         job->sub (_("Computing image digest"));
472         _picture_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
473
474         if (_sound_asset) {
475                 job->sub (_("Computing audio digest"));
476                 _sound_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
477         }
478
479         libdcp::XMLMetadata meta;
480         meta.issuer = Config::instance()->dcp_issuer ();
481         meta.creator = String::compose ("DCP-o-matic %1 %2", dcpomatic_version, dcpomatic_git_commit);
482         meta.set_issue_date_now ();
483         dcp.write_xml (_film->interop (), meta, _film->is_signed() ? make_signer () : shared_ptr<const libdcp::Signer> ());
484
485         LOG_GENERAL (
486                 N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT; %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk
487                 );
488 }
489
490 /** Tell the writer that frame `f' should be a repeat of the frame before it */
491 void
492 Writer::repeat (int f, Eyes e)
493 {
494         boost::mutex::scoped_lock lock (_mutex);
495
496         while (_queued_full_in_memory > _maximum_frames_in_memory) {
497                 /* The queue is too big; wait until that is sorted out */
498                 _full_condition.wait (lock);
499         }
500         
501         QueueItem qi;
502         qi.type = QueueItem::REPEAT;
503         qi.frame = f;
504         if (_film->three_d() && e == EYES_BOTH) {
505                 qi.eyes = EYES_LEFT;
506                 _queue.push_back (qi);
507                 qi.eyes = EYES_RIGHT;
508                 _queue.push_back (qi);
509         } else {
510                 qi.eyes = e;
511                 _queue.push_back (qi);
512         }
513
514         /* Now there's something to do: wake anything wait()ing on _empty_condition */
515         _empty_condition.notify_all ();
516 }
517
518 bool
519 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
520 {
521         /* Read the frame info as written */
522         FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
523         if (!ifi) {
524                 LOG_GENERAL ("Existing frame %1 has no info file", f);
525                 return false;
526         }
527         
528         libdcp::FrameInfo info (ifi);
529         fclose (ifi);
530         if (info.size == 0) {
531                 LOG_GENERAL ("Existing frame %1 has no info file", f);
532                 return false;
533         }
534         
535         /* Read the data from the MXF and hash it */
536         dcpomatic_fseek (mxf, info.offset, SEEK_SET);
537         EncodedData data (info.size);
538         size_t const read = fread (data.data(), 1, data.size(), mxf);
539         if (read != static_cast<size_t> (data.size ())) {
540                 LOG_GENERAL ("Existing frame %1 is incomplete", f);
541                 return false;
542         }
543
544         MD5Digester digester;
545         digester.add (data.data(), data.size());
546         if (digester.get() != info.hash) {
547                 LOG_GENERAL ("Existing frame %1 failed hash check", f);
548                 return false;
549         }
550
551         return true;
552 }
553
554 void
555 Writer::check_existing_picture_mxf ()
556 {
557         /* Try to open the existing MXF */
558         boost::filesystem::path p;
559         p /= _film->internal_video_mxf_dir ();
560         p /= _film->internal_video_mxf_filename ();
561         FILE* mxf = fopen_boost (p, "rb");
562         if (!mxf) {
563                 LOG_GENERAL ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno);
564                 return;
565         }
566
567         int N = 0;
568         for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
569                 ++N;
570         }
571
572         while (true) {
573
574                 shared_ptr<Job> job = _job.lock ();
575                 assert (job);
576
577                 if (N > 0) {
578                         job->set_progress (float (_first_nonexistant_frame) / N);
579                 }
580
581                 if (_film->three_d ()) {
582                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
583                                 break;
584                         }
585                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
586                                 break;
587                         }
588                 } else {
589                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
590                                 break;
591                         }
592                 }
593
594                 LOG_GENERAL ("Have existing frame %1", _first_nonexistant_frame);
595                 ++_first_nonexistant_frame;
596         }
597
598         fclose (mxf);
599 }
600
601 /** @param frame Frame index.
602  *  @return true if we can fake-write this frame.
603  */
604 bool
605 Writer::can_fake_write (int frame) const
606 {
607         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
608            parameters in the MXF writer.
609         */
610         return (frame != 0 && frame < _first_nonexistant_frame);
611 }
612
613 bool
614 operator< (QueueItem const & a, QueueItem const & b)
615 {
616         if (a.frame != b.frame) {
617                 return a.frame < b.frame;
618         }
619
620         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
621 }
622
623 bool
624 operator== (QueueItem const & a, QueueItem const & b)
625 {
626         return a.frame == b.frame && a.eyes == b.eyes;
627 }