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