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