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