9f27a894dcdc71b489a461c301609699643fc984
[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 namespace std;
36 using namespace boost;
37 using namespace libdcp;
38
39 SoundAsset::SoundAsset (
40         vector<string> const & files, string directory, string mxf_name, sigc::signal1<void, float>* progress, int fps, int length
41         )
42         : MXFAsset (directory, mxf_name, progress, fps, 0, length)
43         , _channels (files.size ())
44         , _sampling_rate (0)
45 {
46         construct (sigc::bind (sigc::mem_fun (*this, &SoundAsset::path_from_channel), files));
47 }
48
49 SoundAsset::SoundAsset (
50         sigc::slot<string, Channel> get_path, string directory, string mxf_name, sigc::signal1<void, float>* progress, int fps, int length, int channels
51         )
52         : MXFAsset (directory, mxf_name, progress, fps, 0, length)
53         , _channels (channels)
54         , _sampling_rate (0)
55 {
56         construct (get_path);
57 }
58
59 SoundAsset::SoundAsset (string directory, string mxf_name, int fps, int entry_point, int length)
60         : MXFAsset (directory, mxf_name, 0, fps, entry_point, length)
61         , _channels (0)
62 {
63         ASDCP::PCM::MXFReader reader;
64         if (ASDCP_FAILURE (reader.OpenRead (path().string().c_str()))) {
65                 throw MXFFileError ("could not open MXF file for reading", path().string());
66         }
67
68         
69         ASDCP::PCM::AudioDescriptor desc;
70         if (ASDCP_FAILURE (reader.FillAudioDescriptor (desc))) {
71                 throw DCPReadError ("could not read audio MXF information");
72         }
73
74         _sampling_rate = desc.AudioSamplingRate.Numerator / desc.AudioSamplingRate.Denominator;
75         _channels = desc.ChannelCount;
76 }
77
78 string
79 SoundAsset::path_from_channel (Channel channel, vector<string> const & files)
80 {
81         unsigned int const c = int (channel);
82         assert (c < files.size ());
83         return files[c];
84 }
85
86 void
87 SoundAsset::construct (sigc::slot<string, Channel> get_path)
88 {
89         ASDCP::Rational asdcp_fps (_fps, 1);
90         
91         ASDCP::PCM::WAVParser pcm_parser_channel[_channels];
92         if (pcm_parser_channel[0].OpenRead (get_path(LEFT).c_str(), asdcp_fps)) {
93                 throw FileError ("could not open WAV file for reading", get_path(LEFT));
94         }
95         
96         ASDCP::PCM::AudioDescriptor audio_desc;
97         pcm_parser_channel[0].FillAudioDescriptor (audio_desc);
98         audio_desc.ChannelCount = 0;
99         audio_desc.BlockAlign = 0;
100         audio_desc.EditRate = asdcp_fps;
101         audio_desc.AvgBps = audio_desc.AvgBps * _channels;
102
103         Channel channels[] = {
104                 LEFT,
105                 RIGHT,
106                 CENTRE,
107                 LFE,
108                 LS,
109                 RS
110         };
111
112         ASDCP::PCM::FrameBuffer frame_buffer_channel[_channels];
113         ASDCP::PCM::AudioDescriptor audio_desc_channel[_channels];
114
115         for (int i = 0; i < _channels; ++i) {
116
117                 string const path = get_path (channels[i]);
118                 
119                 if (ASDCP_FAILURE (pcm_parser_channel[i].OpenRead (path.c_str(), asdcp_fps))) {
120                         throw FileError ("could not open WAV file for reading", path);
121                 }
122
123                 pcm_parser_channel[i].FillAudioDescriptor (audio_desc_channel[i]);
124                 frame_buffer_channel[i].Capacity (ASDCP::PCM::CalcFrameBufferSize (audio_desc_channel[i]));
125
126                 audio_desc.ChannelCount += audio_desc_channel[i].ChannelCount;
127                 audio_desc.BlockAlign += audio_desc_channel[i].BlockAlign;
128         }
129
130         ASDCP::PCM::FrameBuffer frame_buffer;
131         frame_buffer.Capacity (ASDCP::PCM::CalcFrameBufferSize (audio_desc));
132         frame_buffer.Size (ASDCP::PCM::CalcFrameBufferSize (audio_desc));
133
134         ASDCP::WriterInfo writer_info;
135         fill_writer_info (&writer_info);
136
137         ASDCP::PCM::MXFWriter mxf_writer;
138         if (ASDCP_FAILURE (mxf_writer.OpenWrite (path().string().c_str(), writer_info, audio_desc))) {
139                 throw FileError ("could not open audio MXF for writing", path().string());
140         }
141
142         for (int i = 0; i < _length; ++i) {
143
144                 byte_t *data_s = frame_buffer.Data();
145                 byte_t *data_e = data_s + frame_buffer.Capacity();
146                 byte_t sample_size = ASDCP::PCM::CalcSampleSize (audio_desc_channel[0]);
147                 int offset = 0;
148
149                 for (int j = 0; j < _channels; ++j) {
150                         memset (frame_buffer_channel[j].Data(), 0, frame_buffer_channel[j].Capacity());
151                         if (ASDCP_FAILURE (pcm_parser_channel[j].ReadFrame (frame_buffer_channel[j]))) {
152                                 throw MiscError ("could not read audio frame");
153                         }
154                         
155                         if (frame_buffer_channel[j].Size() != frame_buffer_channel[j].Capacity()) {
156                                 throw MiscError ("short audio frame");
157                         }
158                 }
159
160                 while (data_s < data_e) {
161                         for (int j = 0; j < _channels; ++j) {
162                                 byte_t* frame = frame_buffer_channel[j].Data() + offset;
163                                 memcpy (data_s, frame, sample_size);
164                                 data_s += sample_size;
165                         }
166                         offset += sample_size;
167                 }
168
169                 if (ASDCP_FAILURE (mxf_writer.WriteFrame (frame_buffer, 0, 0))) {
170                         throw MiscError ("could not write audio MXF frame");
171                 }
172
173                 if (_progress) {
174                         (*_progress) (0.5 * float (i) / _length);
175                 }
176         }
177
178         if (ASDCP_FAILURE (mxf_writer.Finalize())) {
179                 throw MiscError ("could not finalise audio MXF");
180         }
181 }
182
183 void
184 SoundAsset::write_to_cpl (ostream& s) const
185 {
186         s << "        <MainSound>\n"
187           << "          <Id>urn:uuid:" << _uuid << "</Id>\n"
188           << "          <AnnotationText>" << _file_name << "</AnnotationText>\n"
189           << "          <EditRate>" << _fps << " 1</EditRate>\n"
190           << "          <IntrinsicDuration>" << _length << "</IntrinsicDuration>\n"
191           << "          <EntryPoint>0</EntryPoint>\n"
192           << "          <Duration>" << _length << "</Duration>\n"
193           << "        </MainSound>\n";
194 }
195
196 bool
197 SoundAsset::equals (shared_ptr<const Asset> other, EqualityOptions opt, list<string>& notes) const
198 {
199         if (!MXFAsset::equals (other, opt, notes)) {
200                 return false;
201         }
202                      
203         ASDCP::PCM::MXFReader reader_A;
204         if (ASDCP_FAILURE (reader_A.OpenRead (path().string().c_str()))) {
205                 throw MXFFileError ("could not open MXF file for reading", path().string());
206         }
207
208         ASDCP::PCM::MXFReader reader_B;
209         if (ASDCP_FAILURE (reader_B.OpenRead (other->path().string().c_str()))) {
210                 throw MXFFileError ("could not open MXF file for reading", path().string());
211         }
212
213         ASDCP::PCM::AudioDescriptor desc_A;
214         if (ASDCP_FAILURE (reader_A.FillAudioDescriptor (desc_A))) {
215                 throw DCPReadError ("could not read audio MXF information");
216         }
217         ASDCP::PCM::AudioDescriptor desc_B;
218         if (ASDCP_FAILURE (reader_B.FillAudioDescriptor (desc_B))) {
219                 throw DCPReadError ("could not read audio MXF information");
220         }
221         
222         if (
223                 desc_A.EditRate != desc_B.EditRate ||
224                 desc_A.AudioSamplingRate != desc_B.AudioSamplingRate ||
225                 desc_A.Locked != desc_B.Locked ||
226                 desc_A.ChannelCount != desc_B.ChannelCount ||
227                 desc_A.QuantizationBits != desc_B.QuantizationBits ||
228                 desc_A.BlockAlign != desc_B.BlockAlign ||
229                 desc_A.AvgBps != desc_B.AvgBps ||
230                 desc_A.LinkedTrackID != desc_B.LinkedTrackID ||
231                 desc_A.ContainerDuration != desc_B.ContainerDuration
232 //              desc_A.ChannelFormat != desc_B.ChannelFormat ||
233                 ) {
234                 
235                 notes.push_back ("audio MXF picture descriptors differ");
236                 return false;
237         }
238         
239         ASDCP::PCM::FrameBuffer buffer_A (1 * Kumu::Megabyte);
240         ASDCP::PCM::FrameBuffer buffer_B (1 * Kumu::Megabyte);
241         
242         for (int i = 0; i < _length; ++i) {
243                 if (ASDCP_FAILURE (reader_A.ReadFrame (i, buffer_A))) {
244                         throw DCPReadError ("could not read audio frame");
245                 }
246                 
247                 if (ASDCP_FAILURE (reader_B.ReadFrame (i, buffer_B))) {
248                         throw DCPReadError ("could not read audio frame");
249                 }
250                 
251                 if (buffer_A.Size() != buffer_B.Size()) {
252                         notes.push_back ("sizes of audio data for frame " + lexical_cast<string>(i) + " differ");
253                         return false;
254                 }
255                 
256                 if (memcmp (buffer_A.RoData(), buffer_B.RoData(), buffer_A.Size()) != 0) {
257                         notes.push_back ("PCM data for MXF frame " + lexical_cast<string>(i) + " differ");
258
259                         for (uint32_t i = 0; i < buffer_A.Size(); ++i) {
260                                 int const d = abs (buffer_A.RoData()[i] - buffer_B.RoData()[i]);
261                                 if (d) {
262                                         notes.push_back ("First difference is " + lexical_cast<string> (d));
263                                         return false;
264                                 }
265                         }
266                         return false;
267                 }
268         }
269
270         return true;
271 }
272
273 shared_ptr<const SoundFrame>
274 SoundAsset::get_frame (int n) const
275 {
276         return shared_ptr<const SoundFrame> (new SoundFrame (path().string(), n + _entry_point));
277 }