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