Tidy up equality options slightly.
[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 "AS_DCP.h"
33 #include "KM_fileio.h"
34 #include "picture_asset.h"
35 #include "util.h"
36 #include "exceptions.h"
37
38 using namespace std;
39 using namespace boost;
40 using namespace libdcp;
41
42 PictureAsset::PictureAsset (
43         sigc::slot<string, int> get_path,
44         string directory,
45         string mxf_name,
46         sigc::signal1<void, float>* progress,
47         int fps,
48         int length,
49         int width,
50         int height)
51         : Asset (directory, mxf_name, progress, fps, length)
52         , _width (width)
53         , _height (height)
54 {
55         construct (get_path);
56 }
57
58 PictureAsset::PictureAsset (
59         vector<string> const & files,
60         string directory,
61         string mxf_name,
62         sigc::signal1<void, float>* progress,
63         int fps,
64         int length,
65         int width,
66         int height)
67         : Asset (directory, mxf_name, progress, fps, length)
68         , _width (width)
69         , _height (height)
70 {
71         construct (sigc::bind (sigc::mem_fun (*this, &PictureAsset::path_from_list), files));
72 }
73
74 PictureAsset::PictureAsset (string directory, string mxf_name, int fps, int length, int width, int height)
75         : Asset (directory, mxf_name, 0, fps, length)
76         , _width (width)
77         , _height (height)
78 {
79
80 }
81
82 string
83 PictureAsset::path_from_list (int f, vector<string> const & files) const
84 {
85         return files[f];
86 }
87
88 void
89 PictureAsset::construct (sigc::slot<string, int> get_path)
90 {
91         ASDCP::JP2K::CodestreamParser j2k_parser;
92         ASDCP::JP2K::FrameBuffer frame_buffer (4 * Kumu::Megabyte);
93         if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (get_path(0).c_str(), frame_buffer))) {
94                 throw FileError ("could not open JPEG2000 file for reading", get_path (0));
95         }
96         
97         ASDCP::JP2K::PictureDescriptor picture_desc;
98         j2k_parser.FillPictureDescriptor (picture_desc);
99         picture_desc.EditRate = ASDCP::Rational (_fps, 1);
100         
101         ASDCP::WriterInfo writer_info;
102         fill_writer_info (&writer_info);
103         
104         ASDCP::JP2K::MXFWriter mxf_writer;
105         if (ASDCP_FAILURE (mxf_writer.OpenWrite (mxf_path().string().c_str(), writer_info, picture_desc))) {
106                 throw FileError ("could not open MXF file for writing", mxf_path().string());
107         }
108
109         for (int i = 0; i < _length; ++i) {
110
111                 string const path = get_path (i);
112                 
113                 if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (path.c_str(), frame_buffer))) {
114                         throw FileError ("could not open JPEG2000 file for reading", path);
115                 }
116
117                 /* XXX: passing 0 to WriteFrame ok? */
118                 if (ASDCP_FAILURE (mxf_writer.WriteFrame (frame_buffer, 0, 0))) {
119                         throw MiscError ("error in writing video MXF");
120                 }
121                 
122                 (*_progress) (0.5 * float (i) / _length);
123         }
124         
125         if (ASDCP_FAILURE (mxf_writer.Finalize())) {
126                 throw MiscError ("error in finalising video MXF");
127         }
128 }
129
130 void
131 PictureAsset::write_to_cpl (ostream& s) const
132 {
133         s << "        <MainPicture>\n"
134           << "          <Id>urn:uuid:" << _uuid << "</Id>\n"
135           << "          <AnnotationText>" << _mxf_name << "</AnnotationText>\n"
136           << "          <EditRate>" << _fps << " 1</EditRate>\n"
137           << "          <IntrinsicDuration>" << _length << "</IntrinsicDuration>\n"
138           << "          <EntryPoint>0</EntryPoint>\n"
139           << "          <Duration>" << _length << "</Duration>\n"
140           << "          <FrameRate>" << _fps << " 1</FrameRate>\n"
141           << "          <ScreenAspectRatio>" << _width << " " << _height << "</ScreenAspectRatio>\n"
142           << "        </MainPicture>\n";
143 }
144
145 list<string>
146 PictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt) const
147 {
148         list<string> notes = Asset::equals (other, opt);
149                      
150         if (opt.flags & MXF_INSPECT) {
151                 ASDCP::JP2K::MXFReader reader_A;
152                 if (ASDCP_FAILURE (reader_A.OpenRead (mxf_path().string().c_str()))) {
153                         throw FileError ("could not open MXF file for reading", mxf_path().string());
154                 }
155
156                 ASDCP::JP2K::MXFReader reader_B;
157                 if (ASDCP_FAILURE (reader_B.OpenRead (other->mxf_path().string().c_str()))) {
158                         throw FileError ("could not open MXF file for reading", mxf_path().string());
159                 }
160
161                 ASDCP::JP2K::PictureDescriptor desc_A;
162                 if (ASDCP_FAILURE (reader_A.FillPictureDescriptor (desc_A))) {
163                         throw DCPReadError ("could not read video MXF information");
164                 }
165                 ASDCP::JP2K::PictureDescriptor desc_B;
166                 if (ASDCP_FAILURE (reader_B.FillPictureDescriptor (desc_B))) {
167                         throw DCPReadError ("could not read video MXF information");
168                 }
169
170                 if (
171                         desc_A.EditRate != desc_B.EditRate ||
172                         desc_A.ContainerDuration != desc_B.ContainerDuration ||
173                         desc_A.SampleRate != desc_B.SampleRate ||
174                         desc_A.StoredWidth != desc_B.StoredWidth ||
175                         desc_A.StoredHeight != desc_B.StoredHeight ||
176                         desc_A.AspectRatio != desc_B.AspectRatio ||
177                         desc_A.Rsize != desc_B.Rsize ||
178                         desc_A.Xsize != desc_B.Xsize ||
179                         desc_A.Ysize != desc_B.Ysize ||
180                         desc_A.XOsize != desc_B.XOsize ||
181                         desc_A.YOsize != desc_B.YOsize ||
182                         desc_A.XTsize != desc_B.XTsize ||
183                         desc_A.YTsize != desc_B.YTsize ||
184                         desc_A.XTOsize != desc_B.XTOsize ||
185                         desc_A.YTOsize != desc_B.YTOsize ||
186                         desc_A.Csize != desc_B.Csize
187 //                      desc_A.CodingStyleDefault != desc_B.CodingStyleDefault ||
188 //                      desc_A.QuantizationDefault != desc_B.QuantizationDefault
189                         ) {
190                 
191                         notes.push_back ("video MXF picture descriptors differ");
192                 }
193
194 //              for (unsigned int j = 0; j < ASDCP::JP2K::MaxComponents; ++j) {
195 //                      if (desc_A.ImageComponents[j] != desc_B.ImageComponents[j]) {
196 //                              notes.pack_start ("video MXF picture descriptors differ");
197 //                      }
198 //              }
199                                 
200
201                 ASDCP::JP2K::FrameBuffer buffer_A (4 * Kumu::Megabyte);
202                 ASDCP::JP2K::FrameBuffer buffer_B (4 * Kumu::Megabyte);
203
204                 for (int i = 0; i < _length; ++i) {
205                         if (ASDCP_FAILURE (reader_A.ReadFrame (i, buffer_A))) {
206                                 throw DCPReadError ("could not read video frame");
207                         }
208
209                         if (ASDCP_FAILURE (reader_B.ReadFrame (i, buffer_B))) {
210                                 throw DCPReadError ("could not read video frame");
211                         }
212
213                         bool j2k_same = true;
214
215                         if (buffer_A.Size() != buffer_B.Size()) {
216                                 notes.push_back ("sizes of video data for frame " + lexical_cast<string>(i) + " differ");
217                                 j2k_same = false;
218                         } else if (memcmp (buffer_A.RoData(), buffer_B.RoData(), buffer_A.Size()) != 0) {
219                                 notes.push_back ("J2K data for frame " + lexical_cast<string>(i) + " differ");
220                                 j2k_same = false;
221                         }
222
223                         if (!j2k_same) {
224
225                                 if (opt.verbose) {
226                                         cout << "J2K images for " << i << " differ; checking by pixel\n";
227                                 }
228                                 
229                                 /* Decompress the images to bitmaps */
230                                 opj_image_t* image_A = decompress_j2k (const_cast<uint8_t*> (buffer_A.RoData()), buffer_A.Size ());
231                                 opj_image_t* image_B = decompress_j2k (const_cast<uint8_t*> (buffer_B.RoData()), buffer_B.Size ());
232
233                                 /* Compare them */
234                                 
235                                 if (image_A->numcomps != image_B->numcomps) {
236                                         notes.push_back ("image component counts for frame " + lexical_cast<string>(i) + " differ");
237                                 }
238
239                                 vector<int> abs_diffs (image_A->comps[0].w * image_A->comps[0].h * image_A->numcomps);
240                                 int d = 0;
241
242                                 for (int c = 0; c < image_A->numcomps; ++c) {
243
244                                         if (image_A->comps[c].w != image_B->comps[c].w || image_A->comps[c].h != image_B->comps[c].h) {
245                                                 notes.push_back ("image sizes for frame " + lexical_cast<string>(i) + " differ");
246                                         }
247
248                                         int const pixels = image_A->comps[c].w * image_A->comps[c].h;
249                                         for (int j = 0; j < pixels; ++j) {
250                                                 abs_diffs[d++] = abs (image_A->comps[c].data[j] - image_B->comps[c].data[j]);
251                                         }
252                                 }
253
254                                 uint64_t total = 0;
255                                 for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
256                                         total += *j;
257                                 }
258
259                                 double const mean = double (total) / abs_diffs.size ();
260
261                                 uint64_t total_squared_deviation = 0;
262                                 for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
263                                         total_squared_deviation += pow (*j - mean, 2);
264                                 }
265
266                                 double const std_dev = sqrt (double (total_squared_deviation) / abs_diffs.size());
267
268                                 if (mean > opt.max_mean_pixel_error || std_dev > opt.max_std_dev_pixel_error) {
269                                         notes.push_back ("mean or standard deviation out of range for " + lexical_cast<string>(i));
270                                 }
271
272                                 if (opt.verbose) {
273                                         cout << "\tmean pixel error " << mean << ", standard deviation " << std_dev << "\n";
274                                 }
275
276                                 opj_image_destroy (image_A);
277                                 opj_image_destroy (image_B);
278                         }
279                 }
280         }
281
282         return notes;
283 }
284
285 opj_image_t *
286 PictureAsset::decompress_j2k (uint8_t* data, int64_t size) const
287 {
288         opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
289         opj_dparameters_t parameters;
290         opj_set_default_decoder_parameters (&parameters);
291         opj_setup_decoder (decoder, &parameters);
292         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
293         opj_image_t* image = opj_decode (decoder, cio);
294         if (!image) {
295                 opj_destroy_decompress (decoder);
296                 opj_cio_close (cio);
297                 throw DCPReadError ("could not decode JPEG2000 codestream");
298         }
299
300         opj_cio_close (cio);
301         return image;
302 }