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