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