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