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