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