A couple of comments; tidy up logging.
[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 (_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                                 _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 {
134         while (1)
135         {
136                 boost::mutex::scoped_lock lock (_mutex);
137
138                 while (1) {
139                         
140                         _queue.sort ();
141                         
142                         if (_finish ||
143                             _queued_full_in_memory > _maximum_frames_in_memory ||
144                             (!_queue.empty() && _queue.front().frame == (_last_written_frame + 1))) {
145                                 
146                                 break;
147                         }
148                         
149                         TIMING ("writer sleeps with a queue of %1", _queue.size());
150                         _condition.wait (lock);
151                         TIMING ("writer wakes with a queue of %1", _queue.size());
152                 }
153
154                 if (_finish && _queue.empty()) {
155                         return;
156                 }
157
158                 /* Write any frames that we can write; i.e. those that are in sequence */
159                 while (!_queue.empty() && _queue.front().frame == (_last_written_frame + 1)) {
160                         QueueItem qi = _queue.front ();
161                         _queue.pop_front ();
162                         if (qi.type == QueueItem::FULL && qi.encoded) {
163                                 --_queued_full_in_memory;
164                         }
165
166                         lock.unlock ();
167                         switch (qi.type) {
168                         case QueueItem::FULL:
169                         {
170                                 _film->log()->log (String::compose ("Writer FULL-writes %1 to MXF", qi.frame));
171                                 if (!qi.encoded) {
172                                         qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, false)));
173                                 }
174                                 libdcp::FrameInfo const fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size());
175                                 qi.encoded->write_info (_film, qi.frame, fin);
176                                 _last_written = qi.encoded;
177                                 ++_full_written;
178                                 break;
179                         }
180                         case QueueItem::FAKE:
181                                 _film->log()->log (String::compose ("Writer FAKE-writes %1 to MXF", qi.frame));
182                                 _picture_asset_writer->fake_write (qi.size);
183                                 _last_written.reset ();
184                                 ++_fake_written;
185                                 break;
186                         case QueueItem::REPEAT:
187                         {
188                                 _film->log()->log (String::compose ("Writer REPEAT-writes %1 to MXF", qi.frame));
189                                 libdcp::FrameInfo const fin = _picture_asset_writer->write (_last_written->data(), _last_written->size());
190                                 _last_written->write_info (_film, qi.frame, fin);
191                                 ++_repeat_written;
192                                 break;
193                         }
194                         }
195                         lock.lock ();
196
197                         ++_last_written_frame;
198                 }
199
200                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
201                         /* Too many frames in memory which can't yet be written to the stream.
202                            Write some FULL frames to disk.
203                         */
204
205                         /* Find one */
206                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
207                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
208                                 ++i;
209                         }
210
211                         assert (i != _queue.rend());
212                         QueueItem qi = *i;
213
214                         ++_pushed_to_disk;
215                         
216                         lock.unlock ();
217                         _film->log()->log (String::compose ("Writer full (awaiting %1); pushes %2 to disk", _last_written_frame + 1, qi.frame));
218                         qi.encoded->write (_film, qi.frame);
219                         lock.lock ();
220                         qi.encoded.reset ();
221                         --_queued_full_in_memory;
222                 }
223         }
224
225 }
226
227 void
228 Writer::finish ()
229 {
230         if (!_thread) {
231                 return;
232         }
233         
234         boost::mutex::scoped_lock lock (_mutex);
235         _finish = true;
236         _condition.notify_all ();
237         lock.unlock ();
238
239         _thread->join ();
240         delete _thread;
241         _thread = 0;
242
243         _picture_asset_writer->finalize ();
244
245         if (_sound_asset_writer) {
246                 _sound_asset_writer->finalize ();
247         }
248
249         int const frames = _last_written_frame + 1;
250         int const duration = frames - _film->trim_start() - _film->trim_end();
251         
252         _film->set_dcp_intrinsic_duration (frames);
253         
254         _picture_asset->set_entry_point (_film->trim_start ());
255         _picture_asset->set_duration (duration);
256
257         /* Hard-link the video MXF into the DCP */
258
259         boost::filesystem::path from;
260         from /= _film->video_mxf_dir();
261         from /= _film->video_mxf_filename();
262         
263         boost::filesystem::path to;
264         to /= _film->dir (_film->dcp_name());
265         to /= "video.mxf";
266         
267         boost::filesystem::create_hard_link (from, to);
268
269         /* And update the asset */
270
271         _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
272         _picture_asset->set_file_name ("video.mxf");
273
274         if (_sound_asset) {
275                 _sound_asset->set_entry_point (_film->trim_start ());
276                 _sound_asset->set_duration (duration);
277         }
278         
279         libdcp::DCP dcp (_film->dir (_film->dcp_name()));
280         DCPFrameRate dfr (_film->frames_per_second ());
281
282         shared_ptr<libdcp::CPL> cpl (
283                 new libdcp::CPL (_film->dir (_film->dcp_name()), _film->dcp_name(), _film->dcp_content_type()->libdcp_kind (), frames, dfr.frames_per_second)
284                 );
285         
286         dcp.add_cpl (cpl);
287
288         cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
289                                                          _picture_asset,
290                                                          _sound_asset,
291                                                          shared_ptr<libdcp::SubtitleAsset> ()
292                                                          )
293                                ));
294
295         dcp.write_xml ();
296
297         _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));
298 }
299
300 /** Tell the writer that frame `f' should be a repeat of the frame before it */
301 void
302 Writer::repeat (int f)
303 {
304         boost::mutex::scoped_lock lock (_mutex);
305
306         QueueItem qi;
307         qi.type = QueueItem::REPEAT;
308         qi.frame = f;
309         
310         _queue.push_back (qi);
311
312         _condition.notify_all ();
313 }
314
315
316 void
317 Writer::check_existing_picture_mxf ()
318 {
319         /* Try to open the existing MXF */
320         boost::filesystem::path p;
321         p /= _film->video_mxf_dir ();
322         p /= _film->video_mxf_filename ();
323         FILE* mxf = fopen (p.string().c_str(), "rb");
324         if (!mxf) {
325                 return;
326         }
327
328         while (1) {
329
330                 /* Read the frame info as written */
331                 ifstream ifi (_film->info_path (_first_nonexistant_frame).c_str());
332                 libdcp::FrameInfo info (ifi);
333
334                 /* Read the data from the MXF and hash it */
335                 fseek (mxf, info.offset, SEEK_SET);
336                 EncodedData data (info.size);
337                 fread (data.data(), 1, data.size(), mxf);
338                 string const existing_hash = md5_digest (data.data(), data.size());
339                 
340                 if (existing_hash != info.hash) {
341                         _film->log()->log (String::compose ("Existing frame %1 failed hash check", _first_nonexistant_frame));
342                         break;
343                 }
344
345                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
346                 ++_first_nonexistant_frame;
347         }
348
349         fclose (mxf);
350 }
351
352 /** @param frame Frame index.
353  *  @return true if we can fake-write this frame.
354  */
355 bool
356 Writer::can_fake_write (int frame) const
357 {
358         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
359            parameters in the MXF writer.
360         */
361         return (frame != 0 && frame < _first_nonexistant_frame);
362 }
363
364
365 bool
366 operator< (QueueItem const & a, QueueItem const & b)
367 {
368         return a.frame < b.frame;
369 }
370
371 bool
372 operator== (QueueItem const & a, QueueItem const & b)
373 {
374         return a.frame == b.frame;
375 }