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