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