Allow no-stretch scaling of video content.
[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/mono_picture_asset.h>
23 #include <libdcp/stereo_picture_asset.h>
24 #include <libdcp/sound_asset.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         , _last_written_eyes (EYES_RIGHT)
61         , _full_written (0)
62         , _fake_written (0)
63         , _repeat_written (0)
64         , _pushed_to_disk (0)
65 {
66         /* Remove any old DCP */
67         boost::filesystem::remove_all (_film->dir (_film->dcp_name ()));
68         
69         check_existing_picture_mxf ();
70         
71         /* Create our picture asset in a subdirectory, named according to those
72            film's parameters which affect the video output.  We will hard-link
73            it into the DCP later.
74         */
75
76         if (_film->three_d ()) {
77                 _picture_asset.reset (new libdcp::StereoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
78         } else {
79                 _picture_asset.reset (new libdcp::MonoPictureAsset (_film->internal_video_mxf_dir (), _film->internal_video_mxf_filename ()));
80         }
81
82         _picture_asset->set_edit_rate (_film->video_frame_rate ());
83         _picture_asset->set_size (fit_ratio_within (_film->container()->ratio(), _film->full_frame ()));
84
85         if (_film->encrypted ()) {
86                 _picture_asset->set_key (_film->key ());
87         }
88         
89         _picture_asset_writer = _picture_asset->start_write (_first_nonexistant_frame > 0);
90         
91         _sound_asset.reset (new libdcp::SoundAsset (_film->dir (_film->dcp_name()), _film->audio_mxf_filename ()));
92         _sound_asset->set_edit_rate (_film->video_frame_rate ());
93         _sound_asset->set_channels (_film->audio_channels ());
94         _sound_asset->set_sampling_rate (_film->audio_frame_rate ());
95
96         if (_film->encrypted ()) {
97                 _sound_asset->set_key (_film->key ());
98         }
99         
100         _sound_asset_writer = _sound_asset->start_write ();
101
102         _thread = new boost::thread (boost::bind (&Writer::thread, this));
103
104         _job->descend (0.9);
105 }
106
107 void
108 Writer::write (shared_ptr<const EncodedData> encoded, int frame, Eyes eyes)
109 {
110         boost::mutex::scoped_lock lock (_mutex);
111
112         QueueItem qi;
113         qi.type = QueueItem::FULL;
114         qi.encoded = encoded;
115         qi.frame = frame;
116
117         if (_film->three_d() && eyes == EYES_BOTH) {
118                 /* 2D material in a 3D DCP; fake the 3D */
119                 qi.eyes = EYES_LEFT;
120                 _queue.push_back (qi);
121                 ++_queued_full_in_memory;
122                 qi.eyes = EYES_RIGHT;
123                 _queue.push_back (qi);
124                 ++_queued_full_in_memory;
125         } else {
126                 qi.eyes = eyes;
127                 _queue.push_back (qi);
128                 ++_queued_full_in_memory;
129         }
130         
131         _condition.notify_all ();
132 }
133
134 void
135 Writer::fake_write (int frame, Eyes eyes)
136 {
137         boost::mutex::scoped_lock lock (_mutex);
138
139         ifstream ifi (_film->info_path (frame, eyes).c_str());
140         libdcp::FrameInfo info (ifi);
141         
142         QueueItem qi;
143         qi.type = QueueItem::FAKE;
144         qi.size = info.size;
145         qi.frame = frame;
146         if (_film->three_d() && eyes == EYES_BOTH) {
147                 qi.eyes = EYES_LEFT;
148                 _queue.push_back (qi);
149                 qi.eyes = EYES_RIGHT;
150                 _queue.push_back (qi);
151         } else {
152                 qi.eyes = eyes;
153                 _queue.push_back (qi);
154         }
155
156         _condition.notify_all ();
157 }
158
159 /** This method is not thread safe */
160 void
161 Writer::write (shared_ptr<const AudioBuffers> audio)
162 {
163         _sound_asset_writer->write (audio->data(), audio->frames());
164 }
165
166 /** This must be called from Writer::thread() with an appropriate lock held,
167  *  and with _queue sorted.
168  */
169 bool
170 Writer::have_sequenced_image_at_queue_head () const
171 {
172         if (_queue.empty ()) {
173                 return false;
174         }
175
176         /* The queue should contain only EYES_LEFT/EYES_RIGHT pairs or EYES_BOTH */
177
178         if (_queue.front().eyes == EYES_BOTH) {
179                 /* 2D */
180                 return _queue.front().frame == (_last_written_frame + 1);
181         }
182
183         /* 3D */
184
185         if (_last_written_eyes == EYES_LEFT && _queue.front().frame == _last_written_frame && _queue.front().eyes == EYES_RIGHT) {
186                 return true;
187         }
188
189         if (_last_written_eyes == EYES_RIGHT && _queue.front().frame == (_last_written_frame + 1) && _queue.front().eyes == EYES_LEFT) {
190                 return true;
191         }
192
193         return false;
194 }
195
196 void
197 Writer::thread ()
198 try
199 {
200         while (1)
201         {
202                 boost::mutex::scoped_lock lock (_mutex);
203
204                 while (1) {
205                         
206                         _queue.sort ();
207                         
208                         if (_finish || _queued_full_in_memory > _maximum_frames_in_memory || have_sequenced_image_at_queue_head ()) {
209                                 break;
210                         }
211
212                         TIMING (N_("writer sleeps with a queue of %1"), _queue.size());
213                         _condition.wait (lock);
214                         TIMING (N_("writer wakes with a queue of %1"), _queue.size());
215                 }
216
217                 if (_finish && _queue.empty()) {
218                         return;
219                 }
220
221                 /* Write any frames that we can write; i.e. those that are in sequence */
222                 while (have_sequenced_image_at_queue_head ()) {
223                         QueueItem qi = _queue.front ();
224                         _queue.pop_front ();
225                         if (qi.type == QueueItem::FULL && qi.encoded) {
226                                 --_queued_full_in_memory;
227                         }
228
229                         lock.unlock ();
230                         switch (qi.type) {
231                         case QueueItem::FULL:
232                         {
233                                 _film->log()->log (String::compose (N_("Writer FULL-writes %1 to MXF"), qi.frame));
234                                 if (!qi.encoded) {
235                                         qi.encoded.reset (new EncodedData (_film->j2c_path (qi.frame, qi.eyes, false)));
236                                 }
237
238                                 libdcp::FrameInfo fin = _picture_asset_writer->write (qi.encoded->data(), qi.encoded->size());
239                                 qi.encoded->write_info (_film, qi.frame, qi.eyes, fin);
240                                 _last_written[qi.eyes] = qi.encoded;
241                                 ++_full_written;
242                                 break;
243                         }
244                         case QueueItem::FAKE:
245                                 _film->log()->log (String::compose (N_("Writer FAKE-writes %1 to MXF"), qi.frame));
246                                 _picture_asset_writer->fake_write (qi.size);
247                                 _last_written[qi.eyes].reset ();
248                                 ++_fake_written;
249                                 break;
250                         case QueueItem::REPEAT:
251                         {
252                                 _film->log()->log (String::compose (N_("Writer REPEAT-writes %1 to MXF"), qi.frame));
253                                 libdcp::FrameInfo fin = _picture_asset_writer->write (
254                                         _last_written[qi.eyes]->data(),
255                                         _last_written[qi.eyes]->size()
256                                         );
257                                 
258                                 _last_written[qi.eyes]->write_info (_film, qi.frame, qi.eyes, fin);
259                                 ++_repeat_written;
260                                 break;
261                         }
262                         }
263                         lock.lock ();
264
265                         _last_written_frame = qi.frame;
266                         _last_written_eyes = qi.eyes;
267                         
268                         if (_film->length()) {
269                                 _job->set_progress (
270                                         float (_full_written + _fake_written + _repeat_written) / _film->time_to_video_frames (_film->length())
271                                         );
272                         }
273                 }
274
275                 while (_queued_full_in_memory > _maximum_frames_in_memory) {
276                         /* Too many frames in memory which can't yet be written to the stream.
277                            Write some FULL frames to disk.
278                         */
279
280                         /* Find one */
281                         list<QueueItem>::reverse_iterator i = _queue.rbegin ();
282                         while (i != _queue.rend() && (i->type != QueueItem::FULL || !i->encoded)) {
283                                 ++i;
284                         }
285
286                         assert (i != _queue.rend());
287                         QueueItem qi = *i;
288
289                         ++_pushed_to_disk;
290                         
291                         lock.unlock ();
292
293                         _film->log()->log (
294                                 String::compose (
295                                         "Writer full (awaiting %1 [last eye was %2]); pushes %3 to disk",
296                                         _last_written_frame + 1,
297                                         _last_written_eyes, qi.frame)
298                                 );
299                         
300                         qi.encoded->write (_film, qi.frame, qi.eyes);
301                         lock.lock ();
302                         qi.encoded.reset ();
303                         --_queued_full_in_memory;
304                 }
305         }
306 }
307 catch (...)
308 {
309         store_current ();
310 }
311
312 void
313 Writer::finish ()
314 {
315         if (!_thread) {
316                 return;
317         }
318         
319         boost::mutex::scoped_lock lock (_mutex);
320         _finish = true;
321         _condition.notify_all ();
322         lock.unlock ();
323
324         _thread->join ();
325         if (thrown ()) {
326                 rethrow ();
327         }
328         
329         delete _thread;
330         _thread = 0;
331
332         _picture_asset_writer->finalize ();
333         _sound_asset_writer->finalize ();
334         
335         int const frames = _last_written_frame + 1;
336
337         _picture_asset->set_duration (frames);
338
339         /* Hard-link the video MXF into the DCP */
340
341         boost::filesystem::path from;
342         from /= _film->internal_video_mxf_dir();
343         from /= _film->internal_video_mxf_filename();
344         
345         boost::filesystem::path to;
346         to /= _film->dir (_film->dcp_name());
347         to /= _film->video_mxf_filename ();
348
349         boost::system::error_code ec;
350         boost::filesystem::create_hard_link (from, to, ec);
351         if (ec) {
352                 /* hard link failed; copy instead */
353                 boost::filesystem::copy_file (from, to);
354                 _film->log()->log ("Hard-link failed; fell back to copying");
355         }
356
357         /* And update the asset */
358
359         _picture_asset->set_directory (_film->dir (_film->dcp_name ()));
360         _picture_asset->set_file_name (_film->video_mxf_filename ());
361         _sound_asset->set_duration (frames);
362         
363         libdcp::DCP dcp (_film->dir (_film->dcp_name()));
364
365         shared_ptr<libdcp::CPL> cpl (
366                 new libdcp::CPL (
367                         _film->dir (_film->dcp_name()),
368                         _film->dcp_name(),
369                         _film->dcp_content_type()->libdcp_kind (),
370                         frames,
371                         _film->video_frame_rate ()
372                         )
373                 );
374         
375         dcp.add_cpl (cpl);
376
377         cpl->add_reel (shared_ptr<libdcp::Reel> (new libdcp::Reel (
378                                                          _picture_asset,
379                                                          _sound_asset,
380                                                          shared_ptr<libdcp::SubtitleAsset> ()
381                                                          )
382                                ));
383
384         /* Compute the digests for the assets now so that we can keep track of progress.
385            We did _job->descend (0.9) in our constructor */
386         _job->ascend ();
387
388         _job->descend (0.1);
389         _picture_asset->compute_digest (boost::bind (&Job::set_progress, _job.get(), _1));
390         _job->ascend ();
391
392         _job->descend (0.1);
393         _sound_asset->compute_digest (boost::bind (&Job::set_progress, _job.get(), _1));
394         _job->ascend ();
395
396         libdcp::XMLMetadata meta = Config::instance()->dcp_metadata ();
397         meta.set_issue_date_now ();
398         dcp.write_xml (_film->interop (), meta, make_signer ());
399
400         _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));
401 }
402
403 /** Tell the writer that frame `f' should be a repeat of the frame before it */
404 void
405 Writer::repeat (int f, Eyes e)
406 {
407         boost::mutex::scoped_lock lock (_mutex);
408
409         QueueItem qi;
410         qi.type = QueueItem::REPEAT;
411         qi.frame = f;
412         if (_film->three_d() && e == EYES_BOTH) {
413                 qi.eyes = EYES_LEFT;
414                 _queue.push_back (qi);
415                 qi.eyes = EYES_RIGHT;
416                 _queue.push_back (qi);
417         } else {
418                 qi.eyes = e;
419                 _queue.push_back (qi);
420         }
421
422         _condition.notify_all ();
423 }
424
425 bool
426 Writer::check_existing_picture_mxf_frame (FILE* mxf, int f, Eyes eyes)
427 {
428         /* Read the frame info as written */
429         ifstream ifi (_film->info_path (f, eyes).c_str());
430         libdcp::FrameInfo info (ifi);
431         if (info.size == 0) {
432                 _film->log()->log (String::compose ("Existing frame %1 has no info file", f));
433                 return false;
434         }
435         
436         /* Read the data from the MXF and hash it */
437         fseek (mxf, info.offset, SEEK_SET);
438         EncodedData data (info.size);
439         size_t const read = fread (data.data(), 1, data.size(), mxf);
440         if (read != static_cast<size_t> (data.size ())) {
441                 _film->log()->log (String::compose ("Existing frame %1 is incomplete", f));
442                 return false;
443         }
444         
445         string const existing_hash = md5_digest (data.data(), data.size());
446         if (existing_hash != info.hash) {
447                 _film->log()->log (String::compose ("Existing frame %1 failed hash check", f));
448                 return false;
449         }
450
451         return true;
452 }
453
454 void
455 Writer::check_existing_picture_mxf ()
456 {
457         /* Try to open the existing MXF */
458         boost::filesystem::path p;
459         p /= _film->internal_video_mxf_dir ();
460         p /= _film->internal_video_mxf_filename ();
461         FILE* mxf = fopen (p.string().c_str(), "rb");
462         if (!mxf) {
463                 _film->log()->log (String::compose ("Could not open existing MXF at %1 (errno=%2)", p.string(), errno));
464                 return;
465         }
466
467         while (1) {
468
469                 if (_film->three_d ()) {
470                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_LEFT)) {
471                                 break;
472                         }
473                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_RIGHT)) {
474                                 break;
475                         }
476                 } else {
477                         if (!check_existing_picture_mxf_frame (mxf, _first_nonexistant_frame, EYES_BOTH)) {
478                                 break;
479                         }
480                 }
481
482                 _film->log()->log (String::compose ("Have existing frame %1", _first_nonexistant_frame));
483                 ++_first_nonexistant_frame;
484         }
485
486         fclose (mxf);
487 }
488
489 /** @param frame Frame index.
490  *  @return true if we can fake-write this frame.
491  */
492 bool
493 Writer::can_fake_write (int frame) const
494 {
495         /* We have to do a proper write of the first frame so that we can set up the JPEG2000
496            parameters in the MXF writer.
497         */
498         return (frame != 0 && frame < _first_nonexistant_frame);
499 }
500
501 bool
502 operator< (QueueItem const & a, QueueItem const & b)
503 {
504         if (a.frame != b.frame) {
505                 return a.frame < b.frame;
506         }
507
508         return static_cast<int> (a.eyes) < static_cast<int> (b.eyes);
509 }
510
511 bool
512 operator== (QueueItem const & a, QueueItem const & b)
513 {
514         return a.frame == b.frame && a.eyes == b.eyes;
515 }