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