Add XYZFrame and use it.
[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
41 using std::string;
42 using std::ostream;
43 using std::list;
44 using std::vector;
45 using std::max;
46 using std::stringstream;
47 using std::pair;
48 using std::make_pair;
49 using std::istream;
50 using std::cout;
51 using boost::shared_ptr;
52 using boost::dynamic_pointer_cast;
53 using boost::lexical_cast;
54 using namespace libdcp;
55
56 PictureAsset::PictureAsset (string directory, string mxf_name, boost::signals2::signal<void (float)>* progress, int fps, int intrinsic_duration, bool encrypted, Size size)
57         : MXFAsset (directory, mxf_name, progress, fps, intrinsic_duration, encrypted)
58         , _size (size)
59 {
60
61 }
62
63 PictureAsset::PictureAsset (string directory, string mxf_name)
64         : MXFAsset (directory, mxf_name)
65 {
66
67 }
68
69 string
70 PictureAsset::cpl_node_name () const
71 {
72         return "MainPicture";
73 }
74
75 void
76 PictureAsset::write_to_cpl (xmlpp::Node* node) const
77 {
78         MXFAsset::write_to_cpl (node);
79         
80         xmlpp::Node::NodeList c = node->get_children ();
81         xmlpp::Node::NodeList::iterator i = c.begin();
82         while (i != c.end() && (*i)->get_name() != cpl_node_name ()) {
83                 ++i;
84         }
85
86         assert (i != c.end ());
87
88         (*i)->add_child ("FrameRate")->add_child_text (lexical_cast<string> (_edit_rate) + " 1");
89         (*i)->add_child ("ScreenAspectRatio")->add_child_text (lexical_cast<string> (_size.width) + " " + lexical_cast<string> (_size.height));
90 }
91
92 bool
93 PictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
94 {
95         if (!MXFAsset::equals (other, opt, note)) {
96                 return false;
97         }
98                      
99         ASDCP::JP2K::MXFReader reader_A;
100         if (ASDCP_FAILURE (reader_A.OpenRead (path().string().c_str()))) {
101                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
102         }
103         
104         ASDCP::JP2K::MXFReader reader_B;
105         if (ASDCP_FAILURE (reader_B.OpenRead (other->path().string().c_str()))) {
106                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
107         }
108         
109         ASDCP::JP2K::PictureDescriptor desc_A;
110         if (ASDCP_FAILURE (reader_A.FillPictureDescriptor (desc_A))) {
111                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
112         }
113         ASDCP::JP2K::PictureDescriptor desc_B;
114         if (ASDCP_FAILURE (reader_B.FillPictureDescriptor (desc_B))) {
115                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
116         }
117         
118         if (
119                 desc_A.EditRate != desc_B.EditRate ||
120                 desc_A.ContainerDuration != desc_B.ContainerDuration ||
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 //              for (unsigned int j = 0; j < ASDCP::JP2K::MaxComponents; ++j) {
144 //                      if (desc_A.ImageComponents[j] != desc_B.ImageComponents[j]) {
145 //                              notes.pack_start ("video MXF picture descriptors differ");
146 //                      }
147 //              }
148
149         return true;
150 }
151
152
153 MonoPictureAsset::MonoPictureAsset (
154         boost::function<string (int)> get_path,
155         string directory,
156         string mxf_name,
157         boost::signals2::signal<void (float)>* progress,
158         int fps,
159         int intrinsic_duration,
160         bool encrypted,
161         Size size,
162         MXFMetadata const & metadata
163         )
164         : PictureAsset (directory, mxf_name, progress, fps, intrinsic_duration, encrypted, size)
165 {
166         construct (get_path, metadata);
167 }
168
169 MonoPictureAsset::MonoPictureAsset (
170         vector<string> const & files,
171         string directory,
172         string mxf_name,
173         boost::signals2::signal<void (float)>* progress,
174         int fps,
175         int intrinsic_duration,
176         bool encrypted,
177         Size size,
178         MXFMetadata const & metadata
179         )
180         : PictureAsset (directory, mxf_name, progress, fps, intrinsic_duration, encrypted, size)
181 {
182         construct (boost::bind (&MonoPictureAsset::path_from_list, this, _1, files), metadata);
183 }
184
185 MonoPictureAsset::MonoPictureAsset (string directory, string mxf_name, int fps, Size size)
186         : PictureAsset (directory, mxf_name, 0, fps, 0, false, size)
187 {
188
189 }
190
191 MonoPictureAsset::MonoPictureAsset (string directory, string mxf_name)
192         : PictureAsset (directory, mxf_name)
193 {
194         ASDCP::JP2K::MXFReader reader;
195         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
196                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
197         }
198         
199         ASDCP::JP2K::PictureDescriptor desc;
200         if (ASDCP_FAILURE (reader.FillPictureDescriptor (desc))) {
201                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
202         }
203
204         _size.width = desc.StoredWidth;
205         _size.height = desc.StoredHeight;
206         _edit_rate = desc.EditRate.Numerator;
207         assert (desc.EditRate.Denominator == 1);
208         _intrinsic_duration = desc.ContainerDuration;
209 }
210
211 void
212 MonoPictureAsset::construct (boost::function<string (int)> get_path, MXFMetadata const & metadata)
213 {
214         ASDCP::JP2K::CodestreamParser j2k_parser;
215         ASDCP::JP2K::FrameBuffer frame_buffer (4 * Kumu::Megabyte);
216         if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (get_path(0).c_str(), frame_buffer))) {
217                 boost::throw_exception (FileError ("could not open JPEG2000 file for reading", get_path (0)));
218         }
219         
220         ASDCP::JP2K::PictureDescriptor picture_desc;
221         j2k_parser.FillPictureDescriptor (picture_desc);
222         picture_desc.EditRate = ASDCP::Rational (_edit_rate, 1);
223         
224         ASDCP::WriterInfo writer_info;
225         fill_writer_info (&writer_info, _uuid, metadata);
226         
227         ASDCP::JP2K::MXFWriter mxf_writer;
228         if (ASDCP_FAILURE (mxf_writer.OpenWrite (path().string().c_str(), writer_info, picture_desc, 16384, false))) {
229                 boost::throw_exception (MXFFileError ("could not open MXF file for writing", path().string()));
230         }
231
232         for (int i = 0; i < _intrinsic_duration; ++i) {
233
234                 string const path = get_path (i);
235
236                 if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (path.c_str(), frame_buffer))) {
237                         boost::throw_exception (FileError ("could not open JPEG2000 file for reading", path));
238                 }
239
240                 if (ASDCP_FAILURE (mxf_writer.WriteFrame (frame_buffer, _encryption_context, 0))) {
241                         boost::throw_exception (MXFFileError ("error in writing video MXF", this->path().string()));
242                 }
243
244                 if (_progress) {
245                         (*_progress) (0.5 * float (i) / _intrinsic_duration);
246                 }
247         }
248         
249         if (ASDCP_FAILURE (mxf_writer.Finalize())) {
250                 boost::throw_exception (MXFFileError ("error in finalising video MXF", path().string()));
251         }
252 }
253
254 string
255 MonoPictureAsset::path_from_list (int f, vector<string> const & files) const
256 {
257         return files[f];
258 }
259
260 shared_ptr<const MonoPictureFrame>
261 MonoPictureAsset::get_frame (int n) const
262 {
263         return shared_ptr<const MonoPictureFrame> (new MonoPictureFrame (path().string(), n, _decryption_context));
264 }
265
266
267 bool
268 MonoPictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
269 {
270         if (!PictureAsset::equals (other, opt, note)) {
271                 return false;
272         }
273
274         shared_ptr<const MonoPictureAsset> other_picture = dynamic_pointer_cast<const MonoPictureAsset> (other);
275         assert (other_picture);
276
277         for (int i = 0; i < _intrinsic_duration; ++i) {
278                 note (PROGRESS, "Comparing video frame " + lexical_cast<string> (i) + " of " + lexical_cast<string> (_intrinsic_duration));
279                 shared_ptr<const MonoPictureFrame> frame_A = get_frame (i);
280                 shared_ptr<const MonoPictureFrame> frame_B = other_picture->get_frame (i);
281                 
282                 if (!frame_buffer_equals (
283                             i, opt, note,
284                             frame_A->j2k_data(), frame_A->j2k_size(),
285                             frame_B->j2k_data(), frame_B->j2k_size()
286                             )) {
287                         return false;
288                 }
289         }
290
291         return true;
292 }
293
294 bool
295 StereoPictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
296 {
297         if (!PictureAsset::equals (other, opt, note)) {
298                 return false;
299         }
300         
301         shared_ptr<const StereoPictureAsset> other_picture = dynamic_pointer_cast<const StereoPictureAsset> (other);
302         assert (other_picture);
303
304         for (int i = 0; i < _intrinsic_duration; ++i) {
305                 shared_ptr<const StereoPictureFrame> frame_A = get_frame (i);
306                 shared_ptr<const StereoPictureFrame> frame_B = other_picture->get_frame (i);
307                 
308                 if (!frame_buffer_equals (
309                             i, opt, note,
310                             frame_A->left_j2k_data(), frame_A->left_j2k_size(),
311                             frame_B->left_j2k_data(), frame_B->left_j2k_size()
312                             )) {
313                         return false;
314                 }
315                 
316                 if (!frame_buffer_equals (
317                             i, opt, note,
318                             frame_A->right_j2k_data(), frame_A->right_j2k_size(),
319                             frame_B->right_j2k_data(), frame_B->right_j2k_size()
320                             )) {
321                         return false;
322                 }
323         }
324
325         return true;
326 }
327
328 bool
329 PictureAsset::frame_buffer_equals (
330         int frame, EqualityOptions opt, boost::function<void (NoteType, string)> note,
331         uint8_t const * data_A, unsigned int size_A, uint8_t const * data_B, unsigned int size_B
332         ) const
333 {
334         if (size_A == size_B && memcmp (data_A, data_B, size_A) == 0) {
335                 note (NOTE, "J2K identical");
336                 /* Easy result; the J2K data is identical */
337                 return true;
338         }
339                 
340         /* Decompress the images to bitmaps */
341         shared_ptr<XYZFrame> image_A = decompress_j2k (const_cast<uint8_t*> (data_A), size_A, 0);
342         shared_ptr<XYZFrame> image_B = decompress_j2k (const_cast<uint8_t*> (data_B), size_B, 0);
343         
344         /* Compare them */
345         
346         vector<int> abs_diffs (image_A->size().width * image_A->size().height * 3);
347         int d = 0;
348         int max_diff = 0;
349         
350         for (int c = 0; c < 3; ++c) {
351                 
352                 if (image_A->size() != image_B->size()) {
353                         note (ERROR, "image sizes for frame " + lexical_cast<string>(frame) + " differ");
354                         return false;
355                 }
356                 
357                 int const pixels = image_A->size().width * image_A->size().height;
358                 for (int j = 0; j < pixels; ++j) {
359                         int const t = abs (image_A->data(c)[j] - image_B->data(c)[j]);
360                         abs_diffs[d++] = t;
361                         max_diff = max (max_diff, t);
362                 }
363         }
364                 
365         uint64_t total = 0;
366         for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
367                 total += *j;
368         }
369         
370         double const mean = double (total) / abs_diffs.size ();
371         
372         uint64_t total_squared_deviation = 0;
373         for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
374                 total_squared_deviation += pow (*j - mean, 2);
375         }
376         
377         double const std_dev = sqrt (double (total_squared_deviation) / abs_diffs.size());
378         
379         note (NOTE, "mean difference " + lexical_cast<string> (mean) + ", deviation " + lexical_cast<string> (std_dev));
380         
381         if (mean > opt.max_mean_pixel_error) {
382                 note (ERROR, "mean " + lexical_cast<string>(mean) + " out of range " + lexical_cast<string>(opt.max_mean_pixel_error) + " in frame " + lexical_cast<string>(frame));
383                 return false;
384         }
385
386         if (std_dev > opt.max_std_dev_pixel_error) {
387                 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));
388                 return false;
389         }
390
391         return true;
392 }
393
394
395 StereoPictureAsset::StereoPictureAsset (string directory, string mxf_name, int fps, int intrinsic_duration)
396         : PictureAsset (directory, mxf_name, 0, fps, intrinsic_duration, false, Size (0, 0))
397 {
398         ASDCP::JP2K::MXFSReader reader;
399         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
400                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
401         }
402         
403         ASDCP::JP2K::PictureDescriptor desc;
404         if (ASDCP_FAILURE (reader.FillPictureDescriptor (desc))) {
405                 boost::throw_exception (DCPReadError ("could not read video MXF information"));
406         }
407
408         _size.width = desc.StoredWidth;
409         _size.height = desc.StoredHeight;
410 }
411
412 shared_ptr<const StereoPictureFrame>
413 StereoPictureAsset::get_frame (int n) const
414 {
415         return shared_ptr<const StereoPictureFrame> (new StereoPictureFrame (path().string(), n));
416 }
417
418 shared_ptr<MonoPictureAssetWriter>
419 MonoPictureAsset::start_write (bool overwrite, MXFMetadata const & metadata)
420 {
421         /* XXX: can't we use shared_ptr here? */
422         return shared_ptr<MonoPictureAssetWriter> (new MonoPictureAssetWriter (this, overwrite, metadata));
423 }
424
425 FrameInfo::FrameInfo (istream& s)
426 {
427         s >> offset >> size >> hash;
428 }
429
430 void
431 FrameInfo::write (ostream& s)
432 {
433         s << offset << " " << size << " " << hash;
434 }
435
436 struct MonoPictureAssetWriter::ASDCPState
437 {
438         ASDCPState()
439                 : frame_buffer (4 * Kumu::Megabyte)
440         {}
441         
442         ASDCP::JP2K::CodestreamParser j2k_parser;
443         ASDCP::JP2K::FrameBuffer frame_buffer;
444         ASDCP::JP2K::MXFWriter mxf_writer;
445         ASDCP::WriterInfo writer_info;
446         ASDCP::JP2K::PictureDescriptor picture_descriptor;
447 };
448
449
450 /** @param a Asset to write to.  `a' must not be deleted while
451  *  this writer class still exists, or bad things will happen.
452  */
453 MonoPictureAssetWriter::MonoPictureAssetWriter (MonoPictureAsset* a, bool overwrite, MXFMetadata const & m)
454         : _state (new MonoPictureAssetWriter::ASDCPState)
455         , _asset (a)
456         , _frames_written (0)
457         , _started (false)
458         , _finalized (false)
459         , _overwrite (overwrite)
460         , _metadata (m)
461 {
462
463 }
464
465
466 void
467 MonoPictureAssetWriter::start (uint8_t* data, int size)
468 {
469         if (ASDCP_FAILURE (_state->j2k_parser.OpenReadFrame (data, size, _state->frame_buffer))) {
470                 boost::throw_exception (MiscError ("could not parse J2K frame"));
471         }
472
473         _state->j2k_parser.FillPictureDescriptor (_state->picture_descriptor);
474         _state->picture_descriptor.EditRate = ASDCP::Rational (_asset->edit_rate(), 1);
475         
476         _asset->fill_writer_info (&_state->writer_info, _asset->uuid(), _metadata);
477         
478         if (ASDCP_FAILURE (_state->mxf_writer.OpenWrite (
479                                    _asset->path().string().c_str(),
480                                    _state->writer_info,
481                                    _state->picture_descriptor,
482                                    16384,
483                                    _overwrite)
484                     )) {
485                 
486                 boost::throw_exception (MXFFileError ("could not open MXF file for writing", _asset->path().string()));
487         }
488
489         _started = true;
490 }
491
492 FrameInfo
493 MonoPictureAssetWriter::write (uint8_t* data, int size)
494 {
495         assert (!_finalized);
496
497         if (!_started) {
498                 start (data, size);
499         }
500
501         if (ASDCP_FAILURE (_state->j2k_parser.OpenReadFrame (data, size, _state->frame_buffer))) {
502                 boost::throw_exception (MiscError ("could not parse J2K frame"));
503         }
504
505         uint64_t const before_offset = _state->mxf_writer.Tell ();
506
507         string hash;
508         if (ASDCP_FAILURE (_state->mxf_writer.WriteFrame (_state->frame_buffer, 0, 0, &hash))) {
509                 boost::throw_exception (MXFFileError ("error in writing video MXF", _asset->path().string()));
510         }
511
512         ++_frames_written;
513         return FrameInfo (before_offset, _state->mxf_writer.Tell() - before_offset, hash);
514 }
515
516 void
517 MonoPictureAssetWriter::fake_write (int size)
518 {
519         assert (_started);
520         assert (!_finalized);
521
522         if (ASDCP_FAILURE (_state->mxf_writer.FakeWriteFrame (size))) {
523                 boost::throw_exception (MXFFileError ("error in writing video MXF", _asset->path().string()));
524         }
525
526         ++_frames_written;
527 }
528
529 void
530 MonoPictureAssetWriter::finalize ()
531 {
532         assert (!_finalized);
533         
534         if (ASDCP_FAILURE (_state->mxf_writer.Finalize())) {
535                 boost::throw_exception (MXFFileError ("error in finalizing video MXF", _asset->path().string()));
536         }
537
538         _finalized = true;
539         _asset->set_intrinsic_duration (_frames_written);
540         _asset->set_duration (_frames_written);
541 }
542
543 string
544 PictureAsset::key_type () const
545 {
546         return "MDIK";
547 }