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