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