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