A couple of 3D fixes.
[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);
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 ();
111
112         _thread = new boost::thread (boost::bind (&Writer::thread, this));
113 }
114
115 void
116 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
117 {
118         boost::mutex::scoped_lock lock (_mutex);
119
120         QueueItem qi;
121         qi.type = QueueItem::FULL;
122         qi.encoded = encoded;
123         qi.frame = frame;
124
125         if (_film->three_d() && eyes == EYES_BOTH) {
126                 /* 2D material in a 3D DCP; fake the 3D */
127                 qi.eyes = EYES_LEFT;
128                 _queue.push_back (qi);
129                 ++_queued_full_in_memory;
130                 qi.eyes = EYES_RIGHT;
131                 _queue.push_back (qi);
132                 ++_queued_full_in_memory;
133         } else {
134                 qi.eyes = eyes;
135                 _queue.push_back (qi);
136                 ++_queued_full_in_memory;
137         }
138         
139         _condition.notify_all ();
140 }
141
142 void
143 Writer::fake_write (int frame, Eyes eyes)
144 {
145         boost::mutex::scoped_lock lock (_mutex);
146
147         ifstream ifi (_film->info_path (frame, eyes).c_str());
148         libdcp::FrameInfo info (ifi);
149         
150         QueueItem qi;
151         qi.type = QueueItem::FAKE;
152         qi.size = info.size;
153         qi.frame = frame;
154         if (_film->three_d() && eyes == EYES_BOTH) {
155                 qi.eyes = EYES_LEFT;
156                 _queue.push_back (qi);
157                 qi.eyes = EYES_RIGHT;
158                 _queue.push_back (qi);
159         } else {
160                 qi.eyes = eyes;
161                 _queue.push_back (qi);
162         }
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                                 libdcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size());
247                                 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
248                                 _last_written[qi.eyes] = qi.encoded;
249                                 ++_full_written;
250                                 break;
251                         }
252                         case QueueItem::FAKE:
253                                 _film->log()->log (String::compose (N_("Writer FAKE-writes %1 to MXF"), qi.frame));
254                                 _picture_asset_writer->fake_write (qi.size);
255                                 _last_written[qi.eyes].reset ();
256                                 ++_fake_written;
257                                 break;
258                         case QueueItem::REPEAT:
259                         {
260                                 _film->log()->log (String::compose (N_("Writer REPEAT-writes %1 to MXF"), qi.frame));
261                                 libdcp::FrameInfo fin = _picture_asset_writer->write (
262                                         _last_written[qi.eyes]->data(),
263                                         _last_written[qi.eyes]->size()
264                                         );
265                                 
266                                 _last_written[qi.eyes]->write_info (_film, qi.frame, qi.eyes, fin);
267                                 ++_repeat_written;
268                                 break;
269                         }
270                         }
271                         lock.lock ();
272
273                         _last_written_frame = qi.frame;
274                         _last_written_eyes = qi.eyes;
275                         
276                         if (_film->length()) {
277                                 _job->set_progress (
278                                         float (_full_written + _fake_written + _repeat_written) / _film->time_to_video_frames (_film->length())
279                                         );
280                         }
281                 }
282
283                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
284                         /* Too many frames in memory which can't yet be written to the stream.
285                            Write some FULL frames to disk.
286                         */
287
288                         /* Find one */
289                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
290                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
291                                 ++i;
292                         }
293
294                         assert (i != _queue.rend());
295                         QueueItem qi = *i;
296
297                         ++_pushed_to_disk;
298                         
299                         lock.unlock ();
300
301                         _film->log()->log (
302                                 String::compose (
303                                         "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
304                                         _last_written_frame + 1,
305                                         _last_written_eyes, qi.frame)
306                                 );
307                         
308                         qi.encoded->write (_film, qi.frame, qi.eyes);
309                         lock.lock ();
310                         qi.encoded.reset ();
311                         --_queued_full_in_memory;
312                 }
313         }
314 }
315 catch (...)
316 {
317         store_current ();
318 }
319
320 void
321 Writer::finish ()
322 {
323         if (!_thread) {
324                 return;
325         }
326         
327         boost::mutex::scoped_lock lock (_mutex);
328         _finish = true;
329         _condition.notify_all ();
330         lock.unlock ();
331
332         _thread->join ();
333         if (thrown ()) {
334                 rethrow ();
335         }
336         
337         delete _thread;
338         _thread = 0;
339
340         _picture_asset_writer->finalize ();
341         _sound_asset_writer->finalize ();
342         
343         int const frames = _last_written_frame + 1;
344
345         _picture_asset->set_duration (frames);
346
347         /* Hard-link the video MXF into the DCP */
348
349         boost::filesystem::path from;
350         from /= _film->internal_video_mxf_dir();
351         from /= _film->internal_video_mxf_filename();
352         
353         boost::filesystem::path to;
354         to /= _film->dir (_film->dcp_name());
355         to /= _film->video_mxf_filename ();
356
357         boost::system::error_code ec;
358         boost::filesystem::create_hard_link (from, to, ec);
359         if (ec) {
360                 /* hard link failed; copy instead */
361                 boost::filesystem::copy_file (from, to);
362                 _film->log()->log ("Hard-link failed; fell back to copying");
363         }
364
365         /* And update the asset */
366
367         _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
368         _picture_asset->set_file_name (_film->video_mxf_filename ());
369         _sound_asset->set_duration (frames);
370         
371         libdcp::DCP dcp (_film->dir (_film->dcp_name()));
372
373         shared_ptr<libdcp::CPL> cpl (
374                 new libdcp::CPL (
375                         _film->dir (_film->dcp_name()),
376                         _film->dcp_name(),
377                         _film->dcp_content_type()->libdcp_kind (),
378                         frames,
379                         _film->video_frame_rate ()
380                         )
381                 );
382         
383         dcp.add_cpl (cpl);
384
385         cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
386                                                          _picture_asset,
387                                                          _sound_asset,
388                                                          shared_ptr<libdcp::SubtitleAsset> ()
389                                                          )
390                                ));
391
392         libdcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
393         meta.set_issue_date_now ();
394         dcp.write_xml (meta);
395
396         _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));
397 }
398
399 /** Tell the writer that frame `f' should be a repeat of the frame before it */
400 void
401 Writer::repeat (int f, Eyes e)
402 {
403         boost::mutex::scoped_lock lock (_mutex);
404
405         QueueItem qi;
406         qi.type = QueueItem::REPEAT;
407         qi.frame = f;
408         if (_film->three_d() && e == EYES_BOTH) {
409                 qi.eyes = EYES_LEFT;
410                 _queue.push_back (qi);
411                 qi.eyes = EYES_RIGHT;
412                 _queue.push_back (qi);
413         } else {
414                 qi.eyes = e;
415                 _queue.push_back (qi);
416         }
417
418         _condition.notify_all ();
419 }
420
421 bool
422 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
423 {
424         /* Read the frame info as written */
425         ifstream ifi (_film->info_path (f, eyes).c_str());
426         libdcp::FrameInfo info (ifi);
427         if (info.size == 0) {
428                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
429                 return false;
430         }
431         
432         /* Read the data from the MXF and hash it */
433         fseek (mxf, info.offset, SEEK_SET);
434         EncodedData data (info.size);
435         size_t const read = fread (data.data(), 1, data.size(), mxf);
436         if (read != static_cast<size_t> (data.size ())) {
437                 _film->log()->log (String::compose ("Existing frame %1 is incomplete", f));
438                 return false;
439         }
440         
441         string const existing_hash = md5_digest (data.data(), data.size());
442         if (existing_hash != info.hash) {
443                 _film->log()->log (String::compose ("Existing frame %1 failed hash check", f));
444                 return false;
445         }
446
447         return true;
448 }
449
450 void
451 Writer::check_existing_picture_mxf ()
452 {
453         /* Try to open the existing MXF */
454         boost::filesystem::path p;
455         p /= _film->internal_video_mxf_dir ();
456         p /= _film->internal_video_mxf_filename ();
457         FILE* mxf = fopen (p.string().c_str(), "rb");
458         if (!mxf) {
459                 _film->log()->log (String::compose ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno));
460                 return;
461         }
462
463         while (1) {
464
465                 if (_film->three_d ()) {
466                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
467                                 break;
468                         }
469                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
470                                 break;
471                         }
472                 } else {
473                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
474                                 break;
475                         }
476                 }
477
478                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
479                 ++_first_nonexistant_frame;
480         }
481
482         fclose (mxf);
483 }
484
485 /** @param frame Frame index.
486  *  @return true if we can fake-write this frame.
487  */
488 bool
489 Writer::can_fake_write (int frame) const
490 {
491         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
492            parameters in the MXF writer.
493         */
494         return (frame != 0 && frame < _first_nonexistant_frame);
495 }
496
497 bool
498 operator< (QueueItem const & a, QueueItem const & b)
499 {
500         if (a.frame != b.frame) {
501                 return a.frame < b.frame;
502         }
503
504         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
505 }
506
507 bool
508 operator== (QueueItem const & a, QueueItem const & b)
509 {
510         return a.frame == b.frame && a.eyes == b.eyes;
511 }