Merge master; at least partially.
[libdcp.git] / src / picture_asset.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 /** @file  src/picture_asset.cc
21  *  @brief An asset made up of JPEG2000 files
22  */
23
24 #include <list>
25 #include <stdexcept>
26 #include <iostream>
27 #include <sstream>
28 #include <fstream>
29 #include <boost/filesystem.hpp>
30 #include <boost/lexical_cast.hpp>
31 #include <openjpeg.h>
32 #include <libxml++/nodes/element.h>
33 #include "AS_DCP.h"
34 #include "KM_fileio.h"
35 #include "picture_asset.h"
36 #include "util.h"
37 #include "exceptions.h"
38 #include "picture_frame.h"
39
40 using std::string;
41 using std::ostream;
42 using std::list;
43 using std::vector;
44 using std::max;
45 using std::stringstream;
46 using std::pair;
47 using std::make_pair;
48 using std::istream;
49 using std::cout;
50 using boost::shared_ptr;
51 using boost::dynamic_pointer_cast;
52 using boost::lexical_cast;
53 using namespace libdcp;
54
55 PictureAsset::PictureAsset (string directory, string mxf_name, boost::signals2::signal<void (float)>* progress, int fps, int intrinsic_duration, bool encrypted, Size size)
56         : MXFAsset (directory, mxf_name, progress, fps, intrinsic_duration, encrypted)
57         , _size (size)
58 {
59
60 }
61
62 PictureAsset::PictureAsset (string directory, string mxf_name)
63         : MXFAsset (directory, mxf_name)
64 {
65
66 }
67
68 void
69 PictureAsset::write_to_cpl (xmlpp::Node* node) const
70 {
71         xmlpp::Node* mp = node->add_child ("MainPicture");
72         mp->add_child ("Id")->add_child_text ("urn:uuid:" + _uuid);
73         mp->add_child ("AnnotationText")->add_child_text (_file_name);
74         mp->add_child ("EditRate")->add_child_text (lexical_cast<string> (_edit_rate) + " 1");
75         mp->add_child ("IntrinsicDuration")->add_child_text (lexical_cast<string> (_intrinsic_duration));
76         mp->add_child ("EntryPoint")->add_child_text (lexical_cast<string> (_entry_point));
77         mp->add_child ("Duration")->add_child_text (lexical_cast<string> (_duration));
78         if (_encrypted) {
79                 mp->add_child("KeyId")->add_child_text("urn:uuid:" + _key_id);
80         }
81         mp->add_child ("FrameRate")->add_child_text (lexical_cast<string> (_edit_rate) + " 1");
82         mp->add_child ("ScreenAspectRatio")->add_child_text (lexical_cast<string> (_size.width) + " " + lexical_cast<string> (_size.height));
83 }
84
85 bool
86 PictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
87 {
88         if (!MXFAsset::equals (other, opt, note)) {
89                 return false;
90         }
91                      
92         ASDCP::JP2K::MXFReader reader_A;
93         if (ASDCP_FAILURE (reader_A.OpenRead (path().string().c_str()))) {
94                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
95         }
96         
97         ASDCP::JP2K::MXFReader reader_B;
98         if (ASDCP_FAILURE (reader_B.OpenRead (other->path().string().c_str()))) {
99                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
100         }
101         
102         ASDCP::JP2K::PictureDescriptor desc_A;
103         if (ASDCP_FAILURE (reader_A.FillPictureDescriptor (desc_A))) {
104                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
105         }
106         ASDCP::JP2K::PictureDescriptor desc_B;
107         if (ASDCP_FAILURE (reader_B.FillPictureDescriptor (desc_B))) {
108                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
109         }
110         
111         if (
112                 desc_A.EditRate != desc_B.EditRate ||
113                 desc_A.ContainerDuration != desc_B.ContainerDuration ||
114                 desc_A.SampleRate != desc_B.SampleRate ||
115                 desc_A.StoredWidth != desc_B.StoredWidth ||
116                 desc_A.StoredHeight != desc_B.StoredHeight ||
117                 desc_A.AspectRatio != desc_B.AspectRatio ||
118                 desc_A.Rsize != desc_B.Rsize ||
119                 desc_A.Xsize != desc_B.Xsize ||
120                 desc_A.Ysize != desc_B.Ysize ||
121                 desc_A.XOsize != desc_B.XOsize ||
122                 desc_A.YOsize != desc_B.YOsize ||
123                 desc_A.XTsize != desc_B.XTsize ||
124                 desc_A.YTsize != desc_B.YTsize ||
125                 desc_A.XTOsize != desc_B.XTOsize ||
126                 desc_A.YTOsize != desc_B.YTOsize ||
127                 desc_A.Csize != desc_B.Csize
128 //              desc_A.CodingStyleDefault != desc_B.CodingStyleDefault ||
129 //              desc_A.QuantizationDefault != desc_B.QuantizationDefault
130                 ) {
131                 
132                 note (ERROR, "video MXF picture descriptors differ");
133                 return false;
134         }
135
136 //              for (unsigned int j = 0; j < ASDCP::JP2K::MaxComponents; ++j) {
137 //                      if (desc_A.ImageComponents[j] != desc_B.ImageComponents[j]) {
138 //                              notes.pack_start ("video MXF picture descriptors differ");
139 //                      }
140 //              }
141
142         return true;
143 }
144
145
146 MonoPictureAsset::MonoPictureAsset (
147         boost::function<string (int)> get_path,
148         string directory,
149         string mxf_name,
150         boost::signals2::signal<void (float)>* progress,
151         int fps,
152         int intrinsic_duration,
153         bool encrypted,
154         Size size,
155         MXFMetadata const & metadata
156         )
157         : PictureAsset (directory, mxf_name, progress, fps, intrinsic_duration, encrypted, size)
158 {
159         construct (get_path, metadata);
160 }
161
162 MonoPictureAsset::MonoPictureAsset (
163         vector<string> const & files,
164         string directory,
165         string mxf_name,
166         boost::signals2::signal<void (float)>* progress,
167         int fps,
168         int intrinsic_duration,
169         bool encrypted,
170         Size size,
171         MXFMetadata const & metadata
172         )
173         : PictureAsset (directory, mxf_name, progress, fps, intrinsic_duration, encrypted, size)
174 {
175         construct (boost::bind (&MonoPictureAsset::path_from_list, this, _1, files), metadata);
176 }
177
178 MonoPictureAsset::MonoPictureAsset (string directory, string mxf_name, int fps, Size size)
179         : PictureAsset (directory, mxf_name, 0, fps, 0, false, size)
180 {
181
182 }
183
184 MonoPictureAsset::MonoPictureAsset (string directory, string mxf_name)
185         : PictureAsset (directory, mxf_name)
186 {
187         ASDCP::JP2K::MXFReader reader;
188         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
189                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
190         }
191         
192         ASDCP::JP2K::PictureDescriptor desc;
193         if (ASDCP_FAILURE (reader.FillPictureDescriptor (desc))) {
194                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
195         }
196
197         _size.width = desc.StoredWidth;
198         _size.height = desc.StoredHeight;
199         _edit_rate = desc.EditRate.Numerator;
200         assert (desc.EditRate.Denominator == 1);
201         _intrinsic_duration = desc.ContainerDuration;
202 }
203
204 void
205 MonoPictureAsset::construct (boost::function<string (int)> get_path, MXFMetadata const & metadata)
206 {
207         ASDCP::JP2K::CodestreamParser j2k_parser;
208         ASDCP::JP2K::FrameBuffer frame_buffer (4 * Kumu::Megabyte);
209         if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (get_path(0).c_str(), frame_buffer))) {
210                 boost::throw_exception (FileError ("could not open JPEG2000 file for reading", get_path (0)));
211         }
212         
213         ASDCP::JP2K::PictureDescriptor picture_desc;
214         j2k_parser.FillPictureDescriptor (picture_desc);
215         picture_desc.EditRate = ASDCP::Rational (_edit_rate, 1);
216         
217         ASDCP::WriterInfo writer_info;
218         fill_writer_info (&writer_info, _uuid, metadata);
219         
220         ASDCP::JP2K::MXFWriter mxf_writer;
221         if (ASDCP_FAILURE (mxf_writer.OpenWrite (path().string().c_str(), writer_info, picture_desc, 16384, false))) {
222                 boost::throw_exception (MXFFileError ("could not open MXF file for writing", path().string()));
223         }
224
225         for (int i = 0; i < _intrinsic_duration; ++i) {
226
227                 string const path = get_path (i);
228
229                 if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (path.c_str(), frame_buffer))) {
230                         boost::throw_exception (FileError ("could not open JPEG2000 file for reading", path));
231                 }
232
233                 if (ASDCP_FAILURE (mxf_writer.WriteFrame (frame_buffer, _encryption_context, 0))) {
234                         boost::throw_exception (MXFFileError ("error in writing video MXF", this->path().string()));
235                 }
236
237                 if (_progress) {
238                         (*_progress) (0.5 * float (i) / _intrinsic_duration);
239                 }
240         }
241         
242         if (ASDCP_FAILURE (mxf_writer.Finalize())) {
243                 boost::throw_exception (MXFFileError ("error in finalising video MXF", path().string()));
244         }
245 }
246
247 string
248 MonoPictureAsset::path_from_list (int f, vector<string> const & files) const
249 {
250         return files[f];
251 }
252
253 shared_ptr<const MonoPictureFrame>
254 MonoPictureAsset::get_frame (int n) const
255 {
256         return shared_ptr<const MonoPictureFrame> (new MonoPictureFrame (path().string(), n));
257 }
258
259
260 bool
261 MonoPictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
262 {
263         if (!PictureAsset::equals (other, opt, note)) {
264                 return false;
265         }
266
267         shared_ptr<const MonoPictureAsset> other_picture = dynamic_pointer_cast<const MonoPictureAsset> (other);
268         assert (other_picture);
269
270         for (int i = 0; i < _intrinsic_duration; ++i) {
271                 note (PROGRESS, "Comparing video frame " + lexical_cast<string> (i) + " of " + lexical_cast<string> (_intrinsic_duration));
272                 shared_ptr<const MonoPictureFrame> frame_A = get_frame (i);
273                 shared_ptr<const MonoPictureFrame> frame_B = other_picture->get_frame (i);
274                 
275                 if (!frame_buffer_equals (
276                             i, opt, note,
277                             frame_A->j2k_data(), frame_A->j2k_size(),
278                             frame_B->j2k_data(), frame_B->j2k_size()
279                             )) {
280                         return false;
281                 }
282         }
283
284         return true;
285 }
286
287 bool
288 StereoPictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
289 {
290         if (!PictureAsset::equals (other, opt, note)) {
291                 return false;
292         }
293         
294         shared_ptr<const StereoPictureAsset> other_picture = dynamic_pointer_cast<const StereoPictureAsset> (other);
295         assert (other_picture);
296
297         for (int i = 0; i < _intrinsic_duration; ++i) {
298                 shared_ptr<const StereoPictureFrame> frame_A = get_frame (i);
299                 shared_ptr<const StereoPictureFrame> frame_B = other_picture->get_frame (i);
300                 
301                 if (!frame_buffer_equals (
302                             i, opt, note,
303                             frame_A->left_j2k_data(), frame_A->left_j2k_size(),
304                             frame_B->left_j2k_data(), frame_B->left_j2k_size()
305                             )) {
306                         return false;
307                 }
308                 
309                 if (!frame_buffer_equals (
310                             i, opt, note,
311                             frame_A->right_j2k_data(), frame_A->right_j2k_size(),
312                             frame_B->right_j2k_data(), frame_B->right_j2k_size()
313                             )) {
314                         return false;
315                 }
316         }
317
318         return true;
319 }
320
321 bool
322 PictureAsset::frame_buffer_equals (
323         int frame, EqualityOptions opt, boost::function<void (NoteType, string)> note,
324         uint8_t const * data_A, unsigned int size_A, uint8_t const * data_B, unsigned int size_B
325         ) const
326 {
327         if (size_A == size_B && memcmp (data_A, data_B, size_A) == 0) {
328                 note (NOTE, "J2K identical");
329                 /* Easy result; the J2K data is identical */
330                 return true;
331         }
332                 
333         /* Decompress the images to bitmaps */
334         opj_image_t* image_A = decompress_j2k (const_cast<uint8_t*> (data_A), size_A, 0);
335         opj_image_t* image_B = decompress_j2k (const_cast<uint8_t*> (data_B), size_B, 0);
336         
337         /* Compare them */
338         
339         if (image_A->numcomps != image_B->numcomps) {
340                 note (ERROR, "image component counts for frame " + lexical_cast<string>(frame) + " differ");
341                 return false;
342         }
343         
344         vector<int> abs_diffs (image_A->comps[0].w * image_A->comps[0].h * image_A->numcomps);
345         int d = 0;
346         int max_diff = 0;
347         
348         for (int c = 0; c < image_A->numcomps; ++c) {
349                 
350                 if (image_A->comps[c].w != image_B->comps[c].w || image_A->comps[c].h != image_B->comps[c].h) {
351                         note (ERROR, "image sizes for frame " + lexical_cast<string>(frame) + " differ");
352                         return false;
353                 }
354                 
355                 int const pixels = image_A->comps[c].w * image_A->comps[c].h;
356                 for (int j = 0; j < pixels; ++j) {
357                         int const t = abs (image_A->comps[c].data[j] - image_B->comps[c].data[j]);
358                         abs_diffs[d++] = t;
359                         max_diff = max (max_diff, t);
360                 }
361         }
362                 
363         uint64_t total = 0;
364         for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
365                 total += *j;
366         }
367         
368         double const mean = double (total) / abs_diffs.size ();
369         
370         uint64_t total_squared_deviation = 0;
371         for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
372                 total_squared_deviation += pow (*j - mean, 2);
373         }
374         
375         double const std_dev = sqrt (double (total_squared_deviation) / abs_diffs.size());
376         
377         note (NOTE, "mean difference " + lexical_cast<string> (mean) + ", deviation " + lexical_cast<string> (std_dev));
378         
379         if (mean > opt.max_mean_pixel_error) {
380                 note (ERROR, "mean " + lexical_cast<string>(mean) + " out of range " + lexical_cast<string>(opt.max_mean_pixel_error) + " in frame " + lexical_cast<string>(frame));
381                 return false;
382         }
383
384         if (std_dev > opt.max_std_dev_pixel_error) {
385                 note (ERROR, "standard deviation " + lexical_cast<string>(std_dev) + " out of range " + lexical_cast<string>(opt.max_std_dev_pixel_error) + " in frame " + lexical_cast<string>(frame));
386                 return false;
387         }
388
389         opj_image_destroy (image_A);
390         opj_image_destroy (image_B);
391
392         return true;
393 }
394
395
396 StereoPictureAsset::StereoPictureAsset (string directory, string mxf_name, int fps, int intrinsic_duration)
397         : PictureAsset (directory, mxf_name, 0, fps, intrinsic_duration, false, Size (0, 0))
398 {
399         ASDCP::JP2K::MXFSReader reader;
400         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
401                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
402         }
403         
404         ASDCP::JP2K::PictureDescriptor desc;
405         if (ASDCP_FAILURE (reader.FillPictureDescriptor (desc))) {
406                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
407         }
408
409         _size.width = desc.StoredWidth;
410         _size.height = desc.StoredHeight;
411 }
412
413 shared_ptr<const StereoPictureFrame>
414 StereoPictureAsset::get_frame (int n) const
415 {
416         return shared_ptr<const StereoPictureFrame> (new StereoPictureFrame (path().string(), n));
417 }
418
419 shared_ptr<MonoPictureAssetWriter>
420 MonoPictureAsset::start_write (bool overwrite, MXFMetadata const & metadata)
421 {
422         /* XXX: can't we use shared_ptr here? */
423         return shared_ptr<MonoPictureAssetWriter> (new MonoPictureAssetWriter (this, overwrite, metadata));
424 }
425
426 FrameInfo::FrameInfo (istream& s)
427 {
428         s >> offset >> size >> hash;
429 }
430
431 void
432 FrameInfo::write (ostream& s)
433 {
434         s << offset << " " << size << " " << hash;
435 }
436
437 struct MonoPictureAssetWriter::ASDCPState
438 {
439         ASDCPState()
440                 : frame_buffer (4 * Kumu::Megabyte)
441         {}
442         
443         ASDCP::JP2K::CodestreamParser j2k_parser;
444         ASDCP::JP2K::FrameBuffer frame_buffer;
445         ASDCP::JP2K::MXFWriter mxf_writer;
446         ASDCP::WriterInfo writer_info;
447         ASDCP::JP2K::PictureDescriptor picture_descriptor;
448 };
449
450
451 /** @param a Asset to write to.  `a' must not be deleted while
452  *  this writer class still exists, or bad things will happen.
453  */
454 MonoPictureAssetWriter::MonoPictureAssetWriter (MonoPictureAsset* a, bool overwrite, MXFMetadata const & m)
455         : _state (new MonoPictureAssetWriter::ASDCPState)
456         , _asset (a)
457         , _frames_written (0)
458         , _started (false)
459         , _finalized (false)
460         , _overwrite (overwrite)
461         , _metadata (m)
462 {
463
464 }
465
466
467 void
468 MonoPictureAssetWriter::start (uint8_t* data, int size)
469 {
470         if (ASDCP_FAILURE (_state->j2k_parser.OpenReadFrame (data, size, _state->frame_buffer))) {
471                 boost::throw_exception (MiscError ("could not parse J2K frame"));
472         }
473
474         _state->j2k_parser.FillPictureDescriptor (_state->picture_descriptor);
475         _state->picture_descriptor.EditRate = ASDCP::Rational (_asset->edit_rate(), 1);
476         
477         _asset->fill_writer_info (&_state->writer_info, _asset->uuid(), _metadata);
478         
479         if (ASDCP_FAILURE (_state->mxf_writer.OpenWrite (
480                                    _asset->path().string().c_str(),
481                                    _state->writer_info,
482                                    _state->picture_descriptor,
483                                    16384,
484                                    _overwrite)
485                     )) {
486                 
487                 boost::throw_exception (MXFFileError ("could not open MXF file for writing", _asset->path().string()));
488         }
489
490         _started = true;
491 }
492
493 FrameInfo
494 MonoPictureAssetWriter::write (uint8_t* data, int size)
495 {
496         assert (!_finalized);
497
498         if (!_started) {
499                 start (data, size);
500         }
501
502         if (ASDCP_FAILURE (_state->j2k_parser.OpenReadFrame (data, size, _state->frame_buffer))) {
503                 boost::throw_exception (MiscError ("could not parse J2K frame"));
504         }
505
506         uint64_t const before_offset = _state->mxf_writer.Tell ();
507
508         string hash;
509         if (ASDCP_FAILURE (_state->mxf_writer.WriteFrame (_state->frame_buffer, 0, 0, &hash))) {
510                 boost::throw_exception (MXFFileError ("error in writing video MXF", _asset->path().string()));
511         }
512
513         ++_frames_written;
514         return FrameInfo (before_offset, _state->mxf_writer.Tell() - before_offset, hash);
515 }
516
517 void
518 MonoPictureAssetWriter::fake_write (int size)
519 {
520         assert (_started);
521         assert (!_finalized);
522
523         if (ASDCP_FAILURE (_state->mxf_writer.FakeWriteFrame (size))) {
524                 boost::throw_exception (MXFFileError ("error in writing video MXF", _asset->path().string()));
525         }
526
527         ++_frames_written;
528 }
529
530 void
531 MonoPictureAssetWriter::finalize ()
532 {
533         assert (!_finalized);
534         
535         if (ASDCP_FAILURE (_state->mxf_writer.Finalize())) {
536                 boost::throw_exception (MXFFileError ("error in finalizing video MXF", _asset->path().string()));
537         }
538
539         _finalized = true;
540         _asset->set_intrinsic_duration (_frames_written);
541         _asset->set_duration (_frames_written);
542 }
543
544 string
545 PictureAsset::key_type () const
546 {
547         return "MDIK";
548 }