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