36bb41fa58102ed45a7655bda1e8a92d4b75c401
[ardour.git] / libs / appleutility / CoreAudio / AudioUnits / AUPublic / Utility / AUBuffer.cpp
1 /*
2      File: AUBuffer.cpp
3  Abstract: AUBuffer.h
4   Version: 1.1
5  
6  Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple
7  Inc. ("Apple") in consideration of your agreement to the following
8  terms, and your use, installation, modification or redistribution of
9  this Apple software constitutes acceptance of these terms.  If you do
10  not agree with these terms, please do not use, install, modify or
11  redistribute this Apple software.
12  
13  In consideration of your agreement to abide by the following terms, and
14  subject to these terms, Apple grants you a personal, non-exclusive
15  license, under Apple's copyrights in this original Apple software (the
16  "Apple Software"), to use, reproduce, modify and redistribute the Apple
17  Software, with or without modifications, in source and/or binary forms;
18  provided that if you redistribute the Apple Software in its entirety and
19  without modifications, you must retain this notice and the following
20  text and disclaimers in all such redistributions of the Apple Software.
21  Neither the name, trademarks, service marks or logos of Apple Inc. may
22  be used to endorse or promote products derived from the Apple Software
23  without specific prior written permission from Apple.  Except as
24  expressly stated in this notice, no other rights or licenses, express or
25  implied, are granted by Apple herein, including but not limited to any
26  patent rights that may be infringed by your derivative works or by other
27  works in which the Apple Software may be incorporated.
28  
29  The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
30  MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
31  THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
32  FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
33  OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
34  
35  IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
36  OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
37  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38  INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
39  MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
40  AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
41  STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
42  POSSIBILITY OF SUCH DAMAGE.
43  
44  Copyright (C) 2014 Apple Inc. All Rights Reserved.
45  
46 */
47 #include "AUBuffer.h"
48 #include <stdlib.h>
49
50 AUBufferList::~AUBufferList()
51 {
52         Deallocate();
53         if (mPtrs)
54                 free(mPtrs);
55 }
56
57 // a * b + c
58 static UInt32 SafeMultiplyAddUInt32(UInt32 a, UInt32 b, UInt32 c)
59 {
60         if (a == 0 || b == 0) return c;  // prevent zero divide
61         
62         if (a > (0xFFFFFFFF - c) / b)
63                 throw std::bad_alloc();
64         
65         return a * b + c;
66 }
67
68 void                            AUBufferList::Allocate(const CAStreamBasicDescription &format, UInt32 nFrames)
69 {
70         UInt32 nStreams;
71         if (format.IsInterleaved()) {
72                 nStreams = 1;
73         } else {
74                 nStreams = format.mChannelsPerFrame;
75         }
76
77         // careful -- the I/O thread could be running!
78         if (nStreams > mAllocatedStreams) {
79                 size_t theHeaderSize = sizeof(AudioBufferList) - sizeof(AudioBuffer);
80                 mPtrs = (AudioBufferList *)CA_realloc(mPtrs,
81                                                                         SafeMultiplyAddUInt32(nStreams, sizeof(AudioBuffer), theHeaderSize));
82                 mAllocatedStreams = nStreams;
83         }
84         UInt32 bytesPerStream = SafeMultiplyAddUInt32(nFrames, format.mBytesPerFrame, 0xF) & ~0xF;
85         UInt32 nBytes = SafeMultiplyAddUInt32(nStreams, bytesPerStream, 0);
86         if (nBytes > mAllocatedBytes) {
87                 if (mExternalMemory) {
88                         mExternalMemory = false;
89                         mMemory = NULL;
90                 }
91                 mMemory = (Byte *)CA_realloc(mMemory, nBytes);
92                 mAllocatedBytes = nBytes;
93         }
94         mAllocatedFrames = nFrames;
95         mPtrState = kPtrsInvalid;
96 }
97
98 void                            AUBufferList::Deallocate()
99 {
100         mAllocatedStreams = 0;
101         mAllocatedFrames = 0;
102         mAllocatedBytes = 0;
103 // this causes a world of hurt if someone upstream disconnects during I/O (SysSoundGraph)
104 /*      if (mPtrs) {
105                 printf("deallocating bufferlist %08X\n", int(mPtrs));
106                 free(mPtrs);
107                 mPtrs = NULL;
108         } */
109         if (mMemory) {
110                 if (mExternalMemory)
111                         mExternalMemory = false;
112                 else
113                         free(mMemory);
114                 mMemory = NULL;
115         }
116         mPtrState = kPtrsInvalid;
117 }
118
119 AudioBufferList &       AUBufferList::PrepareBuffer(const CAStreamBasicDescription &format, UInt32 nFrames)
120 {
121         if (nFrames > mAllocatedFrames)
122                 COMPONENT_THROW(kAudioUnitErr_TooManyFramesToProcess);
123
124         UInt32 nStreams;
125         UInt32 channelsPerStream;
126         if (format.IsInterleaved()) {
127                 nStreams = 1;
128                 channelsPerStream = format.mChannelsPerFrame;
129         } else {
130                 nStreams = format.mChannelsPerFrame;
131                 channelsPerStream = 1;
132                 if (nStreams > mAllocatedStreams)
133                         COMPONENT_THROW(kAudioUnitErr_FormatNotSupported);
134         }
135         
136         AudioBufferList *abl = mPtrs;
137         abl->mNumberBuffers = nStreams;
138         AudioBuffer *buf = abl->mBuffers;
139         Byte *mem = mMemory;
140         UInt32 streamInterval = (mAllocatedFrames * format.mBytesPerFrame + 0xF) & ~0xF;
141         UInt32 bytesPerBuffer = nFrames * format.mBytesPerFrame;
142         for ( ; nStreams--; ++buf) {
143                 buf->mNumberChannels = channelsPerStream;
144                 buf->mData = mem;
145                 buf->mDataByteSize = bytesPerBuffer;
146                 mem += streamInterval;
147         }
148         if (UInt32(mem - mMemory) > mAllocatedBytes)
149                 COMPONENT_THROW(kAudioUnitErr_TooManyFramesToProcess);
150         mPtrState = kPtrsToMyMemory;
151         return *mPtrs;
152 }
153
154 AudioBufferList &       AUBufferList::PrepareNullBuffer(const CAStreamBasicDescription &format, UInt32 nFrames)
155 {
156         UInt32 nStreams;
157         UInt32 channelsPerStream;
158         if (format.IsInterleaved()) {
159                 nStreams = 1;
160                 channelsPerStream = format.mChannelsPerFrame;
161         } else {
162                 nStreams = format.mChannelsPerFrame;
163                 channelsPerStream = 1;
164                 if (nStreams > mAllocatedStreams)
165                         COMPONENT_THROW(kAudioUnitErr_FormatNotSupported);
166         }
167         AudioBufferList *abl = mPtrs;
168         abl->mNumberBuffers = nStreams;
169         AudioBuffer *buf = abl->mBuffers;
170         UInt32 bytesPerBuffer = nFrames * format.mBytesPerFrame;
171         for ( ; nStreams--; ++buf) {
172                 buf->mNumberChannels = channelsPerStream;
173                 buf->mData = NULL;
174                 buf->mDataByteSize = bytesPerBuffer;
175         }
176         mPtrState = kPtrsToExternalMemory;
177         return *mPtrs;
178 }
179
180 // this should NOT be called while I/O is in process
181 void            AUBufferList::UseExternalBuffer(const CAStreamBasicDescription &format, const AudioUnitExternalBuffer &buf)
182 {
183         UInt32 alignedSize = buf.size & ~0xF;
184         if (mMemory != NULL && alignedSize >= mAllocatedBytes) {
185                 // don't accept the buffer if we already have one and it's big enough
186                 // if we don't already have one, we don't need one
187                 Byte *oldMemory = mMemory;
188                 mMemory = buf.buffer;
189                 mAllocatedBytes = alignedSize;
190                 // from Allocate(): nBytes = nStreams * nFrames * format.mBytesPerFrame;        
191                 // thus: nFrames = nBytes / (nStreams * format.mBytesPerFrame)
192                 mAllocatedFrames = mAllocatedBytes / (format.NumberChannelStreams() * format.mBytesPerFrame);
193                 mExternalMemory = true;
194                 free(oldMemory);
195         }
196 }
197
198 #if DEBUG
199 void    AUBufferList::PrintBuffer(const char *label, int subscript, const AudioBufferList &abl, UInt32 nFrames, bool asFloats)
200 {
201         printf("  %s [%d] 0x%08lX:\n", label, subscript, long(&abl));
202         const AudioBuffer *buf = abl.mBuffers;
203         for (UInt32 i = 0; i < abl.mNumberBuffers; ++buf, ++i) {
204                 printf("      [%2d] %5dbytes %dch @ %p: ", (int)i, (int)buf->mDataByteSize, (int)buf->mNumberChannels, buf->mData);
205                 if (buf->mData != NULL) {
206                         UInt32 nSamples = nFrames * buf->mNumberChannels;
207                         for (UInt32 j = 0; j < nSamples; ++j) {
208                                 if (nSamples > 16 && (j % 16) == 0)
209                                         printf("\n\t");
210                                 if (asFloats)
211                                         printf(" %6.3f", ((float *)buf->mData)[j]);
212                                 else
213                                         printf(" %08X", (unsigned)((UInt32 *)buf->mData)[j]);
214                         }
215                 }
216                 printf("\n");
217         }
218 }
219 #endif