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