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