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