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