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