summaryrefslogtreecommitdiff
path: root/package/libaudiofile/patches/patch-sfcommands_sfconvert_c
blob: cdf0e8dc306b320ef64a83e06d70b455afb874ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
--- audiofile-0.3.6.orig/sfcommands/sfconvert.c	2013-03-06 06:30:03.000000000 +0100
+++ audiofile-0.3.6/sfcommands/sfconvert.c	2017-04-26 02:15:11.864252147 +0200
@@ -45,6 +45,33 @@ void printusage (void);
 void usageerror (void);
 bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid);
 
+int firstBitSet(int x)
+{
+        int position=0;
+        while (x!=0)
+        {
+                x>>=1;
+                ++position;
+        }
+        return position;
+}
+
+#ifndef __has_builtin
+#define __has_builtin(x) 0
+#endif
+
+int multiplyCheckOverflow(int a, int b, int *result)
+{
+#if (defined __GNUC__ && __GNUC__ >= 5) || ( __clang__ && __has_builtin(__builtin_mul_overflow))
+	return __builtin_mul_overflow(a, b, result);
+#else
+	if (firstBitSet(a)+firstBitSet(b)>31) // int is signed, so we can't use 32 bits
+		return true;
+	*result = a * b;
+	return false;
+#endif
+}
+
 int main (int argc, char **argv)
 {
 	if (argc == 2)
@@ -323,8 +350,11 @@ bool copyaudiodata (AFfilehandle infile,
 {
 	int frameSize = afGetVirtualFrameSize(infile, trackid, 1);
 
-	const int kBufferFrameCount = 65536;
-	void *buffer = malloc(kBufferFrameCount * frameSize);
+	int kBufferFrameCount = 65536;
+	int bufferSize;
+	while (multiplyCheckOverflow(kBufferFrameCount, frameSize, &bufferSize))
+		kBufferFrameCount /= 2;
+	void *buffer = malloc(bufferSize);
 
 	AFframecount totalFrames = afGetFrameCount(infile, AF_DEFAULT_TRACK);
 	AFframecount totalFramesWritten = 0;