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