Fix corruption of an existing DCP when a new one is made with the same video
[dcpomatic.git] / src / lib / reel_writer.cc
1 /*
2     Copyright (C) 2012-2016 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "reel_writer.h"
22 #include "film.h"
23 #include "cross.h"
24 #include "job.h"
25 #include "log.h"
26 #include "digester.h"
27 #include "font.h"
28 #include "compose.hpp"
29 #include "audio_buffers.h"
30 #include <dcp/mono_picture_asset.h>
31 #include <dcp/stereo_picture_asset.h>
32 #include <dcp/sound_asset.h>
33 #include <dcp/sound_asset_writer.h>
34 #include <dcp/reel.h>
35 #include <dcp/reel_mono_picture_asset.h>
36 #include <dcp/reel_stereo_picture_asset.h>
37 #include <dcp/reel_sound_asset.h>
38 #include <dcp/reel_subtitle_asset.h>
39 #include <dcp/dcp.h>
40 #include <dcp/cpl.h>
41 #include <dcp/certificate_chain.h>
42 #include <dcp/interop_subtitle_asset.h>
43 #include <dcp/smpte_subtitle_asset.h>
44 #include <dcp/raw_convert.h>
45 #include <boost/foreach.hpp>
46
47 #include "i18n.h"
48
49 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_GENERAL);
50 #define LOG_GENERAL_NC(...) _film->log()->log (__VA_ARGS__, LogEntry::TYPE_GENERAL);
51 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, LogEntry::TYPE_WARNING);
52 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_ERROR);
53
54 using std::list;
55 using std::string;
56 using std::cout;
57 using boost::shared_ptr;
58 using boost::optional;
59 using boost::dynamic_pointer_cast;
60 using dcp::Data;
61 using dcp::raw_convert;
62
63 int const ReelWriter::_info_size = 48;
64
65 ReelWriter::ReelWriter (
66         shared_ptr<const Film> film, DCPTimePeriod period, shared_ptr<Job> job, int reel_index, int reel_count, optional<string> content_summary
67         )
68         : _film (film)
69         , _period (period)
70         , _last_written_video_frame (-1)
71         , _last_written_eyes (EYES_RIGHT)
72         , _total_written_audio_frames (0)
73         , _reel_index (reel_index)
74         , _reel_count (reel_count)
75         , _content_summary (content_summary)
76 {
77         /* Create our picture asset in a subdirectory, named according to those
78            film's parameters which affect the video output.  We will hard-link
79            it into the DCP later.
80         */
81
82         if (_film->three_d ()) {
83                 _picture_asset.reset (new dcp::StereoPictureAsset (dcp::Fraction (_film->video_frame_rate (), 1)));
84         } else {
85                 _picture_asset.reset (new dcp::MonoPictureAsset (dcp::Fraction (_film->video_frame_rate (), 1)));
86         }
87
88         _picture_asset->set_size (_film->frame_size ());
89
90         if (_film->encrypted ()) {
91                 _picture_asset->set_key (_film->key ());
92                 _picture_asset->set_context_id (_film->context_id ());
93         }
94
95         _picture_asset->set_file (
96                 _film->internal_video_asset_dir() / _film->internal_video_asset_filename(_period)
97                 );
98
99         job->sub (_("Checking existing image data"));
100         _first_nonexistant_frame = check_existing_picture_asset ();
101
102         _picture_asset_writer = _picture_asset->start_write (
103                 _film->internal_video_asset_dir() / _film->internal_video_asset_filename(_period),
104                 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
105                 _first_nonexistant_frame > 0
106                 );
107
108         if (_film->audio_channels ()) {
109                 _sound_asset.reset (
110                         new dcp::SoundAsset (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ())
111                         );
112
113                 if (_film->encrypted ()) {
114                         _sound_asset->set_key (_film->key ());
115                 }
116
117                 DCPOMATIC_ASSERT (_film->directory());
118
119                 /* Write the sound asset into the film directory so that we leave the creation
120                    of the DCP directory until the last minute.
121                 */
122                 _sound_asset_writer = _sound_asset->start_write (
123                         _film->directory().get() / audio_asset_filename (_sound_asset, _reel_index, _reel_count, _content_summary),
124                         _film->interop() ? dcp::INTEROP : dcp::SMPTE
125                         );
126         }
127 }
128
129 /** @param frame reel-relative frame */
130 void
131 ReelWriter::write_frame_info (Frame frame, Eyes eyes, dcp::FrameInfo info) const
132 {
133         FILE* file = 0;
134         boost::filesystem::path info_file = _film->info_file (_period);
135
136         bool const read = boost::filesystem::exists (info_file);
137
138 #ifdef DCPOMATIC_WINDOWS
139         if (read) {
140                 LOG_GENERAL (
141                         "Checked %1 (which exists) length is %2 perms are %3",
142                         info_file, boost::filesystem::file_size (info_file), int(boost::filesystem::status(info_file).permissions())
143                         );
144         } else {
145                 LOG_GENERAL ("Checked %1 (which does not exist)", info_file);
146         }
147 #endif
148
149         if (read) {
150                 file = fopen_boost (info_file, "r+b");
151         } else {
152                 file = fopen_boost (info_file, "wb");
153         }
154         if (!file) {
155                 throw OpenFileError (info_file, errno, read);
156         }
157         dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
158         fwrite (&info.offset, sizeof (info.offset), 1, file);
159         fwrite (&info.size, sizeof (info.size), 1, file);
160         fwrite (info.hash.c_str(), 1, info.hash.size(), file);
161         fclose (file);
162 }
163
164 dcp::FrameInfo
165 ReelWriter::read_frame_info (FILE* file, Frame frame, Eyes eyes) const
166 {
167         dcp::FrameInfo info;
168         dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
169         fread (&info.offset, sizeof (info.offset), 1, file);
170         fread (&info.size, sizeof (info.size), 1, file);
171
172         char hash_buffer[33];
173         fread (hash_buffer, 1, 32, file);
174         hash_buffer[32] = '\0';
175         info.hash = hash_buffer;
176
177         return info;
178 }
179
180 long
181 ReelWriter::frame_info_position (Frame frame, Eyes eyes) const
182 {
183         switch (eyes) {
184         case EYES_BOTH:
185                 return frame * _info_size;
186         case EYES_LEFT:
187                 return frame * _info_size * 2;
188         case EYES_RIGHT:
189                 return frame * _info_size * 2 + _info_size;
190         default:
191                 DCPOMATIC_ASSERT (false);
192         }
193
194         DCPOMATIC_ASSERT (false);
195 }
196
197 Frame
198 ReelWriter::check_existing_picture_asset ()
199 {
200         DCPOMATIC_ASSERT (_picture_asset->file());
201         boost::filesystem::path asset = _picture_asset->file().get();
202
203         /* If there is an existing asset, break any hard links to it as we are about to change its contents
204            (if only by changing the IDs); see #1126.
205         */
206
207         if (boost::filesystem::exists(asset) && boost::filesystem::hard_link_count(asset) > 1) {
208                 boost::filesystem::copy_file (asset, asset.string() + ".tmp");
209                 boost::filesystem::remove (asset);
210                 boost::filesystem::rename (asset.string() + ".tmp", asset);
211         }
212
213         /* Try to open the existing asset */
214         FILE* asset_file = fopen_boost (asset, "rb");
215         if (!asset_file) {
216                 LOG_GENERAL ("Could not open existing asset at %1 (errno=%2)", asset.string(), errno);
217                 return 0;
218         } else {
219                 LOG_GENERAL ("Opened existing asset at %1", asset.string());
220         }
221
222         /* Offset of the last dcp::FrameInfo in the info file */
223         int const n = (boost::filesystem::file_size (_film->info_file(_period)) / _info_size) - 1;
224         LOG_GENERAL ("The last FI is %1; info file is %2, info size %3", n, boost::filesystem::file_size (_film->info_file(_period)), _info_size);
225
226         FILE* info_file = fopen_boost (_film->info_file(_period), "rb");
227         if (!info_file) {
228                 LOG_GENERAL_NC ("Could not open film info file");
229                 fclose (asset_file);
230                 return 0;
231         }
232
233         Frame first_nonexistant_frame;
234         if (_film->three_d ()) {
235                 /* Start looking at the last left frame */
236                 first_nonexistant_frame = n / 2;
237         } else {
238                 first_nonexistant_frame = n;
239         }
240
241         while (!existing_picture_frame_ok(asset_file, info_file, first_nonexistant_frame) && first_nonexistant_frame > 0) {
242                 --first_nonexistant_frame;
243         }
244
245         if (!_film->three_d() && first_nonexistant_frame > 0) {
246                 /* If we are doing 3D we might have found a good L frame with no R, so only
247                    do this if we're in 2D and we've just found a good B(oth) frame.
248                 */
249                 ++first_nonexistant_frame;
250         }
251
252         LOG_GENERAL ("Proceeding with first nonexistant frame %1", first_nonexistant_frame);
253
254         fclose (asset_file);
255         fclose (info_file);
256
257         return first_nonexistant_frame;
258 }
259
260 void
261 ReelWriter::write (optional<Data> encoded, Frame frame, Eyes eyes)
262 {
263         dcp::FrameInfo fin = _picture_asset_writer->write (encoded->data().get (), encoded->size());
264         write_frame_info (frame, eyes, fin);
265         _last_written[eyes] = encoded;
266         _last_written_video_frame = frame;
267         _last_written_eyes = eyes;
268 }
269
270 void
271 ReelWriter::fake_write (Frame frame, Eyes eyes, int size)
272 {
273         _picture_asset_writer->fake_write (size);
274         _last_written_video_frame = frame;
275         _last_written_eyes = eyes;
276 }
277
278 void
279 ReelWriter::repeat_write (Frame frame, Eyes eyes)
280 {
281         dcp::FrameInfo fin = _picture_asset_writer->write (
282                 _last_written[eyes]->data().get(),
283                 _last_written[eyes]->size()
284                 );
285         write_frame_info (frame, eyes, fin);
286         _last_written_video_frame = frame;
287         _last_written_eyes = eyes;
288 }
289
290 void
291 ReelWriter::finish ()
292 {
293         if (!_picture_asset_writer->finalize ()) {
294                 /* Nothing was written to the picture asset */
295                 LOG_GENERAL ("Nothing was written to reel %1 of %2", _reel_index, _reel_count);
296                 _picture_asset.reset ();
297         }
298
299         if (_sound_asset_writer && !_sound_asset_writer->finalize ()) {
300                 /* Nothing was written to the sound asset */
301                 _sound_asset.reset ();
302         }
303
304         /* Hard-link any video asset file into the DCP */
305         if (_picture_asset) {
306                 DCPOMATIC_ASSERT (_picture_asset->file());
307                 boost::filesystem::path video_from = _picture_asset->file().get();
308                 boost::filesystem::path video_to;
309                 video_to /= _film->dir (_film->dcp_name());
310                 video_to /= video_asset_filename (_picture_asset, _reel_index, _reel_count, _content_summary);
311
312                 boost::system::error_code ec;
313                 boost::filesystem::create_hard_link (video_from, video_to, ec);
314                 if (ec) {
315                         LOG_WARNING_NC ("Hard-link failed; copying instead");
316                         boost::filesystem::copy_file (video_from, video_to, ec);
317                         if (ec) {
318                                 LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
319                                 throw FileError (ec.message(), video_from);
320                         }
321                 }
322
323                 _picture_asset->set_file (video_to);
324         }
325
326         /* Move the audio asset into the DCP */
327         if (_sound_asset) {
328                 boost::filesystem::path audio_to;
329                 audio_to /= _film->dir (_film->dcp_name ());
330                 string const aaf = audio_asset_filename (_sound_asset, _reel_index, _reel_count, _content_summary);
331                 audio_to /= aaf;
332
333                 boost::system::error_code ec;
334                 boost::filesystem::rename (_film->file (aaf), audio_to, ec);
335                 if (ec) {
336                         throw FileError (
337                                 String::compose (_("could not move audio asset into the DCP (%1)"), ec.value ()), aaf
338                                 );
339                 }
340
341                 _sound_asset->set_file (audio_to);
342         }
343 }
344
345 shared_ptr<dcp::Reel>
346 ReelWriter::create_reel (list<ReferencedReelAsset> const & refs, list<shared_ptr<Font> > const & fonts)
347 {
348         shared_ptr<dcp::Reel> reel (new dcp::Reel ());
349
350         shared_ptr<dcp::ReelPictureAsset> reel_picture_asset;
351
352         if (_picture_asset) {
353                 /* We have made a picture asset of our own.  Put it into the reel */
354                 shared_ptr<dcp::MonoPictureAsset> mono = dynamic_pointer_cast<dcp::MonoPictureAsset> (_picture_asset);
355                 if (mono) {
356                         reel_picture_asset.reset (new dcp::ReelMonoPictureAsset (mono, 0));
357                 }
358
359                 shared_ptr<dcp::StereoPictureAsset> stereo = dynamic_pointer_cast<dcp::StereoPictureAsset> (_picture_asset);
360                 if (stereo) {
361                         reel_picture_asset.reset (new dcp::ReelStereoPictureAsset (stereo, 0));
362                 }
363         } else {
364                 LOG_GENERAL ("no picture asset of our own; look through %1", refs.size());
365                 /* We don't have a picture asset of our own; hopefully we have one to reference */
366                 BOOST_FOREACH (ReferencedReelAsset j, refs) {
367                         shared_ptr<dcp::ReelPictureAsset> k = dynamic_pointer_cast<dcp::ReelPictureAsset> (j.asset);
368                         if (k) {
369                                 LOG_GENERAL ("candidate picture asset period is %1-%2", j.period.from.get(), j.period.to.get());
370                         }
371                         if (k && j.period == _period) {
372                                 reel_picture_asset = k;
373                         }
374                 }
375         }
376
377         LOG_GENERAL ("create_reel for %1-%2; %3 of %4", _period.from.get(), _period.to.get(), _reel_index, _reel_count);
378
379         Frame const period_duration = _period.duration().frames_round(_film->video_frame_rate());
380
381         DCPOMATIC_ASSERT (reel_picture_asset);
382         if (reel_picture_asset->duration() != period_duration) {
383                 throw ProgrammingError (
384                         __FILE__, __LINE__,
385                         String::compose ("%1 vs %2", reel_picture_asset->duration(), period_duration)
386                         );
387         }
388         reel->add (reel_picture_asset);
389
390         /* If we have a hash for this asset in the CPL, assume that it is correct */
391         if (reel_picture_asset->hash()) {
392                 reel_picture_asset->asset_ref()->set_hash (reel_picture_asset->hash().get());
393         }
394
395         shared_ptr<dcp::ReelSoundAsset> reel_sound_asset;
396
397         if (_sound_asset) {
398                 /* We have made a sound asset of our own.  Put it into the reel */
399                 reel_sound_asset.reset (new dcp::ReelSoundAsset (_sound_asset, 0));
400         } else {
401                 /* We don't have a sound asset of our own; hopefully we have one to reference */
402                 BOOST_FOREACH (ReferencedReelAsset j, refs) {
403                         shared_ptr<dcp::ReelSoundAsset> k = dynamic_pointer_cast<dcp::ReelSoundAsset> (j.asset);
404                         if (k && j.period == _period) {
405                                 reel_sound_asset = k;
406                                 /* If we have a hash for this asset in the CPL, assume that it is correct */
407                                 if (k->hash()) {
408                                         k->asset_ref()->set_hash (k->hash().get());
409                                 }
410                         }
411                 }
412         }
413
414         DCPOMATIC_ASSERT (reel_sound_asset);
415         if (reel_sound_asset->duration() != period_duration) {
416                 LOG_ERROR (
417                         "Reel sound asset has length %1 but reel period is %2",
418                         reel_sound_asset->duration(),
419                         period_duration
420                         );
421                 if (reel_sound_asset->duration() != period_duration) {
422                         throw ProgrammingError (
423                                 __FILE__, __LINE__,
424                                 String::compose ("%1 vs %2", reel_sound_asset->duration(), period_duration)
425                                 );
426                 }
427
428         }
429         reel->add (reel_sound_asset);
430
431         shared_ptr<dcp::ReelSubtitleAsset> reel_subtitle_asset;
432
433         if (_subtitle_asset) {
434
435                 boost::filesystem::path liberation_normal;
436                 try {
437                         liberation_normal = shared_path() / "LiberationSans-Regular.ttf";
438                         if (!boost::filesystem::exists (liberation_normal)) {
439                                 /* Hack for unit tests */
440                                 liberation_normal = shared_path() / "fonts" / "LiberationSans-Regular.ttf";
441                         }
442                 } catch (boost::filesystem::filesystem_error& e) {
443
444                 }
445
446                 if (!boost::filesystem::exists(liberation_normal)) {
447                         liberation_normal = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf";
448                 }
449
450                 /* Add all the fonts to the subtitle content */
451                 BOOST_FOREACH (shared_ptr<Font> j, fonts) {
452                         _subtitle_asset->add_font (j->id(), j->file(FontFiles::NORMAL).get_value_or(liberation_normal));
453                 }
454
455                 if (dynamic_pointer_cast<dcp::InteropSubtitleAsset> (_subtitle_asset)) {
456                         boost::filesystem::path directory = _film->dir (_film->dcp_name ()) / _subtitle_asset->id ();
457                         boost::filesystem::create_directories (directory);
458                         _subtitle_asset->write (directory / ("sub_" + _subtitle_asset->id() + ".xml"));
459                 } else {
460
461                         /* All our assets should be the same length; use the picture asset length here
462                            as a reference to set the subtitle one.
463                         */
464                         dynamic_pointer_cast<dcp::SMPTESubtitleAsset>(_subtitle_asset)->set_intrinsic_duration (
465                                 reel_picture_asset->intrinsic_duration ()
466                                 );
467
468                         _subtitle_asset->write (
469                                 _film->dir (_film->dcp_name ()) / ("sub_" + _subtitle_asset->id() + ".mxf")
470                                 );
471                 }
472
473                 reel_subtitle_asset.reset (
474                         new dcp::ReelSubtitleAsset (
475                                 _subtitle_asset,
476                                 dcp::Fraction (_film->video_frame_rate(), 1),
477                                 reel_picture_asset->intrinsic_duration (),
478                                 0
479                                 )
480                         );
481         } else {
482                 /* We don't have a subtitle asset of our own; hopefully we have one to reference */
483                 BOOST_FOREACH (ReferencedReelAsset j, refs) {
484                         shared_ptr<dcp::ReelSubtitleAsset> k = dynamic_pointer_cast<dcp::ReelSubtitleAsset> (j.asset);
485                         if (k && j.period == _period) {
486                                 reel_subtitle_asset = k;
487                                 /* If we have a hash for this asset in the CPL, assume that it is correct */
488                                 if (k->hash()) {
489                                         k->asset_ref()->set_hash (k->hash().get());
490                                 }
491                         }
492                 }
493         }
494
495         if (reel_subtitle_asset) {
496                 DCPOMATIC_ASSERT (reel_subtitle_asset->duration() == period_duration);
497                 reel->add (reel_subtitle_asset);
498         }
499
500         return reel;
501 }
502
503 void
504 ReelWriter::calculate_digests (boost::function<void (float)> set_progress)
505 {
506         if (_picture_asset) {
507                 _picture_asset->hash (set_progress);
508         }
509
510         if (_sound_asset) {
511                 _sound_asset->hash (set_progress);
512         }
513 }
514
515 Frame
516 ReelWriter::start () const
517 {
518         return _period.from.frames_floor (_film->video_frame_rate());
519 }
520
521
522 void
523 ReelWriter::write (shared_ptr<const AudioBuffers> audio)
524 {
525         if (!_sound_asset_writer) {
526                 return;
527         }
528
529         if (audio) {
530                 _sound_asset_writer->write (audio->data(), audio->frames());
531         }
532
533         _total_written_audio_frames += audio->frames ();
534 }
535
536 void
537 ReelWriter::write (PlayerSubtitles subs)
538 {
539         if (!_subtitle_asset) {
540                 string lang = _film->subtitle_language ();
541                 if (lang.empty ()) {
542                         lang = "Unknown";
543                 }
544                 if (_film->interop ()) {
545                         shared_ptr<dcp::InteropSubtitleAsset> s (new dcp::InteropSubtitleAsset ());
546                         s->set_movie_title (_film->name ());
547                         s->set_language (lang);
548                         s->set_reel_number (raw_convert<string> (_reel_index + 1));
549                         _subtitle_asset = s;
550                 } else {
551                         shared_ptr<dcp::SMPTESubtitleAsset> s (new dcp::SMPTESubtitleAsset ());
552                         s->set_content_title_text (_film->name ());
553                         s->set_language (lang);
554                         s->set_edit_rate (dcp::Fraction (_film->video_frame_rate (), 1));
555                         s->set_reel_number (_reel_index + 1);
556                         s->set_time_code_rate (_film->video_frame_rate ());
557                         s->set_start_time (dcp::Time ());
558                         if (_film->encrypted ()) {
559                                 s->set_key (_film->key ());
560                         }
561                         _subtitle_asset = s;
562                 }
563         }
564
565         BOOST_FOREACH (SubtitleString i, subs.text) {
566                 i.set_in  (i.in()  - dcp::Time (_period.from.seconds(), i.in().tcr));
567                 i.set_out (i.out() - dcp::Time (_period.from.seconds(), i.out().tcr));
568                 _subtitle_asset->add (i);
569         }
570 }
571
572 bool
573 ReelWriter::existing_picture_frame_ok (FILE* asset_file, FILE* info_file, Frame frame) const
574 {
575         LOG_GENERAL ("Checking existing picture frame %1", frame);
576
577         /* Read the data from the info file; for 3D we just check the left
578            frames until we find a good one.
579         */
580         dcp::FrameInfo const info = read_frame_info (info_file, frame, _film->three_d () ? EYES_LEFT : EYES_BOTH);
581
582         bool ok = true;
583
584         /* Read the data from the asset and hash it */
585         dcpomatic_fseek (asset_file, info.offset, SEEK_SET);
586         Data data (info.size);
587         size_t const read = fread (data.data().get(), 1, data.size(), asset_file);
588         LOG_GENERAL ("Read %1 bytes of asset data; wanted %2", read, info.size);
589         if (read != static_cast<size_t> (data.size ())) {
590                 LOG_GENERAL ("Existing frame %1 is incomplete", frame);
591                 ok = false;
592         } else {
593                 Digester digester;
594                 digester.add (data.data().get(), data.size());
595                 LOG_GENERAL ("Hash %1 vs %2", digester.get(), info.hash);
596                 if (digester.get() != info.hash) {
597                         LOG_GENERAL ("Existing frame %1 failed hash check", frame);
598                         ok = false;
599                 }
600         }
601
602         return ok;
603 }