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