Various probably quite untidy progress on KDMs.
[libdcp.git] / src / sound_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/sound_asset.cc
21  *  @brief An asset made up of WAV files
22  */
23
24 #include <iostream>
25 #include <stdexcept>
26 #include <boost/filesystem.hpp>
27 #include <boost/lexical_cast.hpp>
28 #include <libxml++/nodes/element.h>
29 #include "KM_fileio.h"
30 #include "AS_DCP.h"
31 #include "sound_asset.h"
32 #include "util.h"
33 #include "exceptions.h"
34 #include "sound_frame.h"
35
36 using std::string;
37 using std::stringstream;
38 using std::ostream;
39 using std::vector;
40 using std::list;
41 using boost::shared_ptr;
42 using boost::lexical_cast;
43 using namespace libdcp;
44
45 SoundAsset::SoundAsset (
46         vector<string> const & files, string directory, string mxf_name, boost::signals2::signal<void (float)>* progress, int fps, int length, bool encrypted
47         )
48         : MXFAsset (directory, mxf_name, progress, fps, 0, length, encrypted)
49         , _channels (files.size ())
50         , _sampling_rate (0)
51 {
52         construct (boost::bind (&SoundAsset::path_from_channel, this, _1, files));
53 }
54
55 SoundAsset::SoundAsset (
56         boost::function<string (Channel)> get_path,
57         string directory,
58         string mxf_name,
59         boost::signals2::signal<void (float)>* progress,
60         int fps, int length, int channels, bool encrypted
61         )
62         : MXFAsset (directory, mxf_name, progress, fps, 0, length, encrypted)
63         , _channels (channels)
64         , _sampling_rate (0)
65 {
66         construct (get_path);
67 }
68
69 SoundAsset::SoundAsset (string directory, string mxf_name, int fps, int entry_point, int length)
70         : MXFAsset (directory, mxf_name, 0, fps, entry_point, length, false)
71         , _channels (0)
72 {
73         ASDCP::PCM::MXFReader reader;
74         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
75                 throw MXFFileError ("could not open MXF file for reading", path().string());
76         }
77
78         
79         ASDCP::PCM::AudioDescriptor desc;
80         if (ASDCP_FAILURE (reader.FillAudioDescriptor (desc))) {
81                 throw DCPReadError ("could not read audio MXF information");
82         }
83
84         _sampling_rate = desc.AudioSamplingRate.Numerator / desc.AudioSamplingRate.Denominator;
85         _channels = desc.ChannelCount;
86 }
87
88 string
89 SoundAsset::path_from_channel (Channel channel, vector<string> const & files)
90 {
91         unsigned int const c = int (channel);
92         assert (c < files.size ());
93         return files[c];
94 }
95
96 void
97 SoundAsset::construct (boost::function<string (Channel)> get_path)
98 {
99         ASDCP::Rational asdcp_fps (_fps, 1);
100         
101         ASDCP::PCM::WAVParser pcm_parser_channel[_channels];
102         if (pcm_parser_channel[0].OpenRead (get_path(LEFT).c_str(), asdcp_fps)) {
103                 throw FileError ("could not open WAV file for reading", get_path(LEFT));
104         }
105         
106         ASDCP::PCM::AudioDescriptor audio_desc;
107         pcm_parser_channel[0].FillAudioDescriptor (audio_desc);
108         audio_desc.ChannelCount = 0;
109         audio_desc.BlockAlign = 0;
110         audio_desc.EditRate = asdcp_fps;
111         audio_desc.AvgBps = audio_desc.AvgBps * _channels;
112
113         Channel channels[] = {
114                 LEFT,
115                 RIGHT,
116                 CENTRE,
117                 LFE,
118                 LS,
119                 RS,
120                 /* XXX: not quite sure what these should be yet */
121                 CHANNEL_7,
122                 CHANNEL_8
123         };
124
125         assert (int(_channels) <= int(sizeof(channels) / sizeof(Channel)));
126
127         ASDCP::PCM::FrameBuffer frame_buffer_channel[_channels];
128         ASDCP::PCM::AudioDescriptor audio_desc_channel[_channels];
129
130         for (int i = 0; i < _channels; ++i) {
131
132                 string const path = get_path (channels[i]);
133                 
134                 if (ASDCP_FAILURE (pcm_parser_channel[i].OpenRead (path.c_str(), asdcp_fps))) {
135                         throw FileError ("could not open WAV file for reading", path);
136                 }
137
138                 pcm_parser_channel[i].FillAudioDescriptor (audio_desc_channel[i]);
139                 frame_buffer_channel[i].Capacity (ASDCP::PCM::CalcFrameBufferSize (audio_desc_channel[i]));
140
141                 audio_desc.ChannelCount += audio_desc_channel[i].ChannelCount;
142                 audio_desc.BlockAlign += audio_desc_channel[i].BlockAlign;
143         }
144
145         ASDCP::PCM::FrameBuffer frame_buffer;
146         frame_buffer.Capacity (ASDCP::PCM::CalcFrameBufferSize (audio_desc));
147         frame_buffer.Size (ASDCP::PCM::CalcFrameBufferSize (audio_desc));
148
149         ASDCP::WriterInfo writer_info;
150         fill_writer_info (&writer_info);
151
152         ASDCP::PCM::MXFWriter mxf_writer;
153         if (ASDCP_FAILURE (mxf_writer.OpenWrite (path().string().c_str(), writer_info, audio_desc))) {
154                 throw FileError ("could not open audio MXF for writing", path().string());
155         }
156
157         for (int i = 0; i < _length; ++i) {
158
159                 for (int j = 0; j < _channels; ++j) {
160                         memset (frame_buffer_channel[j].Data(), 0, frame_buffer_channel[j].Capacity());
161                         if (ASDCP_FAILURE (pcm_parser_channel[j].ReadFrame (frame_buffer_channel[j]))) {
162                                 throw MiscError ("could not read audio frame");
163                         }
164                 }
165
166                 byte_t *data_s = frame_buffer.Data();
167                 byte_t *data_e = data_s + frame_buffer.Capacity();
168                 byte_t sample_size = ASDCP::PCM::CalcSampleSize (audio_desc_channel[0]);
169                 int offset = 0;
170
171                 while (data_s < data_e) {
172                         for (int j = 0; j < _channels; ++j) {
173                                 byte_t* frame = frame_buffer_channel[j].Data() + offset;
174                                 memcpy (data_s, frame, sample_size);
175                                 data_s += sample_size;
176                         }
177                         offset += sample_size;
178                 }
179
180                 if (ASDCP_FAILURE (mxf_writer.WriteFrame (frame_buffer, _encryption_context, 0))) {
181                         throw MiscError ("could not write audio MXF frame");
182                 }
183
184                 if (_progress) {
185                         (*_progress) (0.5 * float (i) / _length);
186                 }
187         }
188
189         if (ASDCP_FAILURE (mxf_writer.Finalize())) {
190                 throw MiscError ("could not finalise audio MXF");
191         }
192 }
193
194 void
195 SoundAsset::write_to_cpl (xmlpp::Element* parent) const
196 {
197         xmlpp::Element* main_sound = parent->add_child("MainSound");
198         main_sound->add_child("Id")->add_child_text("urn:uuid:" + _uuid);
199         main_sound->add_child("AnnotationText")->add_child_text(_file_name);
200         main_sound->add_child("EditRate")->add_child_text(boost::lexical_cast<string> (_fps) + " 1");
201         main_sound->add_child("IntrinsicDuration")->add_child_text(boost::lexical_cast<string> (_length));
202         main_sound->add_child("EntryPoint")->add_child_text("0");
203         main_sound->add_child("Duration")->add_child_text(boost::lexical_cast<string> (_length));
204         if (_encrypted) {
205                 main_sound->add_child("KeyId")->add_child_text("urn:uuid:" + _key_id);
206         }
207 }
208
209 bool
210 SoundAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, list<string>& notes) const
211 {
212         if (!MXFAsset::equals (other, opt, notes)) {
213                 return false;
214         }
215                      
216         ASDCP::PCM::MXFReader reader_A;
217         if (ASDCP_FAILURE (reader_A.OpenRead (path().string().c_str()))) {
218                 throw MXFFileError ("could not open MXF file for reading", path().string());
219         }
220
221         ASDCP::PCM::MXFReader reader_B;
222         if (ASDCP_FAILURE (reader_B.OpenRead (other->path().string().c_str()))) {
223                 throw MXFFileError ("could not open MXF file for reading", path().string());
224         }
225
226         ASDCP::PCM::AudioDescriptor desc_A;
227         if (ASDCP_FAILURE (reader_A.FillAudioDescriptor (desc_A))) {
228                 throw DCPReadError ("could not read audio MXF information");
229         }
230         ASDCP::PCM::AudioDescriptor desc_B;
231         if (ASDCP_FAILURE (reader_B.FillAudioDescriptor (desc_B))) {
232                 throw DCPReadError ("could not read audio MXF information");
233         }
234         
235         if (
236                 desc_A.EditRate != desc_B.EditRate ||
237                 desc_A.AudioSamplingRate != desc_B.AudioSamplingRate ||
238                 desc_A.Locked != desc_B.Locked ||
239                 desc_A.ChannelCount != desc_B.ChannelCount ||
240                 desc_A.QuantizationBits != desc_B.QuantizationBits ||
241                 desc_A.BlockAlign != desc_B.BlockAlign ||
242                 desc_A.AvgBps != desc_B.AvgBps ||
243                 desc_A.LinkedTrackID != desc_B.LinkedTrackID ||
244                 desc_A.ContainerDuration != desc_B.ContainerDuration
245 //              desc_A.ChannelFormat != desc_B.ChannelFormat ||
246                 ) {
247                 
248                 notes.push_back ("audio MXF picture descriptors differ");
249                 return false;
250         }
251         
252         ASDCP::PCM::FrameBuffer buffer_A (1 * Kumu::Megabyte);
253         ASDCP::PCM::FrameBuffer buffer_B (1 * Kumu::Megabyte);
254         
255         for (int i = 0; i < _length; ++i) {
256                 if (ASDCP_FAILURE (reader_A.ReadFrame (i, buffer_A))) {
257                         throw DCPReadError ("could not read audio frame");
258                 }
259                 
260                 if (ASDCP_FAILURE (reader_B.ReadFrame (i, buffer_B))) {
261                         throw DCPReadError ("could not read audio frame");
262                 }
263                 
264                 if (buffer_A.Size() != buffer_B.Size()) {
265                         notes.push_back ("sizes of audio data for frame " + lexical_cast<string>(i) + " differ");
266                         return false;
267                 }
268                 
269                 if (memcmp (buffer_A.RoData(), buffer_B.RoData(), buffer_A.Size()) != 0) {
270                         for (uint32_t i = 0; i < buffer_A.Size(); ++i) {
271                                 int const d = abs (buffer_A.RoData()[i] - buffer_B.RoData()[i]);
272                                 if (d > opt.max_audio_sample_error) {
273                                         notes.push_back ("PCM data difference of " + lexical_cast<string> (d));
274                                         return false;
275                                 }
276                         }
277                 }
278         }
279
280         return true;
281 }
282
283 shared_ptr<const SoundFrame>
284 SoundAsset::get_frame (int n) const
285 {
286         return shared_ptr<const SoundFrame> (new SoundFrame (path().string(), n + _entry_point));
287 }
288
289 string
290 SoundAsset::key_type () const
291 {
292         return "MDAK";
293 }