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