Windows debugging.
[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 #include "cross.h"
40
41 #include "i18n.h"
42
43 using std::make_pair;
44 using std::pair;
45 using std::string;
46 using std::list;
47 using std::cout;
48 using boost::shared_ptr;
49 using boost::weak_ptr;
50
51 int const Writer::_maximum_frames_in_memory = Config::instance()->num_local_encoding_threads() + 4;
52
53 Writer::Writer (shared_ptr<const Film> f, weak_ptr<Job> j)
54         : _film (f)
55         , _job (j)
56         , _first_nonexistant_frame (0)
57         , _thread (0)
58         , _finish (false)
59         , _queued_full_in_memory (0)
60         , _last_written_frame (-1)
61         , _last_written_eyes (EYES_RIGHT)
62         , _full_written (0)
63         , _fake_written (0)
64         , _repeat_written (0)
65         , _pushed_to_disk (0)
66 {
67         /* Remove any old DCP */
68         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
69
70         shared_ptr<Job> job = _job.lock ();
71         assert (job);
72
73         job->sub (_("Checking existing image data"));
74         check_existing_picture_mxf ();
75
76         /* Create our picture asset in a subdirectory, named according to those
77            film's parameters which affect the video output.  We will hard-link
78            it into the DCP later.
79         */
80
81         if (_film->three_d ()) {
82                 _picture_asset.reset (new libdcp::StereoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
83         } else {
84                 _picture_asset.reset (new libdcp::MonoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
85         }
86
87         _picture_asset->set_edit_rate (_film->video_frame_rate ());
88         _picture_asset->set_size (fit_ratio_within (_film->container()->ratio(), _film->full_frame ()));
89
90         if (_film->encrypted ()) {
91                 _picture_asset->set_key (_film->key ());
92         }
93         
94         _picture_asset_writer = _picture_asset->start_write (_first_nonexistant_frame > 0);
95
96         /* Write the sound asset into the film directory so that we leave the creation
97            of the DCP directory until the last minute.
98         */
99         _sound_asset.reset (new libdcp::SoundAsset (_film->directory (), _film->audio_mxf_filename ()));
100         _sound_asset->set_edit_rate (_film->video_frame_rate ());
101         _sound_asset->set_channels (_film->audio_channels ());
102         _sound_asset->set_sampling_rate (_film->audio_frame_rate ());
103
104         if (_film->encrypted ()) {
105                 _sound_asset->set_key (_film->key ());
106         }
107         
108         _sound_asset_writer = _sound_asset->start_write ();
109 #ifdef DCPOMATIC_WINDOWS        
110         _film->log()->log (String::compose ("DEBUG: %1", GetLastError ()));
111 #endif  
112
113         _thread = new boost::thread (boost::bind (&Writer::thread, this));
114
115         job->sub (_("Encoding image data"));
116 }
117
118 void
119 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
120 {
121         boost::mutex::scoped_lock lock (_mutex);
122
123         QueueItem qi;
124         qi.type = QueueItem::FULL;
125         qi.encoded = encoded;
126         qi.frame = frame;
127
128         if (_film->three_d() && eyes == EYES_BOTH) {
129                 /* 2D material in a 3D DCP; fake the 3D */
130                 qi.eyes = EYES_LEFT;
131                 _queue.push_back (qi);
132                 ++_queued_full_in_memory;
133                 qi.eyes = EYES_RIGHT;
134                 _queue.push_back (qi);
135                 ++_queued_full_in_memory;
136         } else {
137                 qi.eyes = eyes;
138                 _queue.push_back (qi);
139                 ++_queued_full_in_memory;
140         }
141         
142         _condition.notify_all ();
143 }
144
145 void
146 Writer::fake_write (int frame, Eyes eyes)
147 {
148         boost::mutex::scoped_lock lock (_mutex);
149
150         FILE* ifi = fopen_boost (_film->info_path (frame, eyes), "r");
151         libdcp::FrameInfo info (ifi);
152         fclose (ifi);
153         
154         QueueItem qi;
155         qi.type = QueueItem::FAKE;
156         qi.size = info.size;
157         qi.frame = frame;
158         if (_film->three_d() && eyes == EYES_BOTH) {
159                 qi.eyes = EYES_LEFT;
160                 _queue.push_back (qi);
161                 qi.eyes = EYES_RIGHT;
162                 _queue.push_back (qi);
163         } else {
164                 qi.eyes = eyes;
165                 _queue.push_back (qi);
166         }
167
168         _condition.notify_all ();
169 }
170
171 /** This method is not thread safe */
172 void
173 Writer::write (shared_ptr<const AudioBuffers> audio)
174 {
175         _sound_asset_writer->write (audio->data(), audio->frames());
176 }
177
178 /** This must be called from Writer::thread() with an appropriate lock held */
179 bool
180 Writer::have_sequenced_image_at_queue_head ()
181 {
182         if (_queue.empty ()) {
183                 return false;
184         }
185
186         _queue.sort ();
187
188         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
189
190         if (_queue.front().eyes == EYES_BOTH) {
191                 /* 2D */
192                 return _queue.front().frame == (_last_written_frame + 1);
193         }
194
195         /* 3D */
196
197         if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
198                 return true;
199         }
200
201         if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
202                 return true;
203         }
204
205         return false;
206 }
207
208 void
209 Writer::thread ()
210 try
211 {
212         while (1)
213         {
214                 boost::mutex::scoped_lock lock (_mutex);
215
216                 while (1) {
217                         
218                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
219                                 break;
220                         }
221
222                         TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
223                         _condition.wait (lock);
224                         TIMING (N_("writer wakes with a queue of %1"), _queue.size());
225                 }
226
227                 if (_finish && _queue.empty()) {
228                         return;
229                 }
230
231                 /* Write any frames that we can write; i.e. those that are in sequence. */
232                 while (have_sequenced_image_at_queue_head ()) {
233                         QueueItem qi = _queue.front ();
234                         _queue.pop_front ();
235                         if (qi.type == QueueItem::FULL && qi.encoded) {
236                                 --_queued_full_in_memory;
237                         }
238
239                         lock.unlock ();
240                         switch (qi.type) {
241                         case QueueItem::FULL:
242                         {
243                                 _film->log()->log (String::compose (N_("Writer FULL-writes %1 to MXF"), qi.frame));
244                                 if (!qi.encoded) {
245                                         qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
246                                 }
247
248                                 libdcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size());
249                                 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
250                                 _last_written[qi.eyes] = qi.encoded;
251                                 ++_full_written;
252                                 break;
253                         }
254                         case QueueItem::FAKE:
255                                 _film->log()->log (String::compose (N_("Writer FAKE-writes %1 to MXF"), qi.frame));
256                                 _picture_asset_writer->fake_write (qi.size);
257                                 _last_written[qi.eyes].reset ();
258                                 ++_fake_written;
259                                 break;
260                         case QueueItem::REPEAT:
261                         {
262                                 _film->log()->log (String::compose (N_("Writer REPEAT-writes %1 to MXF"), qi.frame));
263                                 libdcp::FrameInfo fin = _picture_asset_writer->write (
264                                         _last_written[qi.eyes]->data(),
265                                         _last_written[qi.eyes]->size()
266                                         );
267                                 
268                                 _last_written[qi.eyes]->write_info (_film, qi.frame, qi.eyes, fin);
269                                 ++_repeat_written;
270                                 break;
271                         }
272                         }
273                         lock.lock ();
274
275                         _last_written_frame = qi.frame;
276                         _last_written_eyes = qi.eyes;
277                         
278                         if (_film->length()) {
279                                 shared_ptr<Job> job = _job.lock ();
280                                 assert (job);
281                                 int total = _film->time_to_video_frames (_film->length ());
282                                 if (_film->three_d ()) {
283                                         /* _full_written and so on are incremented for each eye, so we need to double the total
284                                            frames to get the correct progress.
285                                         */
286                                         total *= 2;
287                                 }
288                                 job->set_progress (float (_full_written + _fake_written + _repeat_written) / total);
289                         }
290                 }
291
292                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
293                         /* Too many frames in memory which can't yet be written to the stream.
294                            Write some FULL frames to disk.
295                         */
296
297                         /* Find one from the back of the queue */
298                         _queue.sort ();
299                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
300                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
301                                 ++i;
302                         }
303
304                         assert (i != _queue.rend());
305                         QueueItem qi = *i;
306
307                         ++_pushed_to_disk;
308                         
309                         lock.unlock ();
310
311                         _film->log()->log (
312                                 String::compose (
313                                         "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
314                                         _last_written_frame + 1,
315                                         _last_written_eyes, qi.frame)
316                                 );
317                         
318                         qi.encoded->write (_film, qi.frame, qi.eyes);
319                         lock.lock ();
320                         qi.encoded.reset ();
321                         --_queued_full_in_memory;
322                 }
323         }
324 }
325 catch (...)
326 {
327         store_current ();
328 }
329
330 void
331 Writer::finish ()
332 {
333         if (!_thread) {
334                 return;
335         }
336         
337         boost::mutex::scoped_lock lock (_mutex);
338         _finish = true;
339         _condition.notify_all ();
340         lock.unlock ();
341
342         _thread->join ();
343         rethrow ();
344         
345         delete _thread;
346         _thread = 0;
347
348         _picture_asset_writer->finalize ();
349         _sound_asset_writer->finalize ();
350         
351         int const frames = _last_written_frame + 1;
352
353         _picture_asset->set_duration (frames);
354
355         /* Hard-link the video MXF into the DCP */
356         boost::filesystem::path video_from;
357         video_from /= _film->internal_video_mxf_dir();
358         video_from /= _film->internal_video_mxf_filename();
359         
360         boost::filesystem::path video_to;
361         video_to /= _film->dir (_film->dcp_name());
362         video_to /= _film->video_mxf_filename ();
363
364         boost::system::error_code ec;
365         boost::filesystem::create_hard_link (video_from, video_to, ec);
366         if (ec) {
367                 /* hard link failed; copy instead */
368                 boost::filesystem::copy_file (video_from, video_to);
369                 _film->log()->log ("Hard-link failed; fell back to copying");
370         }
371
372         /* And update the asset */
373
374         _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
375         _picture_asset->set_file_name (_film->video_mxf_filename ());
376
377         /* Move the audio MXF into the DCP */
378
379         boost::filesystem::path audio_to;
380         audio_to /= _film->dir (_film->dcp_name ());
381         audio_to /= _film->audio_mxf_filename ();
382         
383         boost::filesystem::rename (_film->file (_film->audio_mxf_filename ()), audio_to, ec);
384         if (ec) {
385                 throw FileError (
386                         String::compose (_("could not move audio MXF into the DCP (%1)"), ec.value ()), _film->file (_film->audio_mxf_filename ())
387                         );
388         }
389
390         _sound_asset->set_directory (_film->dir (_film->dcp_name ()));
391         _sound_asset->set_duration (frames);
392         
393         libdcp::DCP dcp (_film->dir (_film->dcp_name()));
394
395         shared_ptr<libdcp::CPL> cpl (
396                 new libdcp::CPL (
397                         _film->dir (_film->dcp_name()),
398                         _film->dcp_name(),
399                         _film->dcp_content_type()->libdcp_kind (),
400                         frames,
401                         _film->video_frame_rate ()
402                         )
403                 );
404         
405         dcp.add_cpl (cpl);
406
407         cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
408                                                          _picture_asset,
409                                                          _sound_asset,
410                                                          shared_ptr<libdcp::SubtitleAsset> ()
411                                                          )
412                                ));
413
414         shared_ptr<Job> job = _job.lock ();
415         assert (job);
416
417         job->sub (_("Computing image digest"));
418         _picture_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
419
420         job->sub (_("Computing audio digest"));
421         _sound_asset->compute_digest (boost::bind (&Job::set_progress, job.get(), _1, false));
422
423         libdcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
424         meta.set_issue_date_now ();
425         dcp.write_xml (_film->interop (), meta, _film->is_signed() ? make_signer () : shared_ptr<const libdcp::Signer> ());
426
427         _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));
428 }
429
430 /** Tell the writer that frame `f' should be a repeat of the frame before it */
431 void
432 Writer::repeat (int f, Eyes e)
433 {
434         boost::mutex::scoped_lock lock (_mutex);
435
436         QueueItem qi;
437         qi.type = QueueItem::REPEAT;
438         qi.frame = f;
439         if (_film->three_d() && e == EYES_BOTH) {
440                 qi.eyes = EYES_LEFT;
441                 _queue.push_back (qi);
442                 qi.eyes = EYES_RIGHT;
443                 _queue.push_back (qi);
444         } else {
445                 qi.eyes = e;
446                 _queue.push_back (qi);
447         }
448
449         _condition.notify_all ();
450 }
451
452 bool
453 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
454 {
455         /* Read the frame info as written */
456         FILE* ifi = fopen_boost (_film->info_path (f, eyes), "r");
457         if (!ifi) {
458                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
459                 return false;
460         }
461         
462         libdcp::FrameInfo info (ifi);
463         fclose (ifi);
464         if (info.size == 0) {
465                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
466                 return false;
467         }
468         
469         /* Read the data from the MXF and hash it */
470         dcpomatic_fseek (mxf, info.offset, SEEK_SET);
471         EncodedData data (info.size);
472         size_t const read = fread (data.data(), 1, data.size(), mxf);
473         if (read != static_cast<size_t> (data.size ())) {
474                 _film->log()->log (String::compose ("Existing frame %1 is incomplete", f));
475                 return false;
476         }
477         
478         string const existing_hash = md5_digest (data.data(), data.size());
479         if (existing_hash != info.hash) {
480                 _film->log()->log (String::compose ("Existing frame %1 failed hash check", f));
481                 return false;
482         }
483
484         return true;
485 }
486
487 void
488 Writer::check_existing_picture_mxf ()
489 {
490         /* Try to open the existing MXF */
491         boost::filesystem::path p;
492         p /= _film->internal_video_mxf_dir ();
493         p /= _film->internal_video_mxf_filename ();
494         FILE* mxf = fopen_boost (p, "rb");
495         if (!mxf) {
496                 _film->log()->log (String::compose ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno));
497                 return;
498         }
499
500         int N = 0;
501         for (boost::filesystem::directory_iterator i (_film->info_dir ()); i != boost::filesystem::directory_iterator (); ++i) {
502                 ++N;
503         }
504
505         while (1) {
506
507                 shared_ptr<Job> job = _job.lock ();
508                 assert (job);
509
510                 job->set_progress (float (_first_nonexistant_frame) / N);
511
512                 if (_film->three_d ()) {
513                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
514                                 break;
515                         }
516                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
517                                 break;
518                         }
519                 } else {
520                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
521                                 break;
522                         }
523                 }
524
525                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
526                 ++_first_nonexistant_frame;
527         }
528
529         fclose (mxf);
530 }
531
532 /** @param frame Frame index.
533  *  @return true if we can fake-write this frame.
534  */
535 bool
536 Writer::can_fake_write (int frame) const
537 {
538         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
539            parameters in the MXF writer.
540         */
541         return (frame != 0 && frame < _first_nonexistant_frame);
542 }
543
544 bool
545 operator< (QueueItem const & a, QueueItem const & b)
546 {
547         if (a.frame != b.frame) {
548                 return a.frame < b.frame;
549         }
550
551         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
552 }
553
554 bool
555 operator== (QueueItem const & a, QueueItem const & b)
556 {
557         return a.frame == b.frame && a.eyes == b.eyes;
558 }