Some improvements in progress reporting, especially for long jobs.
[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/mono_picture_asset.h>
23 #include <libdcp/stereo_picture_asset.h>
24 #include <libdcp/sound_asset.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         _job->sub (_("Checking existing image data"));
70         check_existing_picture_mxf ();
71
72         /* Create our picture asset in a subdirectory, named according to those
73            film's parameters which affect the video output.  We will hard-link
74            it into the DCP later.
75         */
76
77         if (_film->three_d ()) {
78                 _picture_asset.reset (new libdcp::StereoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
79         } else {
80                 _picture_asset.reset (new libdcp::MonoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
81         }
82
83         _picture_asset->set_edit_rate (_film->video_frame_rate ());
84         _picture_asset->set_size (fit_ratio_within (_film->container()->ratio(), _film->full_frame ()));
85
86         if (_film->encrypted ()) {
87                 _picture_asset->set_key (_film->key ());
88         }
89         
90         _picture_asset_writer = _picture_asset->start_write (_first_nonexistant_frame > 0);
91         
92         _sound_asset.reset (new libdcp::SoundAsset (_film->dir (_film->dcp_name()), _film->audio_mxf_filename ()));
93         _sound_asset->set_edit_rate (_film->video_frame_rate ());
94         _sound_asset->set_channels (_film->audio_channels ());
95         _sound_asset->set_sampling_rate (_film->audio_frame_rate ());
96
97         if (_film->encrypted ()) {
98                 _sound_asset->set_key (_film->key ());
99         }
100         
101         _sound_asset_writer = _sound_asset->start_write ();
102
103         _thread = new boost::thread (boost::bind (&Writer::thread, this));
104
105         _job->sub (_("Encoding image data"));
106 }
107
108 void
109 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
110 {
111         boost::mutex::scoped_lock lock (_mutex);
112
113         QueueItem qi;
114         qi.type = QueueItem::FULL;
115         qi.encoded = encoded;
116         qi.frame = frame;
117
118         if (_film->three_d() && eyes == EYES_BOTH) {
119                 /* 2D material in a 3D DCP; fake the 3D */
120                 qi.eyes = EYES_LEFT;
121                 _queue.push_back (qi);
122                 ++_queued_full_in_memory;
123                 qi.eyes = EYES_RIGHT;
124                 _queue.push_back (qi);
125                 ++_queued_full_in_memory;
126         } else {
127                 qi.eyes = eyes;
128                 _queue.push_back (qi);
129                 ++_queued_full_in_memory;
130         }
131         
132         _condition.notify_all ();
133 }
134
135 void
136 Writer::fake_write (int frame, Eyes eyes)
137 {
138         boost::mutex::scoped_lock lock (_mutex);
139
140         ifstream ifi (_film->info_path (frame, eyes).c_str());
141         libdcp::FrameInfo info (ifi);
142         
143         QueueItem qi;
144         qi.type = QueueItem::FAKE;
145         qi.size = info.size;
146         qi.frame = frame;
147         if (_film->three_d() && eyes == EYES_BOTH) {
148                 qi.eyes = EYES_LEFT;
149                 _queue.push_back (qi);
150                 qi.eyes = EYES_RIGHT;
151                 _queue.push_back (qi);
152         } else {
153                 qi.eyes = eyes;
154                 _queue.push_back (qi);
155         }
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->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->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->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         _job->sub (_("Computing image digest"));
386         _picture_asset->compute_digest (boost::bind (&Job::set_progress, _job.get(), _1));
387
388         _job->sub (_("Computing audio digest"));
389         _sound_asset->compute_digest (boost::bind (&Job::set_progress, _job.get(), _1));
390
391         libdcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
392         meta.set_issue_date_now ();
393         dcp.write_xml (_film->interop (), meta, make_signer ());
394
395         _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));
396 }
397
398 /** Tell the writer that frame `f' should be a repeat of the frame before it */
399 void
400 Writer::repeat (int f, Eyes e)
401 {
402         boost::mutex::scoped_lock lock (_mutex);
403
404         QueueItem qi;
405         qi.type = QueueItem::REPEAT;
406         qi.frame = f;
407         if (_film->three_d() && e == EYES_BOTH) {
408                 qi.eyes = EYES_LEFT;
409                 _queue.push_back (qi);
410                 qi.eyes = EYES_RIGHT;
411                 _queue.push_back (qi);
412         } else {
413                 qi.eyes = e;
414                 _queue.push_back (qi);
415         }
416
417         _condition.notify_all ();
418 }
419
420 bool
421 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
422 {
423         /* Read the frame info as written */
424         ifstream ifi (_film->info_path (f, eyes).c_str());
425         libdcp::FrameInfo info (ifi);
426         if (info.size == 0) {
427                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
428                 return false;
429         }
430         
431         /* Read the data from the MXF and hash it */
432 #ifdef DCPOMATIC_WINDOWS
433         _fseeki64 (mxf, info.offset, SEEK_SET);
434 #else   
435         fseek (mxf, info.offset, SEEK_SET);
436 #endif  
437         EncodedData data (info.size);
438         size_t const read = fread (data.data(), 1, data.size(), mxf);
439         if (read != static_cast<size_t> (data.size ())) {
440                 _film->log()->log (String::compose ("Existing frame %1 is incomplete", f));
441                 return false;
442         }
443         
444         string const existing_hash = md5_digest (data.data(), data.size());
445         if (existing_hash != info.hash) {
446                 _film->log()->log (String::compose ("Existing frame %1 failed hash check", f));
447                 return false;
448         }
449
450         return true;
451 }
452
453 void
454 Writer::check_existing_picture_mxf ()
455 {
456         /* Try to open the existing MXF */
457         boost::filesystem::path p;
458         p /= _film->internal_video_mxf_dir ();
459         p /= _film->internal_video_mxf_filename ();
460         FILE* mxf = fopen (p.string().c_str(), "rb");
461         if (!mxf) {
462                 _film->log()->log (String::compose ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno));
463                 return;
464         }
465
466         int N = 0;
467         for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
468                 ++N;
469         }
470
471         while (1) {
472
473                 _job->set_progress (float (_first_nonexistant_frame) / N);
474
475                 if (_film->three_d ()) {
476                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
477                                 break;
478                         }
479                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
480                                 break;
481                         }
482                 } else {
483                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
484                                 break;
485                         }
486                 }
487
488                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
489                 ++_first_nonexistant_frame;
490         }
491
492         fclose (mxf);
493 }
494
495 /** @param frame Frame index.
496  *  @return true if we can fake-write this frame.
497  */
498 bool
499 Writer::can_fake_write (int frame) const
500 {
501         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
502            parameters in the MXF writer.
503         */
504         return (frame != 0 && frame < _first_nonexistant_frame);
505 }
506
507 bool
508 operator< (QueueItem const & a, QueueItem const & b)
509 {
510         if (a.frame != b.frame) {
511                 return a.frame < b.frame;
512         }
513
514         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
515 }
516
517 bool
518 operator== (QueueItem const & a, QueueItem const & b)
519 {
520         return a.frame == b.frame && a.eyes == b.eyes;
521 }