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