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