Use make_shared<>.
[dcpomatic.git] / src / lib / reel_writer.cc
1 /*
2     Copyright (C) 2012-2015 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 #include <boost/make_shared.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::make_shared;
59 using boost::optional;
60 using boost::dynamic_pointer_cast;
61 using dcp::Data;
62
63 int const ReelWriter::_info_size = 48;
64
65 ReelWriter::ReelWriter (shared_ptr<const Film> film, DCPTimePeriod period, shared_ptr<Job> job)
66         : _film (film)
67         , _period (period)
68         , _first_nonexistant_frame (0)
69         , _last_written_video_frame (-1)
70         , _last_written_eyes (EYES_RIGHT)
71         , _total_written_audio_frames (0)
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),
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);
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                 audio_to /= audio_asset_filename (_sound_asset);
292
293                 boost::system::error_code ec;
294                 boost::filesystem::rename (_film->file (audio_asset_filename (_sound_asset)), audio_to, ec);
295                 if (ec) {
296                         throw FileError (
297                                 String::compose (_("could not move audio asset into the DCP (%1)"), ec.value ()), audio_asset_filename (_sound_asset)
298                                 );
299                 }
300
301                 _sound_asset->set_file (audio_to);
302         }
303 }
304
305 shared_ptr<dcp::Reel>
306 ReelWriter::create_reel (list<ReferencedReelAsset> const & refs, list<shared_ptr<Font> > const & fonts)
307 {
308         shared_ptr<dcp::Reel> reel = make_shared<dcp::Reel> ();
309
310         shared_ptr<dcp::ReelPictureAsset> reel_picture_asset;
311
312         if (_picture_asset) {
313                 /* We have made a picture asset of our own.  Put it into the reel */
314                 shared_ptr<dcp::MonoPictureAsset> mono = dynamic_pointer_cast<dcp::MonoPictureAsset> (_picture_asset);
315                 if (mono) {
316                         reel_picture_asset.reset (new dcp::ReelMonoPictureAsset (mono, 0));
317                 }
318
319                 shared_ptr<dcp::StereoPictureAsset> stereo = dynamic_pointer_cast<dcp::StereoPictureAsset> (_picture_asset);
320                 if (stereo) {
321                         reel_picture_asset.reset (new dcp::ReelStereoPictureAsset (stereo, 0));
322                 }
323         } else {
324                 /* We don't have a picture asset of our own; hopefully we have one to reference */
325                 BOOST_FOREACH (ReferencedReelAsset j, refs) {
326                         shared_ptr<dcp::ReelPictureAsset> k = dynamic_pointer_cast<dcp::ReelPictureAsset> (j.asset);
327                         if (k && j.period == _period) {
328                                 reel_picture_asset = k;
329                         }
330                 }
331         }
332
333         reel->add (reel_picture_asset);
334         /* If we have a hash for this asset in the CPL, assume that it is correct */
335         if (reel_picture_asset->hash()) {
336                 reel_picture_asset->asset_ref()->set_hash (reel_picture_asset->hash().get());
337         }
338
339         if (_sound_asset) {
340                 /* We have made a sound asset of our own.  Put it into the reel */
341                 reel->add (make_shared<dcp::ReelSoundAsset> (_sound_asset, 0));
342         } else {
343                 /* We don't have a sound asset of our own; hopefully we have one to reference */
344                 BOOST_FOREACH (ReferencedReelAsset j, refs) {
345                         shared_ptr<dcp::ReelSoundAsset> k = dynamic_pointer_cast<dcp::ReelSoundAsset> (j.asset);
346                         if (k && j.period == _period) {
347                                 reel->add (k);
348                                 /* If we have a hash for this asset in the CPL, assume that it is correct */
349                                 if (k->hash()) {
350                                         k->asset_ref()->set_hash (k->hash().get());
351                                 }
352                         }
353                 }
354         }
355
356         if (_subtitle_asset) {
357
358                 boost::filesystem::path liberation_normal;
359                 try {
360                         liberation_normal = shared_path() / "LiberationSans-Regular.ttf";
361                         if (!boost::filesystem::exists (liberation_normal)) {
362                                 /* Hack for unit tests */
363                                 liberation_normal = shared_path() / "fonts" / "LiberationSans-Regular.ttf";
364                         }
365                 } catch (boost::filesystem::filesystem_error& e) {
366
367                 }
368
369                 if (!boost::filesystem::exists(liberation_normal)) {
370                         liberation_normal = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf";
371                 }
372
373                 /* Add all the fonts to the subtitle content */
374                 BOOST_FOREACH (shared_ptr<Font> j, fonts) {
375                         _subtitle_asset->add_font (j->id(), j->file(FontFiles::NORMAL).get_value_or(liberation_normal));
376                 }
377
378                 if (dynamic_pointer_cast<dcp::InteropSubtitleAsset> (_subtitle_asset)) {
379                         boost::filesystem::path directory = _film->dir (_film->dcp_name ()) / _subtitle_asset->id ();
380                         boost::filesystem::create_directories (directory);
381                         _subtitle_asset->write (directory / ("sub_" + _subtitle_asset->id() + ".xml"));
382                 } else {
383
384                         /* All our assets should be the same length; use the picture asset length here
385                            as a reference to set the subtitle one.
386                         */
387                         dynamic_pointer_cast<dcp::SMPTESubtitleAsset>(_subtitle_asset)->set_intrinsic_duration (
388                                 reel_picture_asset->intrinsic_duration ()
389                                 );
390
391                         _subtitle_asset->write (
392                                 _film->dir (_film->dcp_name ()) / ("sub_" + _subtitle_asset->id() + ".mxf")
393                                 );
394                 }
395
396                 reel->add (shared_ptr<dcp::ReelSubtitleAsset> (
397                                    new dcp::ReelSubtitleAsset (
398                                            _subtitle_asset,
399                                            dcp::Fraction (_film->video_frame_rate(), 1),
400                                            reel_picture_asset->intrinsic_duration (),
401                                            0
402                                            )
403                                    ));
404         } else {
405                 /* We don't have a subtitle asset of our own; hopefully we have one to reference */
406                 BOOST_FOREACH (ReferencedReelAsset j, refs) {
407                         shared_ptr<dcp::ReelSubtitleAsset> k = dynamic_pointer_cast<dcp::ReelSubtitleAsset> (j.asset);
408                         if (k && j.period == _period) {
409                                 reel->add (k);
410                                 /* If we have a hash for this asset in the CPL, assume that it is correct */
411                                 if (k->hash()) {
412                                         k->asset_ref()->set_hash (k->hash().get());
413                                 }
414                         }
415                 }
416         }
417
418         return reel;
419 }
420
421 void
422 ReelWriter::calculate_digests (shared_ptr<Job> job)
423 {
424         job->sub (_("Computing image digest"));
425         if (_picture_asset) {
426                 _picture_asset->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
427         }
428
429         if (_sound_asset) {
430                 job->sub (_("Computing audio digest"));
431                 _sound_asset->hash (boost::bind (&Job::set_progress, job.get(), _1, false));
432         }
433 }
434
435 Frame
436 ReelWriter::start () const
437 {
438         return _period.from.frames_floor (_film->video_frame_rate());
439 }
440
441
442 void
443 ReelWriter::write (shared_ptr<const AudioBuffers> audio)
444 {
445         if (!_sound_asset_writer) {
446                 return;
447         }
448
449         if (audio) {
450                 _sound_asset_writer->write (audio->data(), audio->frames());
451         }
452
453         ++_total_written_audio_frames;
454 }
455
456 void
457 ReelWriter::write (PlayerSubtitles subs)
458 {
459         if (!_subtitle_asset) {
460                 string lang = _film->subtitle_language ();
461                 if (lang.empty ()) {
462                         lang = "Unknown";
463                 }
464                 if (_film->interop ()) {
465                         shared_ptr<dcp::InteropSubtitleAsset> s = make_shared<dcp::InteropSubtitleAsset> ();
466                         s->set_movie_title (_film->name ());
467                         s->set_language (lang);
468                         s->set_reel_number ("1");
469                         _subtitle_asset = s;
470                 } else {
471                         shared_ptr<dcp::SMPTESubtitleAsset> s = make_shared<dcp::SMPTESubtitleAsset> ();
472                         s->set_content_title_text (_film->name ());
473                         s->set_language (lang);
474                         s->set_edit_rate (dcp::Fraction (_film->video_frame_rate (), 1));
475                         s->set_reel_number (1);
476                         s->set_time_code_rate (_film->video_frame_rate ());
477                         s->set_start_time (dcp::Time ());
478                         _subtitle_asset = s;
479                 }
480         }
481
482         BOOST_FOREACH (dcp::SubtitleString i, subs.text) {
483                 i.set_in  (i.in()  - dcp::Time (_period.from.seconds(), i.in().tcr));
484                 i.set_out (i.out() - dcp::Time (_period.from.seconds(), i.out().tcr));
485                 _subtitle_asset->add (i);
486         }
487 }
488
489 bool
490 ReelWriter::existing_picture_frame_ok (FILE* asset_file, FILE* info_file) const
491 {
492         LOG_GENERAL ("Checking existing picture frame %1", _first_nonexistant_frame);
493
494         /* Read the data from the info file; for 3D we just check the left
495            frames until we find a good one.
496         */
497         dcp::FrameInfo const info = read_frame_info (info_file, _first_nonexistant_frame, _film->three_d () ? EYES_LEFT : EYES_BOTH);
498
499         bool ok = true;
500
501         /* Read the data from the asset and hash it */
502         dcpomatic_fseek (asset_file, info.offset, SEEK_SET);
503         Data data (info.size);
504         size_t const read = fread (data.data().get(), 1, data.size(), asset_file);
505         LOG_GENERAL ("Read %1 bytes of asset data; wanted %2", read, info.size);
506         if (read != static_cast<size_t> (data.size ())) {
507                 LOG_GENERAL ("Existing frame %1 is incomplete", _first_nonexistant_frame);
508                 ok = false;
509         } else {
510                 Digester digester;
511                 digester.add (data.data().get(), data.size());
512                 LOG_GENERAL ("Hash %1 vs %2", digester.get(), info.hash);
513                 if (digester.get() != info.hash) {
514                         LOG_GENERAL ("Existing frame %1 failed hash check", _first_nonexistant_frame);
515                         ok = false;
516                 }
517         }
518
519         return ok;
520 }