Compile fix.
[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         , _full_written (0)
61         , _fake_written (0)
62         , _repeat_written (0)
63         , _pushed_to_disk (0)
64 {
65         /* Remove any old DCP */
66         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
67         
68         check_existing_picture_mxf ();
69         
70         /* Create our picture asset in a subdirectory, named according to those
71            film's parameters which affect the video output.  We will hard-link
72            it into the DCP later.
73         */
74         
75         _picture_asset.reset (
76                 new libdcp::MonoPictureAsset (
77                         _film->internal_video_mxf_dir (),
78                         _film->internal_video_mxf_filename (),
79                         _film->dcp_video_frame_rate (),
80                         _film->container()->size (_film->full_frame ())
81                         )
82                 );
83
84         _picture_asset_writer = _picture_asset->start_write (_first_nonexistant_frame > 0);
85
86         _sound_asset.reset (
87                 new libdcp::SoundAsset (
88                         _film->dir (_film->dcp_name()),
89                         _film->dcp_audio_mxf_filename (),
90                         _film->dcp_video_frame_rate (),
91                         _film->dcp_audio_channels (),
92                         _film->dcp_audio_frame_rate ()
93                         )
94                 );
95         
96         _sound_asset_writer = _sound_asset->start_write ();
97
98         _thread = new boost::thread (boost::bind (&Writer::thread, this));
99 }
100
101 void
102 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
103 {
104         boost::mutex::scoped_lock lock (_mutex);
105
106         QueueItem qi;
107         qi.type = QueueItem::FULL;
108         qi.encoded = encoded;
109         qi.frame = frame;
110         qi.eyes = eyes;
111         _queue.push_back (qi);
112         ++_queued_full_in_memory;
113
114         _condition.notify_all ();
115 }
116
117 void
118 Writer::fake_write (int frame, Eyes eyes)
119 {
120         boost::mutex::scoped_lock lock (_mutex);
121
122         ifstream ifi (_film->info_path (frame, eyes).c_str());
123         libdcp::FrameInfo info (ifi);
124         
125         QueueItem qi;
126         qi.type = QueueItem::FAKE;
127         qi.size = info.size;
128         qi.frame = frame;
129         qi.eyes = eyes;
130         _queue.push_back (qi);
131
132         _condition.notify_all ();
133 }
134
135 /** This method is not thread safe */
136 void
137 Writer::write (shared_ptr<const AudioBuffers> audio)
138 {
139         _sound_asset_writer->write (audio->data(), audio->frames());
140 }
141
142 /** This must be called from Writer::thread() with an appropriate lock held */
143 bool
144 Writer::have_sequenced_image_at_queue_head () const
145 {
146         if (_queue.empty ()) {
147                 return false;
148         }
149
150         /* We assume that we will get either all 2D frames or all 3D frames, not a mixture */
151         
152         bool const eyes_ok = (_queue.front().eyes == EYES_BOTH) ||
153                 (_queue.front().eyes == EYES_LEFT && _last_written_eyes == EYES_RIGHT) ||
154                 (_queue.front().eyes == EYES_RIGHT && _last_written_eyes == EYES_LEFT);
155         
156         return _queue.front().frame == (_last_written_frame + 1) && eyes_ok;
157 }
158
159 void
160 Writer::thread ()
161 try
162 {
163         while (1)
164         {
165                 boost::mutex::scoped_lock lock (_mutex);
166
167                 while (1) {
168                         
169                         _queue.sort ();
170                         
171                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
172                                 break;
173                         }
174                         
175                         TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
176                         _condition.wait (lock);
177                         TIMING (N_("writer wakes with a queue of %1"), _queue.size());
178                 }
179
180                 if (_finish && _queue.empty()) {
181                         return;
182                 }
183
184                 /* Write any frames that we can write; i.e. those that are in sequence */
185                 while (have_sequenced_image_at_queue_head ()) {
186                         QueueItem qi = _queue.front ();
187                         _queue.pop_front ();
188                         if (qi.type == QueueItem::FULL && qi.encoded) {
189                                 --_queued_full_in_memory;
190                         }
191
192                         lock.unlock ();
193                         switch (qi.type) {
194                         case QueueItem::FULL:
195                         {
196                                 _film->log()->log (String::compose (N_("Writer FULL-writes %1 to MXF"), qi.frame));
197                                 if (!qi.encoded) {
198                                         qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
199                                 }
200                                 libdcp::FrameInfo const fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size(), qi.eyes);
201                                 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
202                                 _last_written = qi.encoded;
203                                 ++_full_written;
204                                 break;
205                         }
206                         case QueueItem::FAKE:
207                                 _film->log()->log (String::compose (N_("Writer FAKE-writes %1 to MXF"), qi.frame));
208                                 _picture_asset_writer->fake_write (qi.size);
209                                 _last_written.reset ();
210                                 ++_fake_written;
211                                 break;
212                         case QueueItem::REPEAT:
213                         {
214                                 _film->log()->log (String::compose (N_("Writer REPEAT-writes %1 to MXF"), qi.frame));
215                                 libdcp::FrameInfo const fin = _picture_asset_writer->write (_last_written->data(), _last_written->size(), qi.eyes);
216                                 _last_written->write_info (_film, qi.frame, qi.eyes, fin);
217                                 ++_repeat_written;
218                                 break;
219                         }
220                         }
221                         lock.lock ();
222                         
223                         if (_film->length()) {
224                                 _job->set_progress (
225                                         float (_full_written + _fake_written + _repeat_written) / _film->time_to_video_frames (_film->length())
226                                         );
227                         }
228
229                         ++_last_written_frame;
230                 }
231
232                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
233                         /* Too many frames in memory which can't yet be written to the stream.
234                            Write some FULL frames to disk.
235                         */
236
237                         /* Find one */
238                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
239                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
240                                 ++i;
241                         }
242
243                         assert (i != _queue.rend());
244                         QueueItem qi = *i;
245
246                         ++_pushed_to_disk;
247                         
248                         lock.unlock ();
249                         _film->log()->log (String::compose (N_("Writer full (awaiting %1); pushes %2 to disk"), _last_written_frame + 1, qi.frame));
250                         qi.encoded->write (_film, qi.frame, qi.eyes);
251                         lock.lock ();
252                         qi.encoded.reset ();
253                         --_queued_full_in_memory;
254                 }
255         }
256 }
257 catch (...)
258 {
259         store_current ();
260 }
261
262 void
263 Writer::finish ()
264 {
265         if (!_thread) {
266                 return;
267         }
268         
269         boost::mutex::scoped_lock lock (_mutex);
270         _finish = true;
271         _condition.notify_all ();
272         lock.unlock ();
273
274         _thread->join ();
275         if (thrown ()) {
276                 rethrow ();
277         }
278         
279         delete _thread;
280         _thread = 0;
281
282         _picture_asset_writer->finalize ();
283         _sound_asset_writer->finalize ();
284         
285         int const frames = _last_written_frame + 1;
286         
287         _picture_asset->set_duration (frames);
288
289         /* Hard-link the video MXF into the DCP */
290
291         boost::filesystem::path from;
292         from /= _film->internal_video_mxf_dir();
293         from /= _film->internal_video_mxf_filename();
294         
295         boost::filesystem::path to;
296         to /= _film->dir (_film->dcp_name());
297         to /= _film->dcp_video_mxf_filename ();
298
299         boost::system::error_code ec;
300         boost::filesystem::create_hard_link (from, to, ec);
301         if (ec) {
302                 /* hard link failed; copy instead */
303                 boost::filesystem::copy_file (from, to);
304                 _film->log()->log ("Hard-link failed; fell back to copying");
305         }
306
307         /* And update the asset */
308
309         _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
310         _picture_asset->set_file_name (_film->dcp_video_mxf_filename ());
311         _sound_asset->set_duration (frames);
312         
313         libdcp::DCP dcp (_film->dir (_film->dcp_name()));
314
315         shared_ptr<libdcp::CPL> cpl (
316                 new libdcp::CPL (
317                         _film->dir (_film->dcp_name()),
318                         _film->dcp_name(),
319                         _film->dcp_content_type()->libdcp_kind (),
320                         frames,
321                         _film->dcp_video_frame_rate ()
322                         )
323                 );
324         
325         dcp.add_cpl (cpl);
326
327         cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
328                                                          _picture_asset,
329                                                          _sound_asset,
330                                                          shared_ptr<libdcp::SubtitleAsset> ()
331                                                          )
332                                ));
333
334         libdcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
335         meta.set_issue_date_now ();
336         dcp.write_xml (meta);
337
338         _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));
339 }
340
341 /** Tell the writer that frame `f' should be a repeat of the frame before it */
342 void
343 Writer::repeat (int f, Eyes e)
344 {
345         boost::mutex::scoped_lock lock (_mutex);
346
347         QueueItem qi;
348         qi.type = QueueItem::REPEAT;
349         qi.frame = f;
350         qi.eyes = e;
351         
352         _queue.push_back (qi);
353
354         _condition.notify_all ();
355 }
356
357 bool
358 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
359 {
360         /* Read the frame info as written */
361         ifstream ifi (_film->info_path (f, eyes).c_str());
362         libdcp::FrameInfo info (ifi);
363         
364         /* Read the data from the MXF and hash it */
365         fseek (mxf, info.offset, SEEK_SET);
366         EncodedData data (info.size);
367         size_t const read = fread (data.data(), 1, data.size(), mxf);
368         if (read != static_cast<size_t> (data.size ())) {
369                 _film->log()->log (String::compose ("Existing frame %1 is incomplete", f));
370                 return false;
371         }
372         
373         string const existing_hash = md5_digest (data.data(), data.size());
374         if (existing_hash != info.hash) {
375                 _film->log()->log (String::compose ("Existing frame %1 failed hash check", f));
376                 return false;
377         }
378
379         return true;
380 }
381
382 void
383 Writer::check_existing_picture_mxf ()
384 {
385         /* Try to open the existing MXF */
386         boost::filesystem::path p;
387         p /= _film->internal_video_mxf_dir ();
388         p /= _film->internal_video_mxf_filename ();
389         FILE* mxf = fopen (p.string().c_str(), "rb");
390         if (!mxf) {
391                 _film->log()->log (String::compose ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno));
392                 return;
393         }
394
395         while (1) {
396
397                 if (_film->dcp_3d ()) {
398                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
399                                 break;
400                         }
401                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
402                                 break;
403                         }
404                 } else {
405                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
406                                 break;
407                         }
408                 }
409
410                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
411                 ++_first_nonexistant_frame;
412         }
413
414         fclose (mxf);
415 }
416
417 /** @param frame Frame index.
418  *  @return true if we can fake-write this frame.
419  */
420 bool
421 Writer::can_fake_write (int frame) const
422 {
423         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
424            parameters in the MXF writer.
425         */
426         return (frame != 0 && frame < _first_nonexistant_frame);
427 }
428
429 bool
430 operator< (QueueItem const & a, QueueItem const & b)
431 {
432         if (a.frame != b.frame) {
433                 return a.frame < b.frame;
434         }
435         
436         return a.eyes == EYES_LEFT && b.eyes == EYES_RIGHT;
437 }
438
439 bool
440 operator== (QueueItem const & a, QueueItem const & b)
441 {
442         return a.frame == b.frame && a.eyes == b.eyes;
443 }