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