Various KDM and encryption fixes.
[dcpomatic.git] / src / lib / writer.cc
1 /*
2     Copyright (C) 2012 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/picture_asset.h>
23 #include <libdcp/sound_asset.h>
24 #include <libdcp/picture_frame.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
40 #include "i18n.h"
41
42 using std::make_pair;
43 using std::pair;
44 using std::string;
45 using std::ifstream;
46 using std::list;
47 using std::cout;
48 using boost::shared_ptr;
49
50 int const Writer::_maximum_frames_in_memory = 8;
51
52 Writer::Writer (shared_ptr<const Film> f, shared_ptr<Job> j)
53         : _film (f)
54         , _job (j)
55         , _first_nonexistant_frame (0)
56         , _thread (0)
57         , _finish (false)
58         , _queued_full_in_memory (0)
59         , _last_written_frame (-1)
60         , _last_written_eyes (EYES_RIGHT)
61         , _full_written (0)
62         , _fake_written (0)
63         , _repeat_written (0)
64         , _pushed_to_disk (0)
65 {
66         /* Remove any old DCP */
67         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
68         
69         check_existing_picture_mxf ();
70         
71         /* Create our picture asset in a subdirectory, named according to those
72            film's parameters which affect the video output.  We will hard-link
73            it into the DCP later.
74         */
75
76         if (_film->three_d ()) {
77                 _picture_asset.reset (
78                         new libdcp::StereoPictureAsset (
79                                 _film->internal_video_mxf_dir (),
80                                 _film->internal_video_mxf_filename (),
81                                 _film->video_frame_rate (),
82                                 _film->container()->size (_film->full_frame ())
83                                 )
84                         );
85                 
86         } else {
87                 _picture_asset.reset (
88                         new libdcp::MonoPictureAsset (
89                                 _film->internal_video_mxf_dir (),
90                                 _film->internal_video_mxf_filename (),
91                                 _film->video_frame_rate (),
92                                 _film->container()->size (_film->full_frame ())
93                                 )
94                         );
95
96         }
97
98         if (_film->encrypted ()) {
99                 _picture_asset->set_key (_film->key ());
100         }
101         
102         _picture_asset_writer = _picture_asset->start_write (_first_nonexistant_frame > 0, _film->interop ());
103         
104         _sound_asset.reset (
105                 new libdcp::SoundAsset (
106                         _film->dir (_film->dcp_name()),
107                         _film->audio_mxf_filename (),
108                         _film->video_frame_rate (),
109                         _film->audio_channels (),
110                         _film->audio_frame_rate ()
111                         )
112                 );
113
114         if (_film->encrypted ()) {
115                 _sound_asset->set_key (_film->key ());
116         }
117         
118         _sound_asset_writer = _sound_asset->start_write (_film->interop ());
119
120         _thread = new boost::thread (boost::bind (&Writer::thread, this));
121
122         _job->descend (0.9);
123 }
124
125 void
126 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
127 {
128         boost::mutex::scoped_lock lock (_mutex);
129
130         QueueItem qi;
131         qi.type = QueueItem::FULL;
132         qi.encoded = encoded;
133         qi.frame = frame;
134
135         if (_film->three_d() && eyes == EYES_BOTH) {
136                 /* 2D material in a 3D DCP; fake the 3D */
137                 qi.eyes = EYES_LEFT;
138                 _queue.push_back (qi);
139                 ++_queued_full_in_memory;
140                 qi.eyes = EYES_RIGHT;
141                 _queue.push_back (qi);
142                 ++_queued_full_in_memory;
143         } else {
144                 qi.eyes = eyes;
145                 _queue.push_back (qi);
146                 ++_queued_full_in_memory;
147         }
148         
149         _condition.notify_all ();
150 }
151
152 void
153 Writer::fake_write (int frame, Eyes eyes)
154 {
155         boost::mutex::scoped_lock lock (_mutex);
156
157         ifstream ifi (_film->info_path (frame, eyes).c_str());
158         libdcp::FrameInfo info (ifi);
159         
160         QueueItem qi;
161         qi.type = QueueItem::FAKE;
162         qi.size = info.size;
163         qi.frame = frame;
164         if (_film->three_d() && eyes == EYES_BOTH) {
165                 qi.eyes = EYES_LEFT;
166                 _queue.push_back (qi);
167                 qi.eyes = EYES_RIGHT;
168                 _queue.push_back (qi);
169         } else {
170                 qi.eyes = eyes;
171                 _queue.push_back (qi);
172         }
173
174         _condition.notify_all ();
175 }
176
177 /** This method is not thread safe */
178 void
179 Writer::write (shared_ptr<const AudioBuffers> audio)
180 {
181         _sound_asset_writer->write (audio->data(), audio->frames());
182 }
183
184 /** This must be called from Writer::thread() with an appropriate lock held,
185  *  and with _queue sorted.
186  */
187 bool
188 Writer::have_sequenced_image_at_queue_head () const
189 {
190         if (_queue.empty ()) {
191                 return false;
192         }
193
194         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
195
196         if (_queue.front().eyes == EYES_BOTH) {
197                 /* 2D */
198                 return _queue.front().frame == (_last_written_frame + 1);
199         }
200
201         /* 3D */
202
203         if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
204                 return true;
205         }
206
207         if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
208                 return true;
209         }
210
211         return false;
212 }
213
214 void
215 Writer::thread ()
216 try
217 {
218         while (1)
219         {
220                 boost::mutex::scoped_lock lock (_mutex);
221
222                 while (1) {
223                         
224                         _queue.sort ();
225                         
226                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
227                                 break;
228                         }
229
230                         TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
231                         _condition.wait (lock);
232                         TIMING (N_("writer wakes with a queue of %1"), _queue.size());
233                 }
234
235                 if (_finish && _queue.empty()) {
236                         return;
237                 }
238
239                 /* Write any frames that we can write; i.e. those that are in sequence */
240                 while (have_sequenced_image_at_queue_head ()) {
241                         QueueItem qi = _queue.front ();
242                         _queue.pop_front ();
243                         if (qi.type == QueueItem::FULL && qi.encoded) {
244                                 --_queued_full_in_memory;
245                         }
246
247                         lock.unlock ();
248                         switch (qi.type) {
249                         case QueueItem::FULL:
250                         {
251                                 _film->log()->log (String::compose (N_("Writer FULL-writes %1 to MXF"), qi.frame));
252                                 if (!qi.encoded) {
253                                         qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
254                                 }
255
256                                 libdcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size());
257                                 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
258                                 _last_written[qi.eyes] = qi.encoded;
259                                 ++_full_written;
260                                 break;
261                         }
262                         case QueueItem::FAKE:
263                                 _film->log()->log (String::compose (N_("Writer FAKE-writes %1 to MXF"), qi.frame));
264                                 _picture_asset_writer->fake_write (qi.size);
265                                 _last_written[qi.eyes].reset ();
266                                 ++_fake_written;
267                                 break;
268                         case QueueItem::REPEAT:
269                         {
270                                 _film->log()->log (String::compose (N_("Writer REPEAT-writes %1 to MXF"), qi.frame));
271                                 libdcp::FrameInfo fin = _picture_asset_writer->write (
272                                         _last_written[qi.eyes]->data(),
273                                         _last_written[qi.eyes]->size()
274                                         );
275                                 
276                                 _last_written[qi.eyes]->write_info (_film, qi.frame, qi.eyes, fin);
277                                 ++_repeat_written;
278                                 break;
279                         }
280                         }
281                         lock.lock ();
282
283                         _last_written_frame = qi.frame;
284                         _last_written_eyes = qi.eyes;
285                         
286                         if (_film->length()) {
287                                 _job->set_progress (
288                                         float (_full_written + _fake_written + _repeat_written) / _film->time_to_video_frames (_film->length())
289                                         );
290                         }
291                 }
292
293                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
294                         /* Too many frames in memory which can't yet be written to the stream.
295                            Write some FULL frames to disk.
296                         */
297
298                         /* Find one */
299                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
300                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
301                                 ++i;
302                         }
303
304                         assert (i != _queue.rend());
305                         QueueItem qi = *i;
306
307                         ++_pushed_to_disk;
308                         
309                         lock.unlock ();
310
311                         _film->log()->log (
312                                 String::compose (
313                                         "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
314                                         _last_written_frame + 1,
315                                         _last_written_eyes, qi.frame)
316                                 );
317                         
318                         qi.encoded->write (_film, qi.frame, qi.eyes);
319                         lock.lock ();
320                         qi.encoded.reset ();
321                         --_queued_full_in_memory;
322                 }
323         }
324 }
325 catch (...)
326 {
327         store_current ();
328 }
329
330 void
331 Writer::finish ()
332 {
333         if (!_thread) {
334                 return;
335         }
336         
337         boost::mutex::scoped_lock lock (_mutex);
338         _finish = true;
339         _condition.notify_all ();
340         lock.unlock ();
341
342         _thread->join ();
343         if (thrown ()) {
344                 rethrow ();
345         }
346         
347         delete _thread;
348         _thread = 0;
349
350         _picture_asset_writer->finalize ();
351         _sound_asset_writer->finalize ();
352         
353         int const frames = _last_written_frame + 1;
354
355         _picture_asset->set_duration (frames);
356
357         /* Hard-link the video MXF into the DCP */
358
359         boost::filesystem::path from;
360         from /= _film->internal_video_mxf_dir();
361         from /= _film->internal_video_mxf_filename();
362         
363         boost::filesystem::path to;
364         to /= _film->dir (_film->dcp_name());
365         to /= _film->video_mxf_filename ();
366
367         boost::system::error_code ec;
368         boost::filesystem::create_hard_link (from, to, ec);
369         if (ec) {
370                 /* hard link failed; copy instead */
371                 boost::filesystem::copy_file (from, to);
372                 _film->log()->log ("Hard-link failed; fell back to copying");
373         }
374
375         /* And update the asset */
376
377         _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
378         _picture_asset->set_file_name (_film->video_mxf_filename ());
379         _sound_asset->set_duration (frames);
380         
381         libdcp::DCP dcp (_film->dir (_film->dcp_name()));
382
383         shared_ptr<libdcp::CPL> cpl (
384                 new libdcp::CPL (
385                         _film->dir (_film->dcp_name()),
386                         _film->dcp_name(),
387                         _film->dcp_content_type()->libdcp_kind (),
388                         frames,
389                         _film->video_frame_rate ()
390                         )
391                 );
392         
393         dcp.add_cpl (cpl);
394
395         cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
396                                                          _picture_asset,
397                                                          _sound_asset,
398                                                          shared_ptr<libdcp::SubtitleAsset> ()
399                                                          )
400                                ));
401
402         /* Compute the digests for the assets now so that we can keep track of progress.
403            We did _job->descend (0.9) in our constructor */
404         _job->ascend ();
405
406         _job->descend (0.1);
407         _picture_asset->compute_digest (boost::bind (&Job::set_progress, _job.get(), _1));
408         _job->ascend ();
409
410         _job->descend (0.1);
411         _sound_asset->compute_digest (boost::bind (&Job::set_progress, _job.get(), _1));
412         _job->ascend ();
413
414         libdcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
415         meta.set_issue_date_now ();
416         dcp.write_xml (_film->interop (), meta);
417
418         _film->log()->log (String::compose (N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT; %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk));
419 }
420
421 /** Tell the writer that frame `f' should be a repeat of the frame before it */
422 void
423 Writer::repeat (int f, Eyes e)
424 {
425         boost::mutex::scoped_lock lock (_mutex);
426
427         QueueItem qi;
428         qi.type = QueueItem::REPEAT;
429         qi.frame = f;
430         if (_film->three_d() && e == EYES_BOTH) {
431                 qi.eyes = EYES_LEFT;
432                 _queue.push_back (qi);
433                 qi.eyes = EYES_RIGHT;
434                 _queue.push_back (qi);
435         } else {
436                 qi.eyes = e;
437                 _queue.push_back (qi);
438         }
439
440         _condition.notify_all ();
441 }
442
443 bool
444 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
445 {
446         /* Read the frame info as written */
447         ifstream ifi (_film->info_path (f, eyes).c_str());
448         libdcp::FrameInfo info (ifi);
449         if (info.size == 0) {
450                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
451                 return false;
452         }
453         
454         /* Read the data from the MXF and hash it */
455         fseek (mxf, info.offset, SEEK_SET);
456         EncodedData data (info.size);
457         size_t const read = fread (data.data(), 1, data.size(), mxf);
458         if (read != static_cast<size_t> (data.size ())) {
459                 _film->log()->log (String::compose ("Existing frame %1 is incomplete", f));
460                 return false;
461         }
462         
463         string const existing_hash = md5_digest (data.data(), data.size());
464         if (existing_hash != info.hash) {
465                 _film->log()->log (String::compose ("Existing frame %1 failed hash check", f));
466                 return false;
467         }
468
469         return true;
470 }
471
472 void
473 Writer::check_existing_picture_mxf ()
474 {
475         /* Try to open the existing MXF */
476         boost::filesystem::path p;
477         p /= _film->internal_video_mxf_dir ();
478         p /= _film->internal_video_mxf_filename ();
479         FILE* mxf = fopen (p.string().c_str(), "rb");
480         if (!mxf) {
481                 _film->log()->log (String::compose ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno));
482                 return;
483         }
484
485         while (1) {
486
487                 if (_film->three_d ()) {
488                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
489                                 break;
490                         }
491                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
492                                 break;
493                         }
494                 } else {
495                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
496                                 break;
497                         }
498                 }
499
500                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
501                 ++_first_nonexistant_frame;
502         }
503
504         fclose (mxf);
505 }
506
507 /** @param frame Frame index.
508  *  @return true if we can fake-write this frame.
509  */
510 bool
511 Writer::can_fake_write (int frame) const
512 {
513         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
514            parameters in the MXF writer.
515         */
516         return (frame != 0 && frame < _first_nonexistant_frame);
517 }
518
519 bool
520 operator< (QueueItem const & a, QueueItem const & b)
521 {
522         if (a.frame != b.frame) {
523                 return a.frame < b.frame;
524         }
525
526         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
527 }
528
529 bool
530 operator== (QueueItem const & a, QueueItem const & b)
531 {
532         return a.frame == b.frame && a.eyes == b.eyes;
533 }