103ac2ba135b118f63d839ad80354ff44c4b688f
[dcpomatic.git] / src / lib / writer.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <fstream>
21 #include <cerrno>
22 #include <libdcp/mono_picture_asset.h>
23 #include <libdcp/stereo_picture_asset.h>
24 #include <libdcp/sound_asset.h>
25 #include <libdcp/reel.h>
26 #include <libdcp/dcp.h>
27 #include <libdcp/cpl.h>
28 #include "writer.h"
29 #include "compose.hpp"
30 #include "film.h"
31 #include "ratio.h"
32 #include "log.h"
33 #include "dcp_video_frame.h"
34 #include "dcp_content_type.h"
35 #include "player.h"
36 #include "audio_mapping.h"
37 #include "config.h"
38 #include "job.h"
39
40 #include "i18n.h"
41
42 using std::make_pair;
43 using std::pair;
44 using std::string;
45 using std::ifstream;
46 using std::list;
47 using std::cout;
48 using boost::shared_ptr;
49 using boost::weak_ptr;
50
51 int const Writer::_maximum_frames_in_memory = 8;
52
53 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
54         : _film (f)
55         , _job (j)
56         , _first_nonexistant_frame (0)
57         , _thread (0)
58         , _finish (false)
59         , _queued_full_in_memory (0)
60         , _last_written_frame (-1)
61         , _last_written_eyes (EYES_RIGHT)
62         , _full_written (0)
63         , _fake_written (0)
64         , _repeat_written (0)
65         , _pushed_to_disk (0)
66 {
67         /* Remove any old DCP */
68         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
69
70         shared_ptr<Job> job = _job.lock ();
71         assert (job);
72
73         job->sub (_("Checking existing image data"));
74         check_existing_picture_mxf ();
75
76         /* Create our picture asset in a subdirectory, named according to those
77            film's parameters which affect the video output.  We will hard-link
78            it into the DCP later.
79         */
80
81         if (_film->three_d ()) {
82                 _picture_asset.reset (new libdcp::StereoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
83         } else {
84                 _picture_asset.reset (new libdcp::MonoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
85         }
86
87         _picture_asset->set_edit_rate (_film->video_frame_rate ());
88         _picture_asset->set_size (fit_ratio_within (_film->container()->ratio(), _film->full_frame ()));
89
90         if (_film->encrypted ()) {
91                 _picture_asset->set_key (_film->key ());
92         }
93         
94         _picture_asset_writer = _picture_asset->start_write (_first_nonexistant_frame > 0);
95         
96         _sound_asset.reset (new libdcp::SoundAsset (_film->dir (_film->dcp_name()), _film->audio_mxf_filename ()));
97         _sound_asset->set_edit_rate (_film->video_frame_rate ());
98         _sound_asset->set_channels (_film->audio_channels ());
99         _sound_asset->set_sampling_rate (_film->audio_frame_rate ());
100
101         if (_film->encrypted ()) {
102                 _sound_asset->set_key (_film->key ());
103         }
104         
105         _sound_asset_writer = _sound_asset->start_write ();
106
107         _thread = new boost::thread (boost::bind (&Writer::thread, this));
108
109         job->sub (_("Encoding image data"));
110 }
111
112 void
113 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
114 {
115         boost::mutex::scoped_lock lock (_mutex);
116
117         QueueItem qi;
118         qi.type = QueueItem::FULL;
119         qi.encoded = encoded;
120         qi.frame = frame;
121
122         if (_film->three_d() && eyes == EYES_BOTH) {
123                 /* 2D material in a 3D DCP; fake the 3D */
124                 qi.eyes = EYES_LEFT;
125                 _queue.push_back (qi);
126                 ++_queued_full_in_memory;
127                 qi.eyes = EYES_RIGHT;
128                 _queue.push_back (qi);
129                 ++_queued_full_in_memory;
130         } else {
131                 qi.eyes = eyes;
132                 _queue.push_back (qi);
133                 ++_queued_full_in_memory;
134         }
135         
136         _condition.notify_all ();
137 }
138
139 void
140 Writer::fake_write (int frame, Eyes eyes)
141 {
142         boost::mutex::scoped_lock lock (_mutex);
143
144         ifstream ifi (_film->info_path (frame, eyes).string().c_str());
145         libdcp::FrameInfo info (ifi);
146         
147         QueueItem qi;
148         qi.type = QueueItem::FAKE;
149         qi.size = info.size;
150         qi.frame = frame;
151         if (_film->three_d() && eyes == EYES_BOTH) {
152                 qi.eyes = EYES_LEFT;
153                 _queue.push_back (qi);
154                 qi.eyes = EYES_RIGHT;
155                 _queue.push_back (qi);
156         } else {
157                 qi.eyes = eyes;
158                 _queue.push_back (qi);
159         }
160
161         _condition.notify_all ();
162 }
163
164 /** This method is not thread safe */
165 void
166 Writer::write (shared_ptr<const AudioBuffers> audio)
167 {
168         _sound_asset_writer->write (audio->data(), audio->frames());
169 }
170
171 /** This must be called from Writer::thread() with an appropriate lock held,
172  *  and with _queue sorted.
173  */
174 bool
175 Writer::have_sequenced_image_at_queue_head () const
176 {
177         if (_queue.empty ()) {
178                 return false;
179         }
180
181         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
182
183         if (_queue.front().eyes == EYES_BOTH) {
184                 /* 2D */
185                 return _queue.front().frame == (_last_written_frame + 1);
186         }
187
188         /* 3D */
189
190         if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
191                 return true;
192         }
193
194         if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
195                 return true;
196         }
197
198         return false;
199 }
200
201 void
202 Writer::thread ()
203 try
204 {
205         while (1)
206         {
207                 boost::mutex::scoped_lock lock (_mutex);
208
209                 while (1) {
210                         
211                         _queue.sort ();
212                         
213                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
214                                 break;
215                         }
216
217                         TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
218                         _condition.wait (lock);
219                         TIMING (N_("writer wakes with a queue of %1"), _queue.size());
220                 }
221
222                 if (_finish && _queue.empty()) {
223                         return;
224                 }
225
226                 /* Write any frames that we can write; i.e. those that are in sequence */
227                 while (have_sequenced_image_at_queue_head ()) {
228                         QueueItem qi = _queue.front ();
229                         _queue.pop_front ();
230                         if (qi.type == QueueItem::FULL && qi.encoded) {
231                                 --_queued_full_in_memory;
232                         }
233
234                         lock.unlock ();
235                         switch (qi.type) {
236                         case QueueItem::FULL:
237                         {
238                                 _film->log()->log (String::compose (N_("Writer FULL-writes %1 to MXF"), qi.frame));
239                                 if (!qi.encoded) {
240                                         qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
241                                 }
242
243                                 libdcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size());
244                                 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
245                                 _last_written[qi.eyes] = qi.encoded;
246                                 ++_full_written;
247                                 break;
248                         }
249                         case QueueItem::FAKE:
250                                 _film->log()->log (String::compose (N_("Writer FAKE-writes %1 to MXF"), qi.frame));
251                                 _picture_asset_writer->fake_write (qi.size);
252                                 _last_written[qi.eyes].reset ();
253                                 ++_fake_written;
254                                 break;
255                         case QueueItem::REPEAT:
256                         {
257                                 _film->log()->log (String::compose (N_("Writer REPEAT-writes %1 to MXF"), qi.frame));
258                                 libdcp::FrameInfo fin = _picture_asset_writer->write (
259                                         _last_written[qi.eyes]->data(),
260                                         _last_written[qi.eyes]->size()
261                                         );
262                                 
263                                 _last_written[qi.eyes]->write_info (_film, qi.frame, qi.eyes, fin);
264                                 ++_repeat_written;
265                                 break;
266                         }
267                         }
268                         lock.lock ();
269
270                         _last_written_frame = qi.frame;
271                         _last_written_eyes = qi.eyes;
272                         
273                         if (_film->length()) {
274                                 shared_ptr<Job> job = _job.lock ();
275                                 assert (job);
276                                 job->set_progress (
277                                         float (_full_written + _fake_written + _repeat_written) / _film->time_to_video_frames (_film->length())
278                                         );
279                         }
280                 }
281
282                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
283                         /* Too many frames in memory which can't yet be written to the stream.
284                            Write some FULL frames to disk.
285                         */
286
287                         /* Find one */
288                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
289                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
290                                 ++i;
291                         }
292
293                         assert (i != _queue.rend());
294                         QueueItem qi = *i;
295
296                         ++_pushed_to_disk;
297                         
298                         lock.unlock ();
299
300                         _film->log()->log (
301                                 String::compose (
302                                         "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
303                                         _last_written_frame + 1,
304                                         _last_written_eyes, qi.frame)
305                                 );
306                         
307                         qi.encoded->write (_film, qi.frame, qi.eyes);
308                         lock.lock ();
309                         qi.encoded.reset ();
310                         --_queued_full_in_memory;
311                 }
312         }
313 }
314 catch (...)
315 {
316         store_current ();
317 }
318
319 void
320 Writer::finish ()
321 {
322         if (!_thread) {
323                 return;
324         }
325         
326         boost::mutex::scoped_lock lock (_mutex);
327         _finish = true;
328         _condition.notify_all ();
329         lock.unlock ();
330
331         _thread->join ();
332         if (thrown ()) {
333                 rethrow ();
334         }
335         
336         delete _thread;
337         _thread = 0;
338
339         _picture_asset_writer->finalize ();
340         _sound_asset_writer->finalize ();
341         
342         int const frames = _last_written_frame + 1;
343
344         _picture_asset->set_duration (frames);
345
346         /* Hard-link the video MXF into the DCP */
347
348         boost::filesystem::path from;
349         from /= _film->internal_video_mxf_dir();
350         from /= _film->internal_video_mxf_filename();
351         
352         boost::filesystem::path to;
353         to /= _film->dir (_film->dcp_name());
354         to /= _film->video_mxf_filename ();
355
356         boost::system::error_code ec;
357         boost::filesystem::create_hard_link (from, to, ec);
358         if (ec) {
359                 /* hard link failed; copy instead */
360                 boost::filesystem::copy_file (from, to);
361                 _film->log()->log ("Hard-link failed; fell back to copying");
362         }
363
364         /* And update the asset */
365
366         _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
367         _picture_asset->set_file_name (_film->video_mxf_filename ());
368         _sound_asset->set_duration (frames);
369         
370         libdcp::DCP dcp (_film->dir (_film->dcp_name()));
371
372         shared_ptr<libdcp::CPL> cpl (
373                 new libdcp::CPL (
374                         _film->dir (_film->dcp_name()),
375                         _film->dcp_name(),
376                         _film->dcp_content_type()->libdcp_kind (),
377                         frames,
378                         _film->video_frame_rate ()
379                         )
380                 );
381         
382         dcp.add_cpl (cpl);
383
384         cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
385                                                          _picture_asset,
386                                                          _sound_asset,
387                                                          shared_ptr<libdcp::SubtitleAsset> ()
388                                                          )
389                                ));
390
391         shared_ptr<Job> job = _job.lock ();
392         assert (job);
393
394         job->sub (_("Computing image digest"));
395         _picture_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
396
397         job->sub (_("Computing audio digest"));
398         _sound_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
399
400         libdcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
401         meta.set_issue_date_now ();
402         dcp.write_xml (_film->interop (), meta, make_signer ());
403
404         _film->log()->log (String::compose (N_("Wrote %1 FULL, %2 FAKE, %3 REPEAT; %4 pushed to disk"), _full_written, _fake_written, _repeat_written, _pushed_to_disk));
405 }
406
407 /** Tell the writer that frame `f' should be a repeat of the frame before it */
408 void
409 Writer::repeat (int f, Eyes e)
410 {
411         boost::mutex::scoped_lock lock (_mutex);
412
413         QueueItem qi;
414         qi.type = QueueItem::REPEAT;
415         qi.frame = f;
416         if (_film->three_d() && e == EYES_BOTH) {
417                 qi.eyes = EYES_LEFT;
418                 _queue.push_back (qi);
419                 qi.eyes = EYES_RIGHT;
420                 _queue.push_back (qi);
421         } else {
422                 qi.eyes = e;
423                 _queue.push_back (qi);
424         }
425
426         _condition.notify_all ();
427 }
428
429 bool
430 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
431 {
432         /* Read the frame info as written */
433         ifstream ifi (_film->info_path (f, eyes).string().c_str());
434         libdcp::FrameInfo info (ifi);
435         if (info.size == 0) {
436                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
437                 return false;
438         }
439         
440         /* Read the data from the MXF and hash it */
441 #ifdef DCPOMATIC_WINDOWS
442         _fseeki64 (mxf, info.offset, SEEK_SET);
443 #else   
444         fseek (mxf, info.offset, SEEK_SET);
445 #endif  
446         EncodedData data (info.size);
447         size_t const read = fread (data.data(), 1, data.size(), mxf);
448         if (read != static_cast<size_t> (data.size ())) {
449                 _film->log()->log (String::compose ("Existing frame %1 is incomplete", f));
450                 return false;
451         }
452         
453         string const existing_hash = md5_digest (data.data(), data.size());
454         if (existing_hash != info.hash) {
455                 _film->log()->log (String::compose ("Existing frame %1 failed hash check", f));
456                 return false;
457         }
458
459         return true;
460 }
461
462 void
463 Writer::check_existing_picture_mxf ()
464 {
465         /* Try to open the existing MXF */
466         boost::filesystem::path p;
467         p /= _film->internal_video_mxf_dir ();
468         p /= _film->internal_video_mxf_filename ();
469         FILE* mxf = fopen (p.string().c_str(), "rb");
470         if (!mxf) {
471                 _film->log()->log (String::compose ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno));
472                 return;
473         }
474
475         int N = 0;
476         for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
477                 ++N;
478         }
479
480         while (1) {
481
482                 shared_ptr<Job> job = _job.lock ();
483                 assert (job);
484
485                 job->set_progress (float (_first_nonexistant_frame) / N);
486
487                 if (_film->three_d ()) {
488                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
489                                 break;
490                         }
491                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
492                                 break;
493                         }
494                 } else {
495                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
496                                 break;
497                         }
498                 }
499
500                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
501                 ++_first_nonexistant_frame;
502         }
503
504         fclose (mxf);
505 }
506
507 /** @param frame Frame index.
508  *  @return true if we can fake-write this frame.
509  */
510 bool
511 Writer::can_fake_write (int frame) const
512 {
513         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
514            parameters in the MXF writer.
515         */
516         return (frame != 0 && frame < _first_nonexistant_frame);
517 }
518
519 bool
520 operator< (QueueItem const & a, QueueItem const & b)
521 {
522         if (a.frame != b.frame) {
523                 return a.frame < b.frame;
524         }
525
526         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
527 }
528
529 bool
530 operator== (QueueItem const & a, QueueItem const & b)
531 {
532         return a.frame == b.frame && a.eyes == b.eyes;
533 }