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