Add duration, starting off as intrinsic_duration but changeable.
[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)
50         : MXFAsset (directory, mxf_name, progress, fps, intrinsic_duration)
51 {
52
53 }
54
55 void
56 PictureAsset::write_to_cpl (ostream& s) const
57 {
58         s << "        <MainPicture>\n"
59           << "          <Id>urn:uuid:" << _uuid << "</Id>\n"
60           << "          <AnnotationText>" << _file_name << "</AnnotationText>\n"
61           << "          <EditRate>" << _fps << " 1</EditRate>\n"
62           << "          <IntrinsicDuration>" << _intrinsic_duration << "</IntrinsicDuration>\n"
63           << "          <EntryPoint>" << _entry_point << "</EntryPoint>\n"
64           << "          <Duration>" << _duration << "</Duration>\n"
65           << "          <FrameRate>" << _fps << " 1</FrameRate>\n"
66           << "          <ScreenAspectRatio>" << _size.width << " " << _size.height << "</ScreenAspectRatio>\n"
67           << "        </MainPicture>\n";
68 }
69
70 bool
71 PictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, list<string>& notes) const
72 {
73         if (!MXFAsset::equals (other, opt, notes)) {
74                 return false;
75         }
76                      
77         ASDCP::JP2K::MXFReader reader_A;
78         if (ASDCP_FAILURE (reader_A.OpenRead (path().string().c_str()))) {
79                 throw MXFFileError ("could not open MXF file for reading", path().string());
80         }
81         
82         ASDCP::JP2K::MXFReader reader_B;
83         if (ASDCP_FAILURE (reader_B.OpenRead (other->path().string().c_str()))) {
84                 throw MXFFileError ("could not open MXF file for reading", path().string());
85         }
86         
87         ASDCP::JP2K::PictureDescriptor desc_A;
88         if (ASDCP_FAILURE (reader_A.FillPictureDescriptor (desc_A))) {
89                 throw DCPReadError ("could not read video MXF information");
90         }
91         ASDCP::JP2K::PictureDescriptor desc_B;
92         if (ASDCP_FAILURE (reader_B.FillPictureDescriptor (desc_B))) {
93                 throw DCPReadError ("could not read video MXF information");
94         }
95         
96         if (
97                 desc_A.EditRate != desc_B.EditRate ||
98                 desc_A.ContainerDuration != desc_B.ContainerDuration ||
99                 desc_A.SampleRate != desc_B.SampleRate ||
100                 desc_A.StoredWidth != desc_B.StoredWidth ||
101                 desc_A.StoredHeight != desc_B.StoredHeight ||
102                 desc_A.AspectRatio != desc_B.AspectRatio ||
103                 desc_A.Rsize != desc_B.Rsize ||
104                 desc_A.Xsize != desc_B.Xsize ||
105                 desc_A.Ysize != desc_B.Ysize ||
106                 desc_A.XOsize != desc_B.XOsize ||
107                 desc_A.YOsize != desc_B.YOsize ||
108                 desc_A.XTsize != desc_B.XTsize ||
109                 desc_A.YTsize != desc_B.YTsize ||
110                 desc_A.XTOsize != desc_B.XTOsize ||
111                 desc_A.YTOsize != desc_B.YTOsize ||
112                 desc_A.Csize != desc_B.Csize
113 //              desc_A.CodingStyleDefault != desc_B.CodingStyleDefault ||
114 //              desc_A.QuantizationDefault != desc_B.QuantizationDefault
115                 ) {
116                 
117                 notes.push_back ("video MXF picture descriptors differ");
118                 return false;
119         }
120
121 //              for (unsigned int j = 0; j < ASDCP::JP2K::MaxComponents; ++j) {
122 //                      if (desc_A.ImageComponents[j] != desc_B.ImageComponents[j]) {
123 //                              notes.pack_start ("video MXF picture descriptors differ");
124 //                      }
125 //              }
126
127         return true;
128 }
129
130
131 MonoPictureAsset::MonoPictureAsset (
132         boost::function<string (int)> get_path,
133         string directory,
134         string mxf_name,
135         boost::signals2::signal<void (float)>* progress,
136         int fps,
137         int intrinsic_duration,
138         Size size)
139         : PictureAsset (directory, mxf_name, progress, fps, intrinsic_duration)
140 {
141         _size = size;
142         construct (get_path);
143 }
144
145 MonoPictureAsset::MonoPictureAsset (
146         vector<string> const & files,
147         string directory,
148         string mxf_name,
149         boost::signals2::signal<void (float)>* progress,
150         int fps,
151         int intrinsic_duration,
152         Size size)
153         : PictureAsset (directory, mxf_name, progress, fps, intrinsic_duration)
154 {
155         _size = size;
156         construct (boost::bind (&MonoPictureAsset::path_from_list, this, _1, files));
157 }
158
159 MonoPictureAsset::MonoPictureAsset (string directory, string mxf_name, int fps, int intrinsic_duration)
160         : PictureAsset (directory, mxf_name, 0, fps, intrinsic_duration)
161 {
162         ASDCP::JP2K::MXFReader reader;
163         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
164                 throw MXFFileError ("could not open MXF file for reading", path().string());
165         }
166         
167         ASDCP::JP2K::PictureDescriptor desc;
168         if (ASDCP_FAILURE (reader.FillPictureDescriptor (desc))) {
169                 throw DCPReadError ("could not read video MXF information");
170         }
171
172         _size.width = desc.StoredWidth;
173         _size.height = desc.StoredHeight;
174 }
175
176 void
177 MonoPictureAsset::construct (boost::function<string (int)> get_path)
178 {
179         ASDCP::JP2K::CodestreamParser j2k_parser;
180         ASDCP::JP2K::FrameBuffer frame_buffer (4 * Kumu::Megabyte);
181         if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (get_path(0).c_str(), frame_buffer))) {
182                 throw FileError ("could not open JPEG2000 file for reading", get_path (0));
183         }
184         
185         ASDCP::JP2K::PictureDescriptor picture_desc;
186         j2k_parser.FillPictureDescriptor (picture_desc);
187         picture_desc.EditRate = ASDCP::Rational (_fps, 1);
188         
189         ASDCP::WriterInfo writer_info;
190         fill_writer_info (&writer_info);
191         
192         ASDCP::JP2K::MXFWriter mxf_writer;
193         if (ASDCP_FAILURE (mxf_writer.OpenWrite (path().string().c_str(), writer_info, picture_desc))) {
194                 throw MXFFileError ("could not open MXF file for writing", path().string());
195         }
196
197         for (int i = 0; i < _intrinsic_duration; ++i) {
198
199                 string const path = get_path (i);
200
201                 if (ASDCP_FAILURE (j2k_parser.OpenReadFrame (path.c_str(), frame_buffer))) {
202                         throw FileError ("could not open JPEG2000 file for reading", path);
203                 }
204
205                 /* XXX: passing 0 to WriteFrame ok? */
206                 if (ASDCP_FAILURE (mxf_writer.WriteFrame (frame_buffer, 0, 0))) {
207                         throw MiscError ("error in writing video MXF");
208                 }
209
210                 if (_progress) {
211                         (*_progress) (0.5 * float (i) / _intrinsic_duration);
212                 }
213         }
214         
215         if (ASDCP_FAILURE (mxf_writer.Finalize())) {
216                 throw MiscError ("error in finalising video MXF");
217         }
218 }
219
220 string
221 MonoPictureAsset::path_from_list (int f, vector<string> const & files) const
222 {
223         return files[f];
224 }
225
226 shared_ptr<const MonoPictureFrame>
227 MonoPictureAsset::get_frame (int n) const
228 {
229         return shared_ptr<const MonoPictureFrame> (new MonoPictureFrame (path().string(), n + _entry_point));
230 }
231
232
233 bool
234 MonoPictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, list<string>& notes) const
235 {
236         if (!PictureAsset::equals (other, opt, notes)) {
237                 return false;
238         }
239
240         shared_ptr<const MonoPictureAsset> other_picture = dynamic_pointer_cast<const MonoPictureAsset> (other);
241         assert (other_picture);
242
243         for (int i = 0; i < _intrinsic_duration; ++i) {
244                 shared_ptr<const MonoPictureFrame> frame_A = get_frame (i);
245                 shared_ptr<const MonoPictureFrame> frame_B = other_picture->get_frame (i);
246                 
247                 if (!frame_buffer_equals (
248                             i, opt, notes,
249                             frame_A->j2k_frame()->RoData(), frame_A->j2k_frame()->Size(),
250                             frame_B->j2k_frame()->RoData(), frame_B->j2k_frame()->Size()
251                             )) {
252                         return false;
253                 }
254         }
255
256         return true;
257 }
258
259 bool
260 StereoPictureAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, list<string>& notes) const
261 {
262         if (!PictureAsset::equals (other, opt, notes)) {
263                 return false;
264         }
265         
266         shared_ptr<const StereoPictureAsset> other_picture = dynamic_pointer_cast<const StereoPictureAsset> (other);
267         assert (other_picture);
268
269         for (int i = 0; i < _intrinsic_duration; ++i) {
270                 shared_ptr<const StereoPictureFrame> frame_A = get_frame (i);
271                 shared_ptr<const StereoPictureFrame> frame_B = other_picture->get_frame (i);
272                 
273                 if (!frame_buffer_equals (
274                             i, opt, notes,
275                             frame_A->j2k_frame()->Left.RoData(), frame_A->j2k_frame()->Left.Size(),
276                             frame_B->j2k_frame()->Left.RoData(), frame_B->j2k_frame()->Left.Size()
277                             )) {
278                         return false;
279                 }
280                 
281                 if (!frame_buffer_equals (
282                             i, opt, notes,
283                             frame_A->j2k_frame()->Right.RoData(), frame_A->j2k_frame()->Right.Size(),
284                             frame_B->j2k_frame()->Right.RoData(), frame_B->j2k_frame()->Right.Size()
285                             )) {
286                         return false;
287                 }
288         }
289
290         return true;
291 }
292
293 bool
294 PictureAsset::frame_buffer_equals (
295         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
296         ) const
297 {
298         if (size_A == size_B && memcmp (data_A, data_B, size_A) == 0) {
299                 /* Easy result; the J2K data is identical */
300                 return true;
301         }
302                 
303         /* Decompress the images to bitmaps */
304         opj_image_t* image_A = decompress_j2k (const_cast<uint8_t*> (data_A), size_A, 0);
305         opj_image_t* image_B = decompress_j2k (const_cast<uint8_t*> (data_B), size_B, 0);
306         
307         /* Compare them */
308         
309         if (image_A->numcomps != image_B->numcomps) {
310                 notes.push_back ("image component counts for frame " + lexical_cast<string>(frame) + " differ");
311                 return false;
312         }
313         
314         vector<int> abs_diffs (image_A->comps[0].w * image_A->comps[0].h * image_A->numcomps);
315         int d = 0;
316         int max_diff = 0;
317         
318         for (int c = 0; c < image_A->numcomps; ++c) {
319                 
320                 if (image_A->comps[c].w != image_B->comps[c].w || image_A->comps[c].h != image_B->comps[c].h) {
321                         notes.push_back ("image sizes for frame " + lexical_cast<string>(frame) + " differ");
322                         return false;
323                 }
324                 
325                 int const pixels = image_A->comps[c].w * image_A->comps[c].h;
326                 for (int j = 0; j < pixels; ++j) {
327                         int const t = abs (image_A->comps[c].data[j] - image_B->comps[c].data[j]);
328                         abs_diffs[d++] = t;
329                         max_diff = max (max_diff, t);
330                 }
331         }
332                 
333         uint64_t total = 0;
334         for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
335                 total += *j;
336         }
337         
338         double const mean = double (total) / abs_diffs.size ();
339         
340         uint64_t total_squared_deviation = 0;
341         for (vector<int>::iterator j = abs_diffs.begin(); j != abs_diffs.end(); ++j) {
342                 total_squared_deviation += pow (*j - mean, 2);
343         }
344         
345         double const std_dev = sqrt (double (total_squared_deviation) / abs_diffs.size());
346         
347         if (mean > opt.max_mean_pixel_error || std_dev > opt.max_std_dev_pixel_error) {
348                 notes.push_back ("mean or standard deviation out of range for " + lexical_cast<string>(frame));
349                 return false;
350         }
351         
352         opj_image_destroy (image_A);
353         opj_image_destroy (image_B);
354
355         return true;
356 }
357
358
359 StereoPictureAsset::StereoPictureAsset (string directory, string mxf_name, int fps, int intrinsic_duration)
360         : PictureAsset (directory, mxf_name, 0, fps, intrinsic_duration)
361 {
362         ASDCP::JP2K::MXFSReader reader;
363         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
364                 throw MXFFileError ("could not open MXF file for reading", path().string());
365         }
366         
367         ASDCP::JP2K::PictureDescriptor desc;
368         if (ASDCP_FAILURE (reader.FillPictureDescriptor (desc))) {
369                 throw DCPReadError ("could not read video MXF information");
370         }
371
372         _size.width = desc.StoredWidth;
373         _size.height = desc.StoredHeight;
374 }
375
376 shared_ptr<const StereoPictureFrame>
377 StereoPictureAsset::get_frame (int n) const
378 {
379         return shared_ptr<const StereoPictureFrame> (new StereoPictureFrame (path().string(), n + _entry_point));
380 }