merge 5764970709f15e85ec30c9cea89c318eb8114c58 from cairocanvas as final(?) change...
[ardour.git] / libs / ardour / coreaudiosource.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3     Written by Taybin Rutkin
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <algorithm>
22 #include <inttypes.h>
23
24 #include "pbd/error.h"
25 #include "ardour/coreaudiosource.h"
26 #include "ardour/utils.h"
27
28 #include <appleutility/CAAudioFile.h>
29 #include <appleutility/CAStreamBasicDescription.h>
30
31 #include <glibmm/fileutils.h>
32
33 #include "i18n.h"
34
35 #include <AudioToolbox/AudioFormat.h>
36
37 using namespace std;
38 using namespace ARDOUR;
39 using namespace PBD;
40
41 /** Create a new CoreAudioSource using session state, which implies that the
42  *  file must already exist.
43  */
44 CoreAudioSource::CoreAudioSource (Session& s, const XMLNode& node)
45         : Source (s, node)
46         , AudioFileSource (s, node)
47 {
48         init_cafile ();
49
50         assert (Glib::file_test (_path, Glib::FILE_TEST_EXISTS));
51         existence_check ();
52 }
53
54 /** Create a new CoreAudioSource from an existing file. Sources created with this
55  *  method are never writable or removable.
56  */
57 CoreAudioSource::CoreAudioSource (Session& s, const string& path, int chn, Flag flags)
58         : Source (s, DataType::AUDIO, path, Source::Flag (flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy))),
59                 AudioFileSource (s, path,
60                         Source::Flag (flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy)))
61 {
62         _channel = chn;
63         init_cafile ();
64
65         assert (Glib::file_test (_path, Glib::FILE_TEST_EXISTS));
66         existence_check ();
67 }
68
69 void
70 CoreAudioSource::init_cafile ()
71 {
72         /* note that we temporarily truncated _id at the colon */
73         try {
74                 af.Open(_path.c_str());
75
76                 CAStreamBasicDescription file_format (af.GetFileDataFormat());
77                 n_channels = file_format.NumberChannels();
78
79                 if (_channel >= n_channels) {
80                         error << string_compose("CoreAudioSource: file only contains %1 channels; %2 is invalid as a channel number (%3)", n_channels, _channel, name()) << endmsg;
81                         throw failed_constructor();
82                 }
83
84                 _length = af.GetNumberFrames();
85
86                 CAStreamBasicDescription client_format (file_format);
87
88                 /* set canonial form (PCM, native float packed, 32 bit, with the correct number of channels
89                    and interleaved (since we plan to deinterleave ourselves)
90                 */
91
92                 client_format.SetCanonical(client_format.NumberChannels(), true);
93                 af.SetClientFormat (client_format);
94
95         } catch (CAXException& cax) {
96
97                 error << string_compose(_("CoreAudioSource: cannot open file \"%1\" for %2"),
98                                         _path, (writable() ? "read+write" : "reading")) << endmsg;
99                 throw failed_constructor ();
100         }
101 }
102
103 CoreAudioSource::~CoreAudioSource ()
104 {
105 }
106
107 int
108 CoreAudioSource::safe_read (Sample* dst, framepos_t start, framecnt_t cnt, AudioBufferList& abl) const
109 {
110         framecnt_t nread = 0;
111
112         while (nread < cnt) {
113
114                 try {
115                         af.Seek (start+nread);
116                 } catch (CAXException& cax) {
117                         error << string_compose("CoreAudioSource: %1 to %2 (%3)", cax.mOperation, start+nread, _name.val().substr (1)) << endmsg;
118                         return -1;
119                 }
120
121                 UInt32 new_cnt = cnt - nread;
122
123                 abl.mBuffers[0].mDataByteSize = new_cnt * n_channels * sizeof(Sample);
124                 abl.mBuffers[0].mData = dst + nread;
125
126                 try {
127                         af.Read (new_cnt, &abl);
128                 } catch (CAXException& cax) {
129                         error << string_compose("CoreAudioSource: %1 (%2)", cax.mOperation, _name);
130                         return -1;
131                 }
132
133                 if (new_cnt == 0) {
134                         /* EOF */
135                         if (start+cnt == _length) {
136                                 /* we really did hit the end */
137                                 nread = cnt;
138                         }
139                         break;
140                 }
141
142                 nread += new_cnt;
143         }
144
145         if (nread < cnt) {
146                 return -1;
147         } else {
148                 return 0;
149         }
150 }
151
152
153 framecnt_t
154 CoreAudioSource::read_unlocked (Sample *dst, framepos_t start, framecnt_t cnt) const
155 {
156         framecnt_t file_cnt;
157         AudioBufferList abl;
158
159         abl.mNumberBuffers = 1;
160         abl.mBuffers[0].mNumberChannels = n_channels;
161
162         if (start > _length) {
163
164                 /* read starts beyond end of data, just memset to zero */
165
166                 file_cnt = 0;
167
168         } else if (start + cnt > _length) {
169
170                 /* read ends beyond end of data, read some, memset the rest */
171
172                 file_cnt = _length - start;
173
174         } else {
175
176                 /* read is entirely within data */
177
178                 file_cnt = cnt;
179         }
180
181         if (file_cnt != cnt) {
182                 frameoffset_t delta = cnt - file_cnt;
183                 memset (dst+file_cnt, 0, sizeof (Sample) * delta);
184         }
185
186         if (file_cnt) {
187
188                 if (n_channels == 1) {
189                         if (safe_read (dst, start, file_cnt, abl) == 0) {
190                                 return cnt;
191                         }
192                         return 0;
193                 }
194         }
195
196         Sample* interleave_buf = get_interleave_buffer (file_cnt * n_channels);
197
198         if (safe_read (interleave_buf, start, file_cnt, abl) != 0) {
199                 return 0;
200         }
201
202         Sample *ptr = interleave_buf + _channel;
203
204         /* stride through the interleaved data */
205
206         for (framecnt_t n = 0; n < file_cnt; ++n) {
207                 dst[n] = *ptr;
208                 ptr += n_channels;
209         }
210
211         return cnt;
212 }
213
214 float
215 CoreAudioSource::sample_rate() const
216 {
217         CAStreamBasicDescription client_asbd;
218
219         try {
220                 client_asbd = af.GetClientDataFormat ();
221         } catch (CAXException& cax) {
222                 error << string_compose("CoreAudioSource: %1 (%2)", cax.mOperation, _name);
223                 return 0.0;
224         }
225
226         return client_asbd.mSampleRate;
227 }
228
229 int
230 CoreAudioSource::update_header (framepos_t, struct tm&, time_t)
231 {
232         return 0;
233 }
234
235 int
236 CoreAudioSource::get_soundfile_info (string path, SoundFileInfo& _info, string&)
237 {
238         FSRef ref;
239         ExtAudioFileRef af = 0;
240         UInt32 size;
241         CFStringRef name;
242         int ret = -1;
243
244         if (FSPathMakeRef ((UInt8*)path.c_str(), &ref, 0) != noErr) {
245                 goto out;
246         }
247
248         if (ExtAudioFileOpen(&ref, &af) != noErr) {
249                 goto out;
250         }
251
252         AudioStreamBasicDescription absd;
253         memset(&absd, 0, sizeof(absd));
254         size = sizeof(AudioStreamBasicDescription);
255         if (ExtAudioFileGetProperty (af, kExtAudioFileProperty_FileDataFormat, &size, &absd) != noErr) {
256                 goto out;
257         }
258
259         _info.samplerate = absd.mSampleRate;
260         _info.channels   = absd.mChannelsPerFrame;
261
262         size = sizeof(_info.length);
263         if (ExtAudioFileGetProperty(af, kExtAudioFileProperty_FileLengthFrames, &size, &_info.length) != noErr) {
264                 goto out;
265         }
266
267         size = sizeof(CFStringRef);
268         if (AudioFormatGetProperty(kAudioFormatProperty_FormatName, sizeof(absd), &absd, &size, &name) != noErr) {
269                 goto out;
270         }
271
272         _info.format_name = "";
273
274         if (absd.mFormatID == kAudioFormatLinearPCM) {
275                 if (absd.mFormatFlags & kAudioFormatFlagIsBigEndian) {
276                         _info.format_name += "big-endian";
277                 } else {
278                         _info.format_name += "little-endian";
279                 }
280
281                 char buf[32];
282                 snprintf (buf, sizeof (buf), " %" PRIu32 " bit", absd.mBitsPerChannel);
283                 _info.format_name += buf;
284                 _info.format_name += '\n';
285
286                 if (absd.mFormatFlags & kAudioFormatFlagIsFloat) {
287                         _info.format_name += "float";
288                 } else {
289                         if (absd.mFormatFlags & kAudioFormatFlagIsSignedInteger) {
290                                 _info.format_name += "signed";
291                         } else {
292                                 _info.format_name += "unsigned";
293                         }
294                         /* integer is typical, do not show it */
295                 }
296
297                 if (_info.channels > 1) {
298                         if (absd.mFormatFlags & kAudioFormatFlagIsNonInterleaved) {
299                                 _info.format_name += " noninterleaved";
300                         }
301                         /* interleaved is the normal case, do not show it */
302                 }
303
304                 _info.format_name += ' ';
305         }
306
307         switch (absd.mFormatID) {
308         case kAudioFormatLinearPCM:
309                 _info.format_name += "PCM";
310                 break;
311
312         case kAudioFormatAC3:
313                 _info.format_name += "AC3";
314                 break;
315
316         case kAudioFormat60958AC3:
317                 _info.format_name += "60958 AC3";
318                 break;
319
320         case kAudioFormatMPEGLayer1:
321                 _info.format_name += "MPEG-1";
322                 break;
323
324         case kAudioFormatMPEGLayer2:
325                 _info.format_name += "MPEG-2";
326                 break;
327
328         case kAudioFormatMPEGLayer3:
329                 _info.format_name += "MPEG-3";
330                 break;
331
332         case kAudioFormatAppleIMA4:
333                 _info.format_name += "IMA-4";
334                 break;
335
336         case kAudioFormatMPEG4AAC:
337                 _info.format_name += "AAC";
338                 break;
339
340         case kAudioFormatMPEG4CELP:
341                 _info.format_name += "CELP";
342                 break;
343
344         case kAudioFormatMPEG4HVXC:
345                 _info.format_name += "HVXC";
346                 break;
347
348         case kAudioFormatMPEG4TwinVQ:
349                 _info.format_name += "TwinVQ";
350                 break;
351
352         /* these really shouldn't show up, but we should do something
353            somewhere else to make sure that doesn't happen. until
354            that is guaranteed, print something anyway.
355         */
356
357         case kAudioFormatTimeCode:
358                 _info.format_name += "timecode";
359                 break;
360
361         case kAudioFormatMIDIStream:
362                 _info.format_name += "MIDI";
363                 break;
364
365         case kAudioFormatParameterValueStream:
366                 _info.format_name += "parameter values";
367                 break;
368         }
369
370         // XXX it would be nice to find a way to get this information if it exists
371
372         _info.timecode = 0;
373         ret = 0;
374
375   out:
376         ExtAudioFileDispose (af);
377         return ret;
378
379 }
380
381 void
382 CoreAudioSource::set_path (const string& p)
383 {
384         FileSource::set_path (p);
385 }