Initial hacks.
[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, string directory, string mxf_name, boost::signals2::signal<void (float)>* progress, int fps, int length, bool encrypted
46         )
47         : MXFAsset (directory, mxf_name, progress, fps, 0, length, encrypted)
48         , _channels (files.size ())
49         , _sampling_rate (0)
50 {
51         construct (boost::bind (&SoundAsset::path_from_channel, this, _1, files));
52 }
53
54 SoundAsset::SoundAsset (
55         boost::function<string (Channel)> get_path,
56         string directory,
57         string mxf_name,
58         boost::signals2::signal<void (float)>* progress,
59         int fps, int length, int channels, bool encrypted
60         )
61         : MXFAsset (directory, mxf_name, progress, fps, 0, length, encrypted)
62         , _channels (channels)
63         , _sampling_rate (0)
64 {
65         construct (get_path);
66 }
67
68 SoundAsset::SoundAsset (string directory, string mxf_name, int fps, int entry_point, int length)
69         : MXFAsset (directory, mxf_name, 0, fps, entry_point, length, false)
70         , _channels (0)
71 {
72         ASDCP::PCM::MXFReader reader;
73         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
74                 throw MXFFileError ("could not open MXF file for reading", path().string());
75         }
76
77         
78         ASDCP::PCM::AudioDescriptor desc;
79         if (ASDCP_FAILURE (reader.FillAudioDescriptor (desc))) {
80                 throw DCPReadError ("could not read audio MXF information");
81         }
82
83         _sampling_rate = desc.AudioSamplingRate.Numerator / desc.AudioSamplingRate.Denominator;
84         _channels = desc.ChannelCount;
85 }
86
87 string
88 SoundAsset::path_from_channel (Channel channel, vector<string> const & files)
89 {
90         unsigned int const c = int (channel);
91         assert (c < files.size ());
92         return files[c];
93 }
94
95 void
96 SoundAsset::construct (boost::function<string (Channel)> get_path)
97 {
98         ASDCP::Rational asdcp_fps (_fps, 1);
99         
100         ASDCP::PCM::WAVParser pcm_parser_channel[_channels];
101         if (pcm_parser_channel[0].OpenRead (get_path(LEFT).c_str(), asdcp_fps)) {
102                 throw FileError ("could not open WAV file for reading", get_path(LEFT));
103         }
104         
105         ASDCP::PCM::AudioDescriptor audio_desc;
106         pcm_parser_channel[0].FillAudioDescriptor (audio_desc);
107         audio_desc.ChannelCount = 0;
108         audio_desc.BlockAlign = 0;
109         audio_desc.EditRate = asdcp_fps;
110         audio_desc.AvgBps = audio_desc.AvgBps * _channels;
111
112         Channel channels[] = {
113                 LEFT,
114                 RIGHT,
115                 CENTRE,
116                 LFE,
117                 LS,
118                 RS,
119                 /* XXX: not quite sure what these should be yet */
120                 CHANNEL_7,
121                 CHANNEL_8
122         };
123
124         assert (int(_channels) <= int(sizeof(channels) / sizeof(Channel)));
125
126         ASDCP::PCM::FrameBuffer frame_buffer_channel[_channels];
127         ASDCP::PCM::AudioDescriptor audio_desc_channel[_channels];
128
129         for (int i = 0; i < _channels; ++i) {
130
131                 string const path = get_path (channels[i]);
132                 
133                 if (ASDCP_FAILURE (pcm_parser_channel[i].OpenRead (path.c_str(), asdcp_fps))) {
134                         throw 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         fill_writer_info (&writer_info);
150
151         ASDCP::PCM::MXFWriter mxf_writer;
152         if (ASDCP_FAILURE (mxf_writer.OpenWrite (path().string().c_str(), writer_info, audio_desc))) {
153                 throw FileError ("could not open audio MXF for writing", path().string());
154         }
155
156         for (int i = 0; i < _length; ++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                                 throw 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                         throw MiscError ("could not write audio MXF frame");
181                 }
182
183                 if (_progress) {
184                         (*_progress) (0.5 * float (i) / _length);
185                 }
186         }
187
188         if (ASDCP_FAILURE (mxf_writer.Finalize())) {
189                 throw MiscError ("could not finalise audio MXF");
190         }
191 }
192
193 void
194 SoundAsset::write_to_cpl (ostream& s) const
195 {
196         s << "        <MainSound>\n"
197           << "          <Id>urn:uuid:" << _uuid << "</Id>\n"
198           << "          <AnnotationText>" << _file_name << "</AnnotationText>\n"
199           << "          <EditRate>" << _fps << " 1</EditRate>\n"
200           << "          <IntrinsicDuration>" << _length << "</IntrinsicDuration>\n"
201           << "          <EntryPoint>0</EntryPoint>\n"
202           << "          <Duration>" << _length << "</Duration>\n"
203           << "        </MainSound>\n";
204 }
205
206 bool
207 SoundAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, list<string>& notes) const
208 {
209         if (!MXFAsset::equals (other, opt, notes)) {
210                 return false;
211         }
212                      
213         ASDCP::PCM::MXFReader reader_A;
214         if (ASDCP_FAILURE (reader_A.OpenRead (path().string().c_str()))) {
215                 throw MXFFileError ("could not open MXF file for reading", path().string());
216         }
217
218         ASDCP::PCM::MXFReader reader_B;
219         if (ASDCP_FAILURE (reader_B.OpenRead (other->path().string().c_str()))) {
220                 throw MXFFileError ("could not open MXF file for reading", path().string());
221         }
222
223         ASDCP::PCM::AudioDescriptor desc_A;
224         if (ASDCP_FAILURE (reader_A.FillAudioDescriptor (desc_A))) {
225                 throw DCPReadError ("could not read audio MXF information");
226         }
227         ASDCP::PCM::AudioDescriptor desc_B;
228         if (ASDCP_FAILURE (reader_B.FillAudioDescriptor (desc_B))) {
229                 throw DCPReadError ("could not read audio MXF information");
230         }
231         
232         if (
233                 desc_A.EditRate != desc_B.EditRate ||
234                 desc_A.AudioSamplingRate != desc_B.AudioSamplingRate ||
235                 desc_A.Locked != desc_B.Locked ||
236                 desc_A.ChannelCount != desc_B.ChannelCount ||
237                 desc_A.QuantizationBits != desc_B.QuantizationBits ||
238                 desc_A.BlockAlign != desc_B.BlockAlign ||
239                 desc_A.AvgBps != desc_B.AvgBps ||
240                 desc_A.LinkedTrackID != desc_B.LinkedTrackID ||
241                 desc_A.ContainerDuration != desc_B.ContainerDuration
242 //              desc_A.ChannelFormat != desc_B.ChannelFormat ||
243                 ) {
244                 
245                 notes.push_back ("audio MXF picture descriptors differ");
246                 return false;
247         }
248         
249         ASDCP::PCM::FrameBuffer buffer_A (1 * Kumu::Megabyte);
250         ASDCP::PCM::FrameBuffer buffer_B (1 * Kumu::Megabyte);
251         
252         for (int i = 0; i < _length; ++i) {
253                 if (ASDCP_FAILURE (reader_A.ReadFrame (i, buffer_A))) {
254                         throw DCPReadError ("could not read audio frame");
255                 }
256                 
257                 if (ASDCP_FAILURE (reader_B.ReadFrame (i, buffer_B))) {
258                         throw DCPReadError ("could not read audio frame");
259                 }
260                 
261                 if (buffer_A.Size() != buffer_B.Size()) {
262                         notes.push_back ("sizes of audio data for frame " + lexical_cast<string>(i) + " differ");
263                         return false;
264                 }
265                 
266                 if (memcmp (buffer_A.RoData(), buffer_B.RoData(), buffer_A.Size()) != 0) {
267                         for (uint32_t i = 0; i < buffer_A.Size(); ++i) {
268                                 int const d = abs (buffer_A.RoData()[i] - buffer_B.RoData()[i]);
269                                 if (d > opt.max_audio_sample_error) {
270                                         notes.push_back ("PCM data difference of " + lexical_cast<string> (d));
271                                         return false;
272                                 }
273                         }
274                 }
275         }
276
277         return true;
278 }
279
280 shared_ptr<const SoundFrame>
281 SoundAsset::get_frame (int n) const
282 {
283         return shared_ptr<const SoundFrame> (new SoundFrame (path().string(), n + _entry_point));
284 }