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