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