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