Various probably quite untidy progress on KDMs.
[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 boost::shared_ptr;
47 using boost::dynamic_pointer_cast;
48 using boost::lexical_cast;
49 using namespace libdcp;
50
51 PictureAsset::PictureAsset (string directory, string mxf_name, boost::signals2::signal<void (float)>* progress, int fps, int entry_point, int length, bool encrypted)
52         : MXFAsset (directory, mxf_name, progress, fps, entry_point, length, encrypted)
53         , _width (0)
54         , _height (0)
55 {
56
57 }
58
59 void
60 PictureAsset::write_to_cpl (xmlpp::Element* parent) const
61 {
62         xmlpp::Element* main_picture = parent->add_child("MainPicture");
63         main_picture->add_child("Id")->add_child_text("urn:uuid:" + _uuid);
64         main_picture->add_child("AnnotationText")->add_child_text(_file_name);
65         main_picture->add_child("EditRate")->add_child_text(boost::lexical_cast<string> (_fps) + " 1");
66         main_picture->add_child("IntrinsicDuration")->add_child_text(boost::lexical_cast<string> (_length));
67         main_picture->add_child("EntryPoint")->add_child_text("0");
68         main_picture->add_child("Duration")->add_child_text(boost::lexical_cast<string> (_length));
69         if (_encrypted) {
70                 main_picture->add_child("KeyId")->add_child_text("urn:uuid:" + _key_id);
71         }
72         main_picture->add_child("FrameRate")->add_child_text(boost::lexical_cast<string> (_fps) + " 1");
73         stringstream sar;
74         sar << _width << " " << _height;
75         main_picture->add_child("ScreenAspectRatio")->add_child_text(sar.str());
76 }
77
78 bool
79 PictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, list<string>& notes) const
80 {
81         if (!MXFAsset::equals (other, opt, notes)) {
82                 return false;
83         }
84                      
85         ASDCP::JP2K::MXFReader reader_A;
86         if (ASDCP_FAILURE (reader_A.OpenRead (path().string().c_str()))) {
87                 throw MXFFileError ("could not open MXF file for reading", path().string());
88         }
89         
90         ASDCP::JP2K::MXFReader reader_B;
91         if (ASDCP_FAILURE (reader_B.OpenRead (other->path().string().c_str()))) {
92                 throw MXFFileError ("could not open MXF file for reading", path().string());
93         }
94         
95         ASDCP::JP2K::PictureDescriptor desc_A;
96         if (ASDCP_FAILURE (reader_A.FillPictureDescriptor (desc_A))) {
97                 throw DCPReadError ("could not read video MXF information");
98         }
99         ASDCP::JP2K::PictureDescriptor desc_B;
100         if (ASDCP_FAILURE (reader_B.FillPictureDescriptor (desc_B))) {
101                 throw DCPReadError ("could not read video MXF information");
102         }
103         
104         if (
105                 desc_A.EditRate != desc_B.EditRate ||
106                 desc_A.ContainerDuration != desc_B.ContainerDuration ||
107                 desc_A.SampleRate != desc_B.SampleRate ||
108                 desc_A.StoredWidth != desc_B.StoredWidth ||
109                 desc_A.StoredHeight != desc_B.StoredHeight ||
110                 desc_A.AspectRatio != desc_B.AspectRatio ||
111                 desc_A.Rsize != desc_B.Rsize ||
112                 desc_A.Xsize != desc_B.Xsize ||
113                 desc_A.Ysize != desc_B.Ysize ||
114                 desc_A.XOsize != desc_B.XOsize ||
115                 desc_A.YOsize != desc_B.YOsize ||
116                 desc_A.XTsize != desc_B.XTsize ||
117                 desc_A.YTsize != desc_B.YTsize ||
118                 desc_A.XTOsize != desc_B.XTOsize ||
119                 desc_A.YTOsize != desc_B.YTOsize ||
120                 desc_A.Csize != desc_B.Csize
121 //              desc_A.CodingStyleDefault != desc_B.CodingStyleDefault ||
122 //              desc_A.QuantizationDefault != desc_B.QuantizationDefault
123                 ) {
124                 
125                 notes.push_back ("video MXF picture descriptors differ");
126                 return false;
127         }
128
129 //              for (unsigned int j = 0; j < ASDCP::JP2K::MaxComponents; ++j) {
130 //                      if (desc_A.ImageComponents[j] != desc_B.ImageComponents[j]) {
131 //                              notes.pack_start ("video MXF picture descriptors differ");
132 //                      }
133 //              }
134
135         return true;
136 }
137
138
139 MonoPictureAsset::MonoPictureAsset (
140         boost::function<string (int)> get_path,
141         string directory,
142         string mxf_name,
143         boost::signals2::signal<void (float)>* progress,
144         int fps,
145         int length,
146         int width,
147         int height,
148         bool encrypted)
149         : PictureAsset (directory, mxf_name, progress, fps, 0, length, encrypted)
150 {
151         _width = width;
152         _height = height;
153         construct (get_path);
154 }
155
156 MonoPictureAsset::MonoPictureAsset (
157         vector<string> const & files,
158         string directory,
159         string mxf_name,
160         boost::signals2::signal<void (float)>* progress,
161         int fps,
162         int length,
163         int width,
164         int height,
165         bool encrypted)
166         : PictureAsset (directory, mxf_name, progress, fps, 0, length, encrypted)
167 {
168         _width = width;
169         _height = height;
170         construct (boost::bind (&MonoPictureAsset::path_from_list, this, _1, files));
171 }
172
173 MonoPictureAsset::MonoPictureAsset (string directory, string mxf_name, int fps, int entry_point, int length)
174         : PictureAsset (directory, mxf_name, 0, fps, entry_point, length, false)
175 {
176         ASDCP::JP2K::MXFReader reader;
177         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
178                 throw MXFFileError ("could not open MXF file for reading", path().string());
179         }
180         
181         ASDCP::JP2K::PictureDescriptor desc;
182         if (ASDCP_FAILURE (reader.FillPictureDescriptor (desc))) {
183                 throw DCPReadError ("could not read video MXF information");
184         }
185
186         _width = desc.StoredWidth;
187         _height = desc.StoredHeight;
188 }
189
190 void
191 MonoPictureAsset::construct (boost::function<string (int)> get_path)
192 {
193         ASDCP::JP2K::CodestreamParser j2k_parser;
194         ASDCP::JP2K::FrameBuffer frame_buffer (4 * Kumu::Megabyte);
195         if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (get_path(0).c_str(), frame_buffer))) {
196                 throw FileError ("could not open JPEG2000 file for reading", get_path (0));
197         }
198         
199         ASDCP::JP2K::PictureDescriptor picture_desc;
200         j2k_parser.FillPictureDescriptor (picture_desc);
201         picture_desc.EditRate = ASDCP::Rational (_fps, 1);
202         
203         ASDCP::WriterInfo writer_info;
204         fill_writer_info (&writer_info);
205
206         ASDCP::JP2K::MXFWriter mxf_writer;
207         if (ASDCP_FAILURE (mxf_writer.OpenWrite (path().string().c_str(), writer_info, picture_desc))) {
208                 throw MXFFileError ("could not open MXF file for writing", path().string());
209         }
210
211         for (int i = 0; i < _length; ++i) {
212
213                 string const path = get_path (i);
214
215                 if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (path.c_str(), frame_buffer))) {
216                         throw FileError ("could not open JPEG2000 file for reading", path);
217                 }
218
219                 if (ASDCP_FAILURE (mxf_writer.WriteFrame (frame_buffer, _encryption_context, 0))) {
220                         throw MiscError ("error in writing video MXF");
221                 }
222
223                 if (_progress) {
224                         (*_progress) (0.5 * float (i) / _length);
225                 }
226         }
227         
228         if (ASDCP_FAILURE (mxf_writer.Finalize())) {
229                 throw MiscError ("error in finalising video MXF");
230         }
231 }
232
233 string
234 MonoPictureAsset::path_from_list (int f, vector<string> const & files) const
235 {
236         return files[f];
237 }
238
239 shared_ptr<const MonoPictureFrame>
240 MonoPictureAsset::get_frame (int n) const
241 {
242         return shared_ptr<const MonoPictureFrame> (new MonoPictureFrame (path().string(), n + _entry_point));
243 }
244
245
246 bool
247 MonoPictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, list<string>& notes) const
248 {
249         if (!PictureAsset::equals (other, opt, notes)) {
250                 return false;
251         }
252
253         shared_ptr<const MonoPictureAsset> other_picture = dynamic_pointer_cast<const MonoPictureAsset> (other);
254         assert (other_picture);
255
256         for (int i = 0; i < _length; ++i) {
257                 shared_ptr<const MonoPictureFrame> frame_A = get_frame (i);
258                 shared_ptr<const MonoPictureFrame> frame_B = other_picture->get_frame (i);
259                 
260                 if (!frame_buffer_equals (
261                             i, opt, notes,
262                             frame_A->j2k_frame()->RoData(), frame_A->j2k_frame()->Size(),
263                             frame_B->j2k_frame()->RoData(), frame_B->j2k_frame()->Size()
264                             )) {
265                         return false;
266                 }
267         }
268
269         return true;
270 }
271
272 bool
273 StereoPictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, list<string>& notes) const
274 {
275         if (!PictureAsset::equals (other, opt, notes)) {
276                 return false;
277         }
278         
279         shared_ptr<const StereoPictureAsset> other_picture = dynamic_pointer_cast<const StereoPictureAsset> (other);
280         assert (other_picture);
281
282         for (int i = 0; i < _length; ++i) {
283                 shared_ptr<const StereoPictureFrame> frame_A = get_frame (i);
284                 shared_ptr<const StereoPictureFrame> frame_B = other_picture->get_frame (i);
285                 
286                 if (!frame_buffer_equals (
287                             i, opt, notes,
288                             frame_A->j2k_frame()->Left.RoData(), frame_A->j2k_frame()->Left.Size(),
289                             frame_B->j2k_frame()->Left.RoData(), frame_B->j2k_frame()->Left.Size()
290                             )) {
291                         return false;
292                 }
293                 
294                 if (!frame_buffer_equals (
295                             i, opt, notes,
296                             frame_A->j2k_frame()->Right.RoData(), frame_A->j2k_frame()->Right.Size(),
297                             frame_B->j2k_frame()->Right.RoData(), frame_B->j2k_frame()->Right.Size()
298                             )) {
299                         return false;
300                 }
301         }
302
303         return true;
304 }
305
306 bool
307 PictureAsset::frame_buffer_equals (
308         int frame, EqualityOptions opt, list<string>& notes, uint8_t const * data_A, unsigned int size_A, uint8_t const * data_B, unsigned int size_B
309         ) const
310 {
311         if (size_A == size_B && memcmp (data_A, data_B, size_A) == 0) {
312                 /* Easy result; the J2K data is identical */
313                 return true;
314         }
315                 
316         /* Decompress the images to bitmaps */
317         opj_image_t* image_A = decompress_j2k (const_cast<uint8_t*> (data_A), size_A, 0);
318         opj_image_t* image_B = decompress_j2k (const_cast<uint8_t*> (data_B), size_B, 0);
319         
320         /* Compare them */
321         
322         if (image_A->numcomps != image_B->numcomps) {
323                 notes.push_back ("image component counts for frame " + lexical_cast<string>(frame) + " differ");
324                 return false;
325         }
326         
327         vector<int> abs_diffs (image_A->comps[0].w * image_A->comps[0].h * image_A->numcomps);
328         int d = 0;
329         int max_diff = 0;
330         
331         for (int c = 0; c < image_A->numcomps; ++c) {
332                 
333                 if (image_A->comps[c].w != image_B->comps[c].w || image_A->comps[c].h != image_B->comps[c].h) {
334                         notes.push_back ("image sizes for frame " + lexical_cast<string>(frame) + " differ");
335                         return false;
336                 }
337                 
338                 int const pixels = image_A->comps[c].w * image_A->comps[c].h;
339                 for (int j = 0; j < pixels; ++j) {
340                         int const t = abs (image_A->comps[c].data[j] - image_B->comps[c].data[j]);
341                         abs_diffs[d++] = t;
342                         max_diff = max (max_diff, t);
343                 }
344         }
345                 
346         uint64_t total = 0;
347         for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
348                 total += *j;
349         }
350         
351         double const mean = double (total) / abs_diffs.size ();
352         
353         uint64_t total_squared_deviation = 0;
354         for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
355                 total_squared_deviation += pow (*j - mean, 2);
356         }
357         
358         double const std_dev = sqrt (double (total_squared_deviation) / abs_diffs.size());
359         
360         if (mean > opt.max_mean_pixel_error || std_dev > opt.max_std_dev_pixel_error) {
361                 notes.push_back ("mean or standard deviation out of range for " + lexical_cast<string>(frame));
362                 return false;
363         }
364         
365         opj_image_destroy (image_A);
366         opj_image_destroy (image_B);
367
368         return true;
369 }
370
371
372 StereoPictureAsset::StereoPictureAsset (string directory, string mxf_name, int fps, int entry_point, int length)
373         : PictureAsset (directory, mxf_name, 0, fps, entry_point, length, false)
374 {
375         ASDCP::JP2K::MXFSReader reader;
376         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
377                 throw MXFFileError ("could not open MXF file for reading", path().string());
378         }
379         
380         ASDCP::JP2K::PictureDescriptor desc;
381         if (ASDCP_FAILURE (reader.FillPictureDescriptor (desc))) {
382                 throw DCPReadError ("could not read video MXF information");
383         }
384
385         _width = desc.StoredWidth;
386         _height = desc.StoredHeight;
387 }
388
389 shared_ptr<const StereoPictureFrame>
390 StereoPictureAsset::get_frame (int n) const
391 {
392         return shared_ptr<const StereoPictureFrame> (new StereoPictureFrame (path().string(), n + _entry_point));
393 }
394
395 string
396 PictureAsset::key_type () const
397 {
398         return "MDIK";
399 }