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