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