Add reel index/count to DCP filename format.
[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 <boost/foreach.hpp>
45
46 #include "i18n.h"
47
48 #define LOG_GENERAL(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_GENERAL);
49 #define LOG_GENERAL_NC(...) _film->log()->log (__VA_ARGS__, LogEntry::TYPE_GENERAL);
50 #define LOG_WARNING_NC(...) _film->log()->log (__VA_ARGS__, LogEntry::TYPE_WARNING);
51 #define LOG_ERROR(...) _film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_ERROR);
52
53 using std::list;
54 using std::string;
55 using std::cout;
56 using boost::shared_ptr;
57 using boost::optional;
58 using boost::dynamic_pointer_cast;
59 using dcp::Data;
60
61 int const ReelWriter::_info_size = 48;
62
63 ReelWriter::ReelWriter (shared_ptr<const Film> film, DCPTimePeriod period, shared_ptr<Job> job, int reel_index, int reel_count)
64         : _film (film)
65         , _period (period)
66         , _first_nonexistant_frame (0)
67         , _last_written_video_frame (-1)
68         , _last_written_eyes (EYES_RIGHT)
69         , _total_written_audio_frames (0)
70         , _reel_index (reel_index)
71         , _reel_count (reel_count)
72 {
73         /* Create our picture asset in a subdirectory, named according to those
74            film's parameters which affect the video output.  We will hard-link
75            it into the DCP later.
76         */
77
78         if (_film->three_d ()) {
79                 _picture_asset.reset (new dcp::StereoPictureAsset (dcp::Fraction (_film->video_frame_rate (), 1)));
80         } else {
81                 _picture_asset.reset (new dcp::MonoPictureAsset (dcp::Fraction (_film->video_frame_rate (), 1)));
82         }
83
84         _picture_asset->set_size (_film->frame_size ());
85
86         if (_film->encrypted ()) {
87                 _picture_asset->set_key (_film->key ());
88         }
89
90         _picture_asset->set_file (
91                 _film->internal_video_asset_dir() / _film->internal_video_asset_filename(_period)
92                 );
93
94         job->sub (_("Checking existing image data"));
95         check_existing_picture_asset ();
96
97         _picture_asset_writer = _picture_asset->start_write (
98                 _film->internal_video_asset_dir() / _film->internal_video_asset_filename(_period),
99                 _film->interop() ? dcp::INTEROP : dcp::SMPTE,
100                 _first_nonexistant_frame > 0
101                 );
102
103         if (_film->audio_channels ()) {
104                 _sound_asset.reset (
105                         new dcp::SoundAsset (dcp::Fraction (_film->video_frame_rate(), 1), _film->audio_frame_rate (), _film->audio_channels ())
106                         );
107
108                 if (_film->encrypted ()) {
109                         _sound_asset->set_key (_film->key ());
110                 }
111
112                 /* Write the sound asset into the film directory so that we leave the creation
113                    of the DCP directory until the last minute.
114                 */
115                 _sound_asset_writer = _sound_asset->start_write (
116                         _film->directory() / audio_asset_filename (_sound_asset, _reel_index, _reel_count),
117                         _film->interop() ? dcp::INTEROP : dcp::SMPTE
118                         );
119         }
120 }
121
122 /** @param frame reel-relative frame */
123 void
124 ReelWriter::write_frame_info (Frame frame, Eyes eyes, dcp::FrameInfo info) const
125 {
126         FILE* file = 0;
127         boost::filesystem::path info_file = _film->info_file (_period);
128         if (boost::filesystem::exists (info_file)) {
129                 file = fopen_boost (info_file, "r+b");
130         } else {
131                 file = fopen_boost (info_file, "wb");
132         }
133         if (!file) {
134                 throw OpenFileError (info_file);
135         }
136         dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
137         fwrite (&info.offset, sizeof (info.offset), 1, file);
138         fwrite (&info.size, sizeof (info.size), 1, file);
139         fwrite (info.hash.c_str(), 1, info.hash.size(), file);
140         fclose (file);
141 }
142
143 dcp::FrameInfo
144 ReelWriter::read_frame_info (FILE* file, Frame frame, Eyes eyes) const
145 {
146         dcp::FrameInfo info;
147         dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
148         fread (&info.offset, sizeof (info.offset), 1, file);
149         fread (&info.size, sizeof (info.size), 1, file);
150
151         char hash_buffer[33];
152         fread (hash_buffer, 1, 32, file);
153         hash_buffer[32] = '\0';
154         info.hash = hash_buffer;
155
156         return info;
157 }
158
159 long
160 ReelWriter::frame_info_position (Frame frame, Eyes eyes) const
161 {
162         switch (eyes) {
163         case EYES_BOTH:
164                 return frame * _info_size;
165         case EYES_LEFT:
166                 return frame * _info_size * 2;
167         case EYES_RIGHT:
168                 return frame * _info_size * 2 + _info_size;
169         default:
170                 DCPOMATIC_ASSERT (false);
171         }
172
173         DCPOMATIC_ASSERT (false);
174 }
175
176 void
177 ReelWriter::check_existing_picture_asset ()
178 {
179         /* Try to open the existing asset */
180         FILE* asset_file = fopen_boost (_picture_asset->file(), "rb");
181         if (!asset_file) {
182                 LOG_GENERAL ("Could not open existing asset at %1 (errno=%2)", _picture_asset->file().string(), errno);
183                 return;
184         } else {
185                 LOG_GENERAL ("Opened existing asset at %1", _picture_asset->file().string());
186         }
187
188         /* Offset of the last dcp::FrameInfo in the info file */
189         int const n = (boost::filesystem::file_size (_film->info_file(_period)) / _info_size) - 1;
190         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);
191
192         FILE* info_file = fopen_boost (_film->info_file(_period), "rb");
193         if (!info_file) {
194                 LOG_GENERAL_NC ("Could not open film info file");
195                 fclose (asset_file);
196                 return;
197         }
198
199         if (_film->three_d ()) {
200                 /* Start looking at the last left frame */
201                 _first_nonexistant_frame = n / 2;
202         } else {
203                 _first_nonexistant_frame = n;
204         }
205
206         while (!existing_picture_frame_ok(asset_file, info_file) && _first_nonexistant_frame > 0) {
207                 --_first_nonexistant_frame;
208         }
209
210         if (!_film->three_d() && _first_nonexistant_frame > 0) {
211                 /* If we are doing 3D we might have found a good L frame with no R, so only
212                    do this if we're in 2D and we've just found a good B(oth) frame.
213                 */
214                 ++_first_nonexistant_frame;
215         }
216
217         LOG_GENERAL ("Proceeding with first nonexistant frame %1", _first_nonexistant_frame);
218
219         fclose (asset_file);
220         fclose (info_file);
221 }
222
223 void
224 ReelWriter::write (optional<Data> encoded, Frame frame, Eyes eyes)
225 {
226         dcp::FrameInfo fin = _picture_asset_writer->write (encoded->data().get (), encoded->size());
227         write_frame_info (frame, eyes, fin);
228         _last_written[eyes] = encoded;
229         _last_written_video_frame = frame;
230         _last_written_eyes = eyes;
231 }
232
233 void
234 ReelWriter::fake_write (Frame frame, Eyes eyes, int size)
235 {
236         _picture_asset_writer->fake_write (size);
237         _last_written_video_frame = frame;
238         _last_written_eyes = eyes;
239 }
240
241 void
242 ReelWriter::repeat_write (Frame frame, Eyes eyes)
243 {
244         dcp::FrameInfo fin = _picture_asset_writer->write (
245                 _last_written[eyes]->data().get(),
246                 _last_written[eyes]->size()
247                 );
248         write_frame_info (frame, eyes, fin);
249         _last_written_video_frame = frame;
250         _last_written_eyes = eyes;
251 }
252
253 void
254 ReelWriter::finish ()
255 {
256         if (!_picture_asset_writer->finalize ()) {
257                 /* Nothing was written to the picture asset */
258                 _picture_asset.reset ();
259         }
260
261         if (_sound_asset_writer && !_sound_asset_writer->finalize ()) {
262                 /* Nothing was written to the sound asset */
263                 _sound_asset.reset ();
264         }
265
266         /* Hard-link any video asset file into the DCP */
267         if (_picture_asset) {
268                 boost::filesystem::path video_from = _picture_asset->file ();
269                 boost::filesystem::path video_to;
270                 video_to /= _film->dir (_film->dcp_name());
271                 video_to /= video_asset_filename (_picture_asset, _reel_index, _reel_count);
272
273                 boost::system::error_code ec;
274                 boost::filesystem::create_hard_link (video_from, video_to, ec);
275                 if (ec) {
276                         LOG_WARNING_NC ("Hard-link failed; copying instead");
277                         boost::filesystem::copy_file (video_from, video_to, ec);
278                         if (ec) {
279                                 LOG_ERROR ("Failed to copy video file from %1 to %2 (%3)", video_from.string(), video_to.string(), ec.message ());
280                                 throw FileError (ec.message(), video_from);
281                         }
282                 }
283
284                 _picture_asset->set_file (video_to);
285         }
286
287         /* Move the audio asset into the DCP */
288         if (_sound_asset) {
289                 boost::filesystem::path audio_to;
290                 audio_to /= _film->dir (_film->dcp_name ());
291                 string const aaf = audio_asset_filename (_sound_asset, _reel_index, _reel_count);
292                 audio_to /= aaf;
293
294                 boost::system::error_code ec;
295                 boost::filesystem::rename (_film->file (aaf), audio_to, ec);
296                 if (ec) {
297                         throw FileError (
298                                 String::compose (_("could not move audio asset into the DCP (%1)"), ec.value ()), aaf
299                                 );
300                 }
301
302                 _sound_asset->set_file (audio_to);
303         }
304 }
305
306 shared_ptr<dcp::Reel>
307 ReelWriter::create_reel (list<ReferencedReelAsset> const & refs, list<shared_ptr<Font> > const & fonts)
308 {
309         shared_ptr<dcp::Reel> reel (new dcp::Reel ());
310
311         shared_ptr<dcp::ReelPictureAsset> reel_picture_asset;
312
313         if (_picture_asset) {
314                 /* We have made a picture asset of our own.  Put it into the reel */
315                 shared_ptr<dcp::MonoPictureAsset> mono = dynamic_pointer_cast<dcp::MonoPictureAsset> (_picture_asset);
316                 if (mono) {
317                         reel_picture_asset.reset (new dcp::ReelMonoPictureAsset (mono, 0));
318                 }
319
320                 shared_ptr<dcp::StereoPictureAsset> stereo = dynamic_pointer_cast<dcp::StereoPictureAsset> (_picture_asset);
321                 if (stereo) {
322                         reel_picture_asset.reset (new dcp::ReelStereoPictureAsset (stereo, 0));
323                 }
324         } else {
325                 /* We don't have a picture asset of our own; hopefully we have one to reference */
326                 BOOST_FOREACH (ReferencedReelAsset j, refs) {
327                         shared_ptr<dcp::ReelPictureAsset> k = dynamic_pointer_cast<dcp::ReelPictureAsset> (j.asset);
328                         if (k && j.period == _period) {
329                                 reel_picture_asset = k;
330                         }
331                 }
332         }
333
334         reel->add (reel_picture_asset);
335         /* If we have a hash for this asset in the CPL, assume that it is correct */
336         if (reel_picture_asset->hash()) {
337                 reel_picture_asset->asset_ref()->set_hash (reel_picture_asset->hash().get());
338         }
339
340         if (_sound_asset) {
341                 /* We have made a sound asset of our own.  Put it into the reel */
342                 reel->add (shared_ptr<dcp::ReelSoundAsset> (new dcp::ReelSoundAsset (_sound_asset, 0)));
343         } else {
344                 /* We don't have a sound asset of our own; hopefully we have one to reference */
345                 BOOST_FOREACH (ReferencedReelAsset j, refs) {
346                         shared_ptr<dcp::ReelSoundAsset> k = dynamic_pointer_cast<dcp::ReelSoundAsset> (j.asset);
347                         if (k && j.period == _period) {
348                                 reel->add (k);
349                                 /* If we have a hash for this asset in the CPL, assume that it is correct */
350                                 if (k->hash()) {
351                                         k->asset_ref()->set_hash (k->hash().get());
352                                 }
353                         }
354                 }
355         }
356
357         if (_subtitle_asset) {
358
359                 boost::filesystem::path liberation_normal;
360                 try {
361                         liberation_normal = shared_path() / "LiberationSans-Regular.ttf";
362                         if (!boost::filesystem::exists (liberation_normal)) {
363                                 /* Hack for unit tests */
364                                 liberation_normal = shared_path() / "fonts" / "LiberationSans-Regular.ttf";
365                         }
366                 } catch (boost::filesystem::filesystem_error& e) {
367
368                 }
369
370                 if (!boost::filesystem::exists(liberation_normal)) {
371                         liberation_normal = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf";
372                 }
373
374                 /* Add all the fonts to the subtitle content */
375                 BOOST_FOREACH (shared_ptr<Font> j, fonts) {
376                         _subtitle_asset->add_font (j->id(), j->file(FontFiles::NORMAL).get_value_or(liberation_normal));
377                 }
378
379                 if (dynamic_pointer_cast<dcp::InteropSubtitleAsset> (_subtitle_asset)) {
380                         boost::filesystem::path directory = _film->dir (_film->dcp_name ()) / _subtitle_asset->id ();
381                         boost::filesystem::create_directories (directory);
382                         _subtitle_asset->write (directory / ("sub_" + _subtitle_asset->id() + ".xml"));
383                 } else {
384
385                         /* All our assets should be the same length; use the picture asset length here
386                            as a reference to set the subtitle one.
387                         */
388                         dynamic_pointer_cast<dcp::SMPTESubtitleAsset>(_subtitle_asset)->set_intrinsic_duration (
389                                 reel_picture_asset->intrinsic_duration ()
390                                 );
391
392                         _subtitle_asset->write (
393                                 _film->dir (_film->dcp_name ()) / ("sub_" + _subtitle_asset->id() + ".mxf")
394                                 );
395                 }
396
397                 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
398                                    new dcp::ReelSubtitleAsset (
399                                            _subtitle_asset,
400                                            dcp::Fraction (_film->video_frame_rate(), 1),
401                                            reel_picture_asset->intrinsic_duration (),
402                                            0
403                                            )
404                                    ));
405         } else {
406                 /* We don't have a subtitle asset of our own; hopefully we have one to reference */
407                 BOOST_FOREACH (ReferencedReelAsset j, refs) {
408                         shared_ptr<dcp::ReelSubtitleAsset> k = dynamic_pointer_cast<dcp::ReelSubtitleAsset> (j.asset);
409                         if (k && j.period == _period) {
410                                 reel->add (k);
411                                 /* If we have a hash for this asset in the CPL, assume that it is correct */
412                                 if (k->hash()) {
413                                         k->asset_ref()->set_hash (k->hash().get());
414                                 }
415                         }
416                 }
417         }
418
419         return reel;
420 }
421
422 void
423 ReelWriter::calculate_digests (boost::function<void (float)> set_progress)
424 {
425         if (_picture_asset) {
426                 _picture_asset->hash (set_progress);
427         }
428
429         if (_sound_asset) {
430                 _sound_asset->hash (set_progress);
431         }
432 }
433
434 Frame
435 ReelWriter::start () const
436 {
437         return _period.from.frames_floor (_film->video_frame_rate());
438 }
439
440
441 void
442 ReelWriter::write (shared_ptr<const AudioBuffers> audio)
443 {
444         if (!_sound_asset_writer) {
445                 return;
446         }
447
448         if (audio) {
449                 _sound_asset_writer->write (audio->data(), audio->frames());
450         }
451
452         ++_total_written_audio_frames;
453 }
454
455 void
456 ReelWriter::write (PlayerSubtitles subs)
457 {
458         if (!_subtitle_asset) {
459                 string lang = _film->subtitle_language ();
460                 if (lang.empty ()) {
461                         lang = "Unknown";
462                 }
463                 if (_film->interop ()) {
464                         shared_ptr<dcp::InteropSubtitleAsset> s (new dcp::InteropSubtitleAsset ());
465                         s->set_movie_title (_film->name ());
466                         s->set_language (lang);
467                         s->set_reel_number ("1");
468                         _subtitle_asset = s;
469                 } else {
470                         shared_ptr<dcp::SMPTESubtitleAsset> s (new dcp::SMPTESubtitleAsset ());
471                         s->set_content_title_text (_film->name ());
472                         s->set_language (lang);
473                         s->set_edit_rate (dcp::Fraction (_film->video_frame_rate (), 1));
474                         s->set_reel_number (1);
475                         s->set_time_code_rate (_film->video_frame_rate ());
476                         s->set_start_time (dcp::Time ());
477                         _subtitle_asset = s;
478                 }
479         }
480
481         BOOST_FOREACH (dcp::SubtitleString i, subs.text) {
482                 i.set_in  (i.in()  - dcp::Time (_period.from.seconds(), i.in().tcr));
483                 i.set_out (i.out() - dcp::Time (_period.from.seconds(), i.out().tcr));
484                 _subtitle_asset->add (i);
485         }
486 }
487
488 bool
489 ReelWriter::existing_picture_frame_ok (FILE* asset_file, FILE* info_file) const
490 {
491         LOG_GENERAL ("Checking existing picture frame %1", _first_nonexistant_frame);
492
493         /* Read the data from the info file; for 3D we just check the left
494            frames until we find a good one.
495         */
496         dcp::FrameInfo const info = read_frame_info (info_file, _first_nonexistant_frame, _film->three_d () ? EYES_LEFT : EYES_BOTH);
497
498         bool ok = true;
499
500         /* Read the data from the asset and hash it */
501         dcpomatic_fseek (asset_file, info.offset, SEEK_SET);
502         Data data (info.size);
503         size_t const read = fread (data.data().get(), 1, data.size(), asset_file);
504         LOG_GENERAL ("Read %1 bytes of asset data; wanted %2", read, info.size);
505         if (read != static_cast<size_t> (data.size ())) {
506                 LOG_GENERAL ("Existing frame %1 is incomplete", _first_nonexistant_frame);
507                 ok = false;
508         } else {
509                 Digester digester;
510                 digester.add (data.data().get(), data.size());
511                 LOG_GENERAL ("Hash %1 vs %2", digester.get(), info.hash);
512                 if (digester.get() != info.hash) {
513                         LOG_GENERAL ("Existing frame %1 failed hash check", _first_nonexistant_frame);
514                         ok = false;
515                 }
516         }
517
518         return ok;
519 }