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