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