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