2c35e9f9702269feafd082c9ae3acb89036b6c02
[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 #include "xyz_frame.h"
40 #include "picture_asset_writer.h"
41
42 using std::string;
43 using std::ostream;
44 using std::list;
45 using std::vector;
46 using std::max;
47 using std::stringstream;
48 using std::pair;
49 using std::make_pair;
50 using std::istream;
51 using std::cout;
52 using boost::shared_ptr;
53 using boost::dynamic_pointer_cast;
54 using boost::lexical_cast;
55 using namespace libdcp;
56
57 PictureAsset::PictureAsset (string directory, string mxf_name, boost::signals2::signal<void (float)>* progress, int fps, int intrinsic_duration, bool encrypted, Size size)
58         : MXFAsset (directory, mxf_name, progress, fps, intrinsic_duration, encrypted)
59         , _size (size)
60 {
61
62 }
63
64 PictureAsset::PictureAsset (string directory, string mxf_name)
65         : MXFAsset (directory, mxf_name)
66 {
67
68 }
69
70 string
71 MonoPictureAsset::cpl_node_name () const
72 {
73         return "MainPicture";
74 }
75
76 int
77 MonoPictureAsset::edit_rate_factor () const
78 {
79         return 1;
80 }
81
82 string
83 StereoPictureAsset::cpl_node_name () const
84 {
85         return "msp-cpl:MainStereoscopicPicture";
86 }
87
88 pair<string, string>
89 StereoPictureAsset::cpl_node_attribute (bool interop) const
90 {
91         if (interop) {
92                 return make_pair ("xmlns:msp-cpl", "http://www.digicine.com/schemas/437-Y/2007/Main-Stereo-Picture-CPL");
93         } else {
94                 return make_pair ("xmlns:msp-cpl", "http://www.smpte-ra.org/schemas/429-10/2008/Main-Stereo-Picture-CPL");
95         }
96
97         return make_pair ("", "");
98 }
99
100 int
101 StereoPictureAsset::edit_rate_factor () const
102 {
103         return 2;
104 }
105
106 void
107 PictureAsset::write_to_cpl (xmlpp::Element* node, bool interop) const
108 {
109         MXFAsset::write_to_cpl (node, interop);
110         
111         xmlpp::Node::NodeList c = node->get_children ();
112         xmlpp::Node::NodeList::iterator i = c.begin();
113         while (i != c.end() && (*i)->get_name() != cpl_node_name ()) {
114                 ++i;
115         }
116
117         assert (i != c.end ());
118
119         (*i)->add_child ("FrameRate")->add_child_text (lexical_cast<string> (_edit_rate * edit_rate_factor ()) + " 1");
120         if (interop) {
121                 (*i)->add_child ("ScreenAspectRatio")->add_child_text (lexical_cast<string> (float (_size.width) / _size.height));
122         } else {
123                 (*i)->add_child ("ScreenAspectRatio")->add_child_text (lexical_cast<string> (_size.width) + " " + lexical_cast<string> (_size.height));
124         }
125 }
126
127 bool
128 PictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
129 {
130         if (!MXFAsset::equals (other, opt, note)) {
131                 return false;
132         }
133                      
134         ASDCP::JP2K::MXFReader reader_A;
135         if (ASDCP_FAILURE (reader_A.OpenRead (path().string().c_str()))) {
136                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
137         }
138         
139         ASDCP::JP2K::MXFReader reader_B;
140         if (ASDCP_FAILURE (reader_B.OpenRead (other->path().string().c_str()))) {
141                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
142         }
143         
144         ASDCP::JP2K::PictureDescriptor desc_A;
145         if (ASDCP_FAILURE (reader_A.FillPictureDescriptor (desc_A))) {
146                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
147         }
148         ASDCP::JP2K::PictureDescriptor desc_B;
149         if (ASDCP_FAILURE (reader_B.FillPictureDescriptor (desc_B))) {
150                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
151         }
152         
153         if (
154                 desc_A.EditRate != desc_B.EditRate ||
155                 desc_A.SampleRate != desc_B.SampleRate ||
156                 desc_A.StoredWidth != desc_B.StoredWidth ||
157                 desc_A.StoredHeight != desc_B.StoredHeight ||
158                 desc_A.AspectRatio != desc_B.AspectRatio ||
159                 desc_A.Rsize != desc_B.Rsize ||
160                 desc_A.Xsize != desc_B.Xsize ||
161                 desc_A.Ysize != desc_B.Ysize ||
162                 desc_A.XOsize != desc_B.XOsize ||
163                 desc_A.YOsize != desc_B.YOsize ||
164                 desc_A.XTsize != desc_B.XTsize ||
165                 desc_A.YTsize != desc_B.YTsize ||
166                 desc_A.XTOsize != desc_B.XTOsize ||
167                 desc_A.YTOsize != desc_B.YTOsize ||
168                 desc_A.Csize != desc_B.Csize
169 //              desc_A.CodingStyleDefault != desc_B.CodingStyleDefault ||
170 //              desc_A.QuantizationDefault != desc_B.QuantizationDefault
171                 ) {
172                 
173                 note (ERROR, "video MXF picture descriptors differ");
174                 return false;
175         }
176
177         if (desc_A.ContainerDuration != desc_B.ContainerDuration) {
178                 note (ERROR, "video container durations differ");
179         }
180         
181 //              for (unsigned int j = 0; j < ASDCP::JP2K::MaxComponents; ++j) {
182 //                      if (desc_A.ImageComponents[j] != desc_B.ImageComponents[j]) {
183 //                              notes.pack_start ("video MXF picture descriptors differ");
184 //                      }
185 //              }
186
187         return true;
188 }
189
190
191 MonoPictureAsset::MonoPictureAsset (
192         boost::function<string (int)> get_path,
193         string directory,
194         string mxf_name,
195         boost::signals2::signal<void (float)>* progress,
196         int fps,
197         int intrinsic_duration,
198         bool encrypted,
199         Size size,
200         bool interop,
201         MXFMetadata const & metadata
202         )
203         : PictureAsset (directory, mxf_name, progress, fps, intrinsic_duration, encrypted, size)
204 {
205         construct (get_path, interop, metadata);
206 }
207
208 MonoPictureAsset::MonoPictureAsset (
209         vector<string> const & files,
210         string directory,
211         string mxf_name,
212         boost::signals2::signal<void (float)>* progress,
213         int fps,
214         int intrinsic_duration,
215         bool encrypted,
216         Size size,
217         bool interop,
218         MXFMetadata const & metadata
219         )
220         : PictureAsset (directory, mxf_name, progress, fps, intrinsic_duration, encrypted, size)
221 {
222         construct (boost::bind (&MonoPictureAsset::path_from_list, this, _1, files), interop, metadata);
223 }
224
225 MonoPictureAsset::MonoPictureAsset (string directory, string mxf_name, int fps, Size size)
226         : PictureAsset (directory, mxf_name, 0, fps, 0, false, size)
227 {
228
229 }
230
231 MonoPictureAsset::MonoPictureAsset (string directory, string mxf_name)
232         : PictureAsset (directory, mxf_name)
233 {
234         ASDCP::JP2K::MXFReader reader;
235         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
236                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
237         }
238         
239         ASDCP::JP2K::PictureDescriptor desc;
240         if (ASDCP_FAILURE (reader.FillPictureDescriptor (desc))) {
241                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
242         }
243
244         _size.width = desc.StoredWidth;
245         _size.height = desc.StoredHeight;
246         _edit_rate = desc.EditRate.Numerator;
247         assert (desc.EditRate.Denominator == 1);
248         _intrinsic_duration = desc.ContainerDuration;
249 }
250
251 void
252 MonoPictureAsset::construct (boost::function<string (int)> get_path, bool interop, MXFMetadata const & metadata)
253 {
254         ASDCP::JP2K::CodestreamParser j2k_parser;
255         ASDCP::JP2K::FrameBuffer frame_buffer (4 * Kumu::Megabyte);
256         if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (get_path(0).c_str(), frame_buffer))) {
257                 boost::throw_exception (FileError ("could not open JPEG2000 file for reading", get_path (0)));
258         }
259         
260         ASDCP::JP2K::PictureDescriptor picture_desc;
261         j2k_parser.FillPictureDescriptor (picture_desc);
262         picture_desc.EditRate = ASDCP::Rational (_edit_rate, 1);
263         
264         ASDCP::WriterInfo writer_info;
265         fill_writer_info (&writer_info, _uuid, interop, metadata);
266         
267         ASDCP::JP2K::MXFWriter mxf_writer;
268         if (ASDCP_FAILURE (mxf_writer.OpenWrite (path().string().c_str(), writer_info, picture_desc, 16384, false))) {
269                 boost::throw_exception (MXFFileError ("could not open MXF file for writing", path().string()));
270         }
271
272         for (int i = 0; i < _intrinsic_duration; ++i) {
273
274                 string const path = get_path (i);
275
276                 if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (path.c_str(), frame_buffer))) {
277                         boost::throw_exception (FileError ("could not open JPEG2000 file for reading", path));
278                 }
279
280                 if (ASDCP_FAILURE (mxf_writer.WriteFrame (frame_buffer, _encryption_context, 0))) {
281                         boost::throw_exception (MXFFileError ("error in writing video MXF", this->path().string()));
282                 }
283
284                 if (_progress) {
285                         (*_progress) (0.5 * float (i) / _intrinsic_duration);
286                 }
287         }
288         
289         if (ASDCP_FAILURE (mxf_writer.Finalize())) {
290                 boost::throw_exception (MXFFileError ("error in finalising video MXF", path().string()));
291         }
292 }
293
294 string
295 MonoPictureAsset::path_from_list (int f, vector<string> const & files) const
296 {
297         return files[f];
298 }
299
300 shared_ptr<const MonoPictureFrame>
301 MonoPictureAsset::get_frame (int n) const
302 {
303         return shared_ptr<const MonoPictureFrame> (new MonoPictureFrame (path().string(), n, _decryption_context));
304 }
305
306
307 bool
308 MonoPictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
309 {
310         if (!PictureAsset::equals (other, opt, note)) {
311                 return false;
312         }
313
314         shared_ptr<const MonoPictureAsset> other_picture = dynamic_pointer_cast<const MonoPictureAsset> (other);
315         assert (other_picture);
316
317         for (int i = 0; i < _intrinsic_duration; ++i) {
318                 if (i >= other_picture->intrinsic_duration()) {
319                         return false;
320                 }
321                 
322                 note (PROGRESS, "Comparing video frame " + lexical_cast<string> (i) + " of " + lexical_cast<string> (_intrinsic_duration));
323                 shared_ptr<const MonoPictureFrame> frame_A = get_frame (i);
324                 shared_ptr<const MonoPictureFrame> frame_B = other_picture->get_frame (i);
325                 
326                 if (!frame_buffer_equals (
327                             i, opt, note,
328                             frame_A->j2k_data(), frame_A->j2k_size(),
329                             frame_B->j2k_data(), frame_B->j2k_size()
330                             )) {
331                         return false;
332                 }
333         }
334
335         return true;
336 }
337
338 bool
339 StereoPictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
340 {
341         if (!PictureAsset::equals (other, opt, note)) {
342                 return false;
343         }
344         
345         shared_ptr<const StereoPictureAsset> other_picture = dynamic_pointer_cast<const StereoPictureAsset> (other);
346         assert (other_picture);
347
348         for (int i = 0; i < _intrinsic_duration; ++i) {
349                 shared_ptr<const StereoPictureFrame> frame_A = get_frame (i);
350                 shared_ptr<const StereoPictureFrame> frame_B = other_picture->get_frame (i);
351                 
352                 if (!frame_buffer_equals (
353                             i, opt, note,
354                             frame_A->left_j2k_data(), frame_A->left_j2k_size(),
355                             frame_B->left_j2k_data(), frame_B->left_j2k_size()
356                             )) {
357                         return false;
358                 }
359                 
360                 if (!frame_buffer_equals (
361                             i, opt, note,
362                             frame_A->right_j2k_data(), frame_A->right_j2k_size(),
363                             frame_B->right_j2k_data(), frame_B->right_j2k_size()
364                             )) {
365                         return false;
366                 }
367         }
368
369         return true;
370 }
371
372 bool
373 PictureAsset::frame_buffer_equals (
374         int frame, EqualityOptions opt, boost::function<void (NoteType, string)> note,
375         uint8_t const * data_A, unsigned int size_A, uint8_t const * data_B, unsigned int size_B
376         ) const
377 {
378         if (size_A == size_B && memcmp (data_A, data_B, size_A) == 0) {
379                 note (NOTE, "J2K identical");
380                 /* Easy result; the J2K data is identical */
381                 return true;
382         }
383                 
384         /* Decompress the images to bitmaps */
385         shared_ptr<XYZFrame> image_A = decompress_j2k (const_cast<uint8_t*> (data_A), size_A, 0);
386         shared_ptr<XYZFrame> image_B = decompress_j2k (const_cast<uint8_t*> (data_B), size_B, 0);
387         
388         /* Compare them */
389         
390         vector<int> abs_diffs (image_A->size().width * image_A->size().height * 3);
391         int d = 0;
392         int max_diff = 0;
393         
394         for (int c = 0; c < 3; ++c) {
395                 
396                 if (image_A->size() != image_B->size()) {
397                         note (ERROR, "image sizes for frame " + lexical_cast<string>(frame) + " differ");
398                         return false;
399                 }
400                 
401                 int const pixels = image_A->size().width * image_A->size().height;
402                 for (int j = 0; j < pixels; ++j) {
403                         int const t = abs (image_A->data(c)[j] - image_B->data(c)[j]);
404                         abs_diffs[d++] = t;
405                         max_diff = max (max_diff, t);
406                 }
407         }
408                 
409         uint64_t total = 0;
410         for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
411                 total += *j;
412         }
413         
414         double const mean = double (total) / abs_diffs.size ();
415         
416         uint64_t total_squared_deviation = 0;
417         for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
418                 total_squared_deviation += pow (*j - mean, 2);
419         }
420         
421         double const std_dev = sqrt (double (total_squared_deviation) / abs_diffs.size());
422         
423         note (NOTE, "mean difference " + lexical_cast<string> (mean) + ", deviation " + lexical_cast<string> (std_dev));
424         
425         if (mean > opt.max_mean_pixel_error) {
426                 note (ERROR, "mean " + lexical_cast<string>(mean) + " out of range " + lexical_cast<string>(opt.max_mean_pixel_error) + " in frame " + lexical_cast<string>(frame));
427                 return false;
428         }
429
430         if (std_dev > opt.max_std_dev_pixel_error) {
431                 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));
432                 return false;
433         }
434
435         return true;
436 }
437
438
439 StereoPictureAsset::StereoPictureAsset (string directory, string mxf_name, int fps, int intrinsic_duration)
440         : PictureAsset (directory, mxf_name, 0, fps, intrinsic_duration, false, Size (0, 0))
441 {
442         ASDCP::JP2K::MXFSReader reader;
443         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
444                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
445         }
446         
447         ASDCP::JP2K::PictureDescriptor desc;
448         if (ASDCP_FAILURE (reader.FillPictureDescriptor (desc))) {
449                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
450         }
451
452         _size.width = desc.StoredWidth;
453         _size.height = desc.StoredHeight;
454 }
455
456 shared_ptr<const StereoPictureFrame>
457 StereoPictureAsset::get_frame (int n) const
458 {
459         return shared_ptr<const StereoPictureFrame> (new StereoPictureFrame (path().string(), n));
460 }
461
462 shared_ptr<PictureAssetWriter>
463 MonoPictureAsset::start_write (bool overwrite, bool interop, MXFMetadata const & metadata)
464 {
465         /* XXX: can't we use shared_ptr here? */
466         return shared_ptr<MonoPictureAssetWriter> (new MonoPictureAssetWriter (this, overwrite, interop, metadata));
467 }
468
469 string
470 PictureAsset::key_type () const
471 {
472         return "MDIK";
473 }
474
475 StereoPictureAsset::StereoPictureAsset (string directory, string mxf_name, int fps, Size size)
476         : PictureAsset (directory, mxf_name, 0, fps, 0, false, size)
477 {
478
479 }
480
481 shared_ptr<PictureAssetWriter>
482 StereoPictureAsset::start_write (bool overwrite, bool interop, MXFMetadata const & metadata)
483 {
484         /* XXX: can't we use shared_ptr here? */
485         return shared_ptr<StereoPictureAssetWriter> (new StereoPictureAssetWriter (this, overwrite, interop, metadata));
486 }
487