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