Fix build on OS X.
[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 (boost::filesystem::path directory, boost::filesystem::path mxf_name)
46         : MXFAsset (directory, mxf_name)
47         , _channels (0)
48         , _sampling_rate (0)
49 {
50
51 }
52
53 void
54 SoundAsset::create (vector<boost::filesystem::path> const & files)
55 {
56         create (boost::bind (&SoundAsset::path_from_channel, this, _1, files));
57 }
58
59 void
60 SoundAsset::read ()
61 {
62         ASDCP::PCM::MXFReader reader;
63         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
64                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
65         }
66
67         ASDCP::PCM::AudioDescriptor desc;
68         if (ASDCP_FAILURE (reader.FillAudioDescriptor (desc))) {
69                 boost::throw_exception (DCPReadError ("could not read audio MXF information"));
70         }
71
72         _sampling_rate = desc.AudioSamplingRate.Numerator / desc.AudioSamplingRate.Denominator;
73         _channels = desc.ChannelCount;
74         _edit_rate = desc.EditRate.Numerator;
75         assert (desc.EditRate.Denominator == 1);
76         _intrinsic_duration = desc.ContainerDuration;
77 }
78
79 boost::filesystem::path
80 SoundAsset::path_from_channel (Channel channel, vector<boost::filesystem::path> const & files)
81 {
82         unsigned int const c = int (channel);
83         assert (c < files.size ());
84         return files[c];
85 }
86
87 void
88 SoundAsset::create (boost::function<boost::filesystem::path (Channel)> get_path)
89 {
90         ASDCP::Rational asdcp_edit_rate (_edit_rate, 1);
91
92         assert (_channels > 0);
93         ASDCP::PCM::WAVParser* pcm_parser_channel[_channels];
94         for (int i = 0; i < _channels; ++i) {
95                 pcm_parser_channel[i] = new ASDCP::PCM::WAVParser ();
96         }
97         if (pcm_parser_channel[0]->OpenRead (get_path(LEFT).string().c_str(), asdcp_edit_rate)) {
98                 boost::throw_exception (FileError ("could not open WAV file for reading", get_path(LEFT)));
99         }
100         
101         ASDCP::PCM::AudioDescriptor audio_desc;
102         pcm_parser_channel[0]->FillAudioDescriptor (audio_desc);
103         audio_desc.ChannelCount = 0;
104         audio_desc.BlockAlign = 0;
105         audio_desc.EditRate = asdcp_edit_rate;
106         audio_desc.AvgBps = audio_desc.AvgBps * _channels;
107
108         Channel channels[] = {
109                 LEFT,
110                 RIGHT,
111                 CENTRE,
112                 LFE,
113                 LS,
114                 RS,
115                 /* XXX: not quite sure what these should be yet */
116                 CHANNEL_7,
117                 CHANNEL_8
118         };
119
120         assert (int(_channels) <= int(sizeof(channels) / sizeof(Channel)));
121
122         ASDCP::PCM::FrameBuffer* frame_buffer_channel[_channels];
123         ASDCP::PCM::AudioDescriptor* audio_desc_channel[_channels];
124         for (int i = 0; i < _channels; ++i) {
125                 frame_buffer_channel[i] = new ASDCP::PCM::FrameBuffer ();
126                 audio_desc_channel[i] = new ASDCP::PCM::AudioDescriptor ();
127         }
128
129         for (int i = 0; i < _channels; ++i) {
130
131                 boost::filesystem::path const path = get_path (channels[i]);
132                 
133                 if (ASDCP_FAILURE (pcm_parser_channel[i]->OpenRead (path.string().c_str(), asdcp_edit_rate))) {
134                         boost::throw_exception (FileError ("could not open WAV file for reading", path));
135                 }
136
137                 pcm_parser_channel[i]->FillAudioDescriptor (*audio_desc_channel[i]);
138                 frame_buffer_channel[i]->Capacity (ASDCP::PCM::CalcFrameBufferSize (*audio_desc_channel[i]));
139
140                 audio_desc.ChannelCount += audio_desc_channel[i]->ChannelCount;
141                 audio_desc.BlockAlign += audio_desc_channel[i]->BlockAlign;
142         }
143
144         ASDCP::PCM::FrameBuffer frame_buffer;
145         frame_buffer.Capacity (ASDCP::PCM::CalcFrameBufferSize (audio_desc));
146         frame_buffer.Size (ASDCP::PCM::CalcFrameBufferSize (audio_desc));
147
148         ASDCP::WriterInfo writer_info;
149         MXFAsset::fill_writer_info (&writer_info, _uuid, _interop, _metadata);
150
151         ASDCP::PCM::MXFWriter mxf_writer;
152         if (ASDCP_FAILURE (mxf_writer.OpenWrite (path().string().c_str(), writer_info, audio_desc))) {
153                 boost::throw_exception (FileError ("could not open audio MXF for writing", path().string()));
154         }
155         
156         for (int i = 0; i < _intrinsic_duration; ++i) {
157
158                 for (int j = 0; j < _channels; ++j) {
159                         memset (frame_buffer_channel[j]->Data(), 0, frame_buffer_channel[j]->Capacity());
160                         if (ASDCP_FAILURE (pcm_parser_channel[j]->ReadFrame (*frame_buffer_channel[j]))) {
161                                 boost::throw_exception (MiscError ("could not read audio frame"));
162                         }
163                 }
164
165                 byte_t *data_s = frame_buffer.Data();
166                 byte_t *data_e = data_s + frame_buffer.Capacity();
167                 byte_t sample_size = ASDCP::PCM::CalcSampleSize (*audio_desc_channel[0]);
168                 int offset = 0;
169
170                 while (data_s < data_e) {
171                         for (int j = 0; j < _channels; ++j) {
172                                 byte_t* frame = frame_buffer_channel[j]->Data() + offset;
173                                 memcpy (data_s, frame, sample_size);
174                                 data_s += sample_size;
175                         }
176                         offset += sample_size;
177                 }
178
179                 if (ASDCP_FAILURE (mxf_writer.WriteFrame (frame_buffer, _encryption_context, 0))) {
180                         boost::throw_exception (MiscError ("could not write audio MXF frame"));
181                 }
182
183                 if (_progress) {
184                         (*_progress) (0.5 * float (i) / _intrinsic_duration);
185                 }
186         }
187
188         bool const failed = ASDCP_FAILURE (mxf_writer.Finalize());
189
190         for (int i = 0; i < _channels; ++i) {
191                 delete pcm_parser_channel[i];
192                 delete frame_buffer_channel[i];
193                 delete audio_desc_channel[i];
194         }
195
196         if (failed) {
197                 boost::throw_exception (MiscError ("could not finalise audio MXF"));
198         }
199 }
200
201 string
202 SoundAsset::cpl_node_name () const
203 {
204         return "MainSound";
205 }
206
207 bool
208 SoundAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
209 {
210         if (!MXFAsset::equals (other, opt, note)) {
211                 return false;
212         }
213                      
214         ASDCP::PCM::MXFReader reader_A;
215         if (ASDCP_FAILURE (reader_A.OpenRead (path().string().c_str()))) {
216                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
217         }
218
219         ASDCP::PCM::MXFReader reader_B;
220         if (ASDCP_FAILURE (reader_B.OpenRead (other->path().string().c_str()))) {
221                 boost::throw_exception (MXFFileError ("could not open MXF file for reading", path().string()));
222         }
223
224         ASDCP::PCM::AudioDescriptor desc_A;
225         if (ASDCP_FAILURE (reader_A.FillAudioDescriptor (desc_A))) {
226                 boost::throw_exception (DCPReadError ("could not read audio MXF information"));
227         }
228         ASDCP::PCM::AudioDescriptor desc_B;
229         if (ASDCP_FAILURE (reader_B.FillAudioDescriptor (desc_B))) {
230                 boost::throw_exception (DCPReadError ("could not read audio MXF information"));
231         }
232         
233         if (
234                 desc_A.EditRate != desc_B.EditRate ||
235                 desc_A.AudioSamplingRate != desc_B.AudioSamplingRate ||
236                 desc_A.Locked != desc_B.Locked ||
237                 desc_A.ChannelCount != desc_B.ChannelCount ||
238                 desc_A.QuantizationBits != desc_B.QuantizationBits ||
239                 desc_A.BlockAlign != desc_B.BlockAlign ||
240                 desc_A.AvgBps != desc_B.AvgBps ||
241                 desc_A.LinkedTrackID != desc_B.LinkedTrackID ||
242                 desc_A.ContainerDuration != desc_B.ContainerDuration
243 //              desc_A.ChannelFormat != desc_B.ChannelFormat ||
244                 ) {
245                 
246                 note (ERROR, "audio MXF picture descriptors differ");
247                 return false;
248         }
249         
250         ASDCP::PCM::FrameBuffer buffer_A (1 * Kumu::Megabyte);
251         ASDCP::PCM::FrameBuffer buffer_B (1 * Kumu::Megabyte);
252         
253         for (int i = 0; i < _intrinsic_duration; ++i) {
254                 if (ASDCP_FAILURE (reader_A.ReadFrame (i, buffer_A))) {
255                         boost::throw_exception (DCPReadError ("could not read audio frame"));
256                 }
257                 
258                 if (ASDCP_FAILURE (reader_B.ReadFrame (i, buffer_B))) {
259                         boost::throw_exception (DCPReadError ("could not read audio frame"));
260                 }
261                 
262                 if (buffer_A.Size() != buffer_B.Size()) {
263                         note (ERROR, "sizes of audio data for frame " + lexical_cast<string>(i) + " differ");
264                         return false;
265                 }
266                 
267                 if (memcmp (buffer_A.RoData(), buffer_B.RoData(), buffer_A.Size()) != 0) {
268                         for (uint32_t i = 0; i < buffer_A.Size(); ++i) {
269                                 int const d = abs (buffer_A.RoData()[i] - buffer_B.RoData()[i]);
270                                 if (d > opt.max_audio_sample_error) {
271                                         note (ERROR, "PCM data difference of " + lexical_cast<string> (d));
272                                         return false;
273                                 }
274                         }
275                 }
276         }
277
278         return true;
279 }
280
281 shared_ptr<const SoundFrame>
282 SoundAsset::get_frame (int n) const
283 {
284         /* XXX: should add on entry point here? */
285         return shared_ptr<const SoundFrame> (new SoundFrame (path().string(), n, _decryption_context));
286 }
287
288 shared_ptr<SoundAssetWriter>
289 SoundAsset::start_write ()
290 {
291         /* XXX: can't we use a shared_ptr here? */
292         return shared_ptr<SoundAssetWriter> (new SoundAssetWriter (this));
293 }
294
295 struct SoundAssetWriter::ASDCPState
296 {
297         ASDCP::PCM::MXFWriter mxf_writer;
298         ASDCP::PCM::FrameBuffer frame_buffer;
299         ASDCP::WriterInfo writer_info;
300         ASDCP::PCM::AudioDescriptor audio_desc;
301         ASDCP::AESEncContext* encryption_context;
302 };
303
304 SoundAssetWriter::SoundAssetWriter (SoundAsset* a)
305         : _state (new SoundAssetWriter::ASDCPState)
306         , _asset (a)
307         , _finalized (false)
308         , _frames_written (0)
309         , _frame_buffer_offset (0)
310 {
311         _state->encryption_context = a->encryption_context ();
312         
313         /* Derived from ASDCP::Wav::SimpleWaveHeader::FillADesc */
314         _state->audio_desc.EditRate = ASDCP::Rational (_asset->edit_rate(), 1);
315         _state->audio_desc.AudioSamplingRate = ASDCP::Rational (_asset->sampling_rate(), 1);
316         _state->audio_desc.Locked = 0;
317         _state->audio_desc.ChannelCount = _asset->channels ();
318         _state->audio_desc.QuantizationBits = 24;
319         _state->audio_desc.BlockAlign = 3 * _asset->channels();
320         _state->audio_desc.AvgBps = _asset->sampling_rate() * _state->audio_desc.BlockAlign;
321         _state->audio_desc.LinkedTrackID = 0;
322         _state->audio_desc.ChannelFormat = ASDCP::PCM::CF_NONE;
323         
324         _state->frame_buffer.Capacity (ASDCP::PCM::CalcFrameBufferSize (_state->audio_desc));
325         _state->frame_buffer.Size (ASDCP::PCM::CalcFrameBufferSize (_state->audio_desc));
326         memset (_state->frame_buffer.Data(), 0, _state->frame_buffer.Capacity());
327         
328         _asset->fill_writer_info (&_state->writer_info, _asset->uuid (), _asset->interop(), _asset->metadata());
329         
330         if (ASDCP_FAILURE (_state->mxf_writer.OpenWrite (_asset->path().string().c_str(), _state->writer_info, _state->audio_desc))) {
331                 boost::throw_exception (FileError ("could not open audio MXF for writing", _asset->path().string()));
332         }
333 }
334
335 void
336 SoundAssetWriter::write (float const * const * data, int frames)
337 {
338         for (int i = 0; i < frames; ++i) {
339
340                 byte_t* out = _state->frame_buffer.Data() + _frame_buffer_offset;
341
342                 /* Write one sample per channel */
343                 for (int j = 0; j < _asset->channels(); ++j) {
344                         int32_t const s = data[j][i] * (1 << 23);
345                         *out++ = (s & 0xff);
346                         *out++ = (s & 0xff00) >> 8;
347                         *out++ = (s & 0xff0000) >> 16;
348                 }
349                 _frame_buffer_offset += 3 * _asset->channels();
350
351                 assert (_frame_buffer_offset <= int (_state->frame_buffer.Capacity()));
352
353                 /* Finish the MXF frame if required */
354                 if (_frame_buffer_offset == int (_state->frame_buffer.Capacity())) {
355                         write_current_frame ();
356                         _frame_buffer_offset = 0;
357                         memset (_state->frame_buffer.Data(), 0, _state->frame_buffer.Capacity());
358                 }
359         }
360 }
361
362 void
363 SoundAssetWriter::write_current_frame ()
364 {
365         ASDCP::Result_t const r = _state->mxf_writer.WriteFrame (_state->frame_buffer, _state->encryption_context, 0);
366         if (ASDCP_FAILURE (r)) {
367                 boost::throw_exception (MiscError ("could not write audio MXF frame (" + lexical_cast<string> (int (r)) + ")"));
368         }
369
370         ++_frames_written;
371 }
372
373 void
374 SoundAssetWriter::finalize ()
375 {
376         if (_frame_buffer_offset > 0) {
377                 write_current_frame ();
378         }
379         
380         if (ASDCP_FAILURE (_state->mxf_writer.Finalize())) {
381                 boost::throw_exception (MiscError ("could not finalise audio MXF"));
382         }
383
384         _finalized = true;
385         _asset->set_intrinsic_duration (_frames_written);
386         _asset->set_duration (_frames_written);
387 }
388
389 string
390 SoundAsset::key_type () const
391 {
392         return "MDAK";
393 }