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