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