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