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