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