├── LICENSE
├── README.md
├── ffttest.xcodeproj
├── project.pbxproj
├── project.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcuserdata
│ │ └── christopher.xcuserdatad
│ │ └── UserInterfaceState.xcuserstate
└── xcuserdata
│ └── christopher.xcuserdatad
│ ├── xcdebugger
│ └── Breakpoints_v2.xcbkptlist
│ └── xcschemes
│ ├── ffttest.xcscheme
│ └── xcschememanagement.plist
└── ffttest
├── fft.swift
└── main.swift
/LICENSE:
--------------------------------------------------------------------------------
1 | CC0 1.0 Universal
2 |
3 | Statement of Purpose
4 |
5 | The laws of most jurisdictions throughout the world automatically confer
6 | exclusive Copyright and Related Rights (defined below) upon the creator and
7 | subsequent owner(s) (each and all, an "owner") of an original work of
8 | authorship and/or a database (each, a "Work").
9 |
10 | Certain owners wish to permanently relinquish those rights to a Work for the
11 | purpose of contributing to a commons of creative, cultural and scientific
12 | works ("Commons") that the public can reliably and without fear of later
13 | claims of infringement build upon, modify, incorporate in other works, reuse
14 | and redistribute as freely as possible in any form whatsoever and for any
15 | purposes, including without limitation commercial purposes. These owners may
16 | contribute to the Commons to promote the ideal of a free culture and the
17 | further production of creative, cultural and scientific works, or to gain
18 | reputation or greater distribution for their Work in part through the use and
19 | efforts of others.
20 |
21 | For these and/or other purposes and motivations, and without any expectation
22 | of additional consideration or compensation, the person associating CC0 with a
23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
25 | and publicly distribute the Work under its terms, with knowledge of his or her
26 | Copyright and Related Rights in the Work and the meaning and intended legal
27 | effect of CC0 on those rights.
28 |
29 | 1. Copyright and Related Rights. A Work made available under CC0 may be
30 | protected by copyright and related or neighboring rights ("Copyright and
31 | Related Rights"). Copyright and Related Rights include, but are not limited
32 | to, the following:
33 |
34 | i. the right to reproduce, adapt, distribute, perform, display, communicate,
35 | and translate a Work;
36 |
37 | ii. moral rights retained by the original author(s) and/or performer(s);
38 |
39 | iii. publicity and privacy rights pertaining to a person's image or likeness
40 | depicted in a Work;
41 |
42 | iv. rights protecting against unfair competition in regards to a Work,
43 | subject to the limitations in paragraph 4(a), below;
44 |
45 | v. rights protecting the extraction, dissemination, use and reuse of data in
46 | a Work;
47 |
48 | vi. database rights (such as those arising under Directive 96/9/EC of the
49 | European Parliament and of the Council of 11 March 1996 on the legal
50 | protection of databases, and under any national implementation thereof,
51 | including any amended or successor version of such directive); and
52 |
53 | vii. other similar, equivalent or corresponding rights throughout the world
54 | based on applicable law or treaty, and any national implementations thereof.
55 |
56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of,
57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
59 | and Related Rights and associated claims and causes of action, whether now
60 | known or unknown (including existing as well as future claims and causes of
61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum
62 | duration provided by applicable law or treaty (including future time
63 | extensions), (iii) in any current or future medium and for any number of
64 | copies, and (iv) for any purpose whatsoever, including without limitation
65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
66 | the Waiver for the benefit of each member of the public at large and to the
67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver
68 | shall not be subject to revocation, rescission, cancellation, termination, or
69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work
70 | by the public as contemplated by Affirmer's express Statement of Purpose.
71 |
72 | 3. Public License Fallback. Should any part of the Waiver for any reason be
73 | judged legally invalid or ineffective under applicable law, then the Waiver
74 | shall be preserved to the maximum extent permitted taking into account
75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
76 | is so judged Affirmer hereby grants to each affected person a royalty-free,
77 | non transferable, non sublicensable, non exclusive, irrevocable and
78 | unconditional license to exercise Affirmer's Copyright and Related Rights in
79 | the Work (i) in all territories worldwide, (ii) for the maximum duration
80 | provided by applicable law or treaty (including future time extensions), (iii)
81 | in any current or future medium and for any number of copies, and (iv) for any
82 | purpose whatsoever, including without limitation commercial, advertising or
83 | promotional purposes (the "License"). The License shall be deemed effective as
84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the
85 | License for any reason be judged legally invalid or ineffective under
86 | applicable law, such partial invalidity or ineffectiveness shall not
87 | invalidate the remainder of the License, and in such case Affirmer hereby
88 | affirms that he or she will not (i) exercise any of his or her remaining
89 | Copyright and Related Rights in the Work or (ii) assert any associated claims
90 | and causes of action with respect to the Work, in either case contrary to
91 | Affirmer's express Statement of Purpose.
92 |
93 | 4. Limitations and Disclaimers.
94 |
95 | a. No trademark or patent rights held by Affirmer are waived, abandoned,
96 | surrendered, licensed or otherwise affected by this document.
97 |
98 | b. Affirmer offers the Work as-is and makes no representations or warranties
99 | of any kind concerning the Work, express, implied, statutory or otherwise,
100 | including without limitation warranties of title, merchantability, fitness
101 | for a particular purpose, non infringement, or the absence of latent or
102 | other defects, accuracy, or the present or absence of errors, whether or not
103 | discoverable, all to the greatest extent permissible under applicable law.
104 |
105 | c. Affirmer disclaims responsibility for clearing rights of other persons
106 | that may apply to the Work or any use thereof, including without limitation
107 | any person's Copyright and Related Rights in the Work. Further, Affirmer
108 | disclaims responsibility for obtaining any necessary consents, permissions
109 | or other rights required for any use of the Work.
110 |
111 | d. Affirmer understands and acknowledges that Creative Commons is not a
112 | party to this document and has no duty or obligation with respect to this
113 | CC0 or use of the Work.
114 |
115 | For more information, please see
116 |
117 |
118 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Swift-FFT-Example
2 |
3 | Example Usage of the Fourier-Transform using Apple's Accelerate Framework in Swift, including a Bandpass Filter. This is more intendended as an example on how to use both forward and backward FFT, and how to apply a bandpass filter inbetween these steps. Evenly sampled values are assumed with an underlying framerate (i.e. FPS) for the bandpass filter to work. Both phase and magnitudes are calculated and bandpassed, as well as the values themselves.
4 |
5 | ## Compatibility
6 |
7 | Tested with Swift 3 and Xcode 8.3.1.
8 |
--------------------------------------------------------------------------------
/ffttest.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 46;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | 9D149E491B82226B00FF68B2 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D149E481B82226B00FF68B2 /* main.swift */; };
11 | 9D149E501B8222B100FF68B2 /* fft.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D149E4F1B8222B100FF68B2 /* fft.swift */; };
12 | /* End PBXBuildFile section */
13 |
14 | /* Begin PBXCopyFilesBuildPhase section */
15 | 9D149E431B82226B00FF68B2 /* CopyFiles */ = {
16 | isa = PBXCopyFilesBuildPhase;
17 | buildActionMask = 2147483647;
18 | dstPath = /usr/share/man/man1/;
19 | dstSubfolderSpec = 0;
20 | files = (
21 | );
22 | runOnlyForDeploymentPostprocessing = 1;
23 | };
24 | /* End PBXCopyFilesBuildPhase section */
25 |
26 | /* Begin PBXFileReference section */
27 | 9D149E451B82226B00FF68B2 /* ffttest */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = ffttest; sourceTree = BUILT_PRODUCTS_DIR; };
28 | 9D149E481B82226B00FF68B2 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; };
29 | 9D149E4F1B8222B100FF68B2 /* fft.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = fft.swift; sourceTree = ""; };
30 | /* End PBXFileReference section */
31 |
32 | /* Begin PBXFrameworksBuildPhase section */
33 | 9D149E421B82226B00FF68B2 /* Frameworks */ = {
34 | isa = PBXFrameworksBuildPhase;
35 | buildActionMask = 2147483647;
36 | files = (
37 | );
38 | runOnlyForDeploymentPostprocessing = 0;
39 | };
40 | /* End PBXFrameworksBuildPhase section */
41 |
42 | /* Begin PBXGroup section */
43 | 9D149E3C1B82226B00FF68B2 = {
44 | isa = PBXGroup;
45 | children = (
46 | 9D149E471B82226B00FF68B2 /* ffttest */,
47 | 9D149E461B82226B00FF68B2 /* Products */,
48 | );
49 | sourceTree = "";
50 | };
51 | 9D149E461B82226B00FF68B2 /* Products */ = {
52 | isa = PBXGroup;
53 | children = (
54 | 9D149E451B82226B00FF68B2 /* ffttest */,
55 | );
56 | name = Products;
57 | sourceTree = "";
58 | };
59 | 9D149E471B82226B00FF68B2 /* ffttest */ = {
60 | isa = PBXGroup;
61 | children = (
62 | 9D149E481B82226B00FF68B2 /* main.swift */,
63 | 9D149E4F1B8222B100FF68B2 /* fft.swift */,
64 | );
65 | path = ffttest;
66 | sourceTree = "";
67 | };
68 | /* End PBXGroup section */
69 |
70 | /* Begin PBXNativeTarget section */
71 | 9D149E441B82226B00FF68B2 /* ffttest */ = {
72 | isa = PBXNativeTarget;
73 | buildConfigurationList = 9D149E4C1B82226B00FF68B2 /* Build configuration list for PBXNativeTarget "ffttest" */;
74 | buildPhases = (
75 | 9D149E411B82226B00FF68B2 /* Sources */,
76 | 9D149E421B82226B00FF68B2 /* Frameworks */,
77 | 9D149E431B82226B00FF68B2 /* CopyFiles */,
78 | );
79 | buildRules = (
80 | );
81 | dependencies = (
82 | );
83 | name = ffttest;
84 | productName = ffttest;
85 | productReference = 9D149E451B82226B00FF68B2 /* ffttest */;
86 | productType = "com.apple.product-type.tool";
87 | };
88 | /* End PBXNativeTarget section */
89 |
90 | /* Begin PBXProject section */
91 | 9D149E3D1B82226B00FF68B2 /* Project object */ = {
92 | isa = PBXProject;
93 | attributes = {
94 | LastUpgradeCheck = 0830;
95 | ORGANIZATIONNAME = "Christopher Helf";
96 | TargetAttributes = {
97 | 9D149E441B82226B00FF68B2 = {
98 | CreatedOnToolsVersion = 6.4;
99 | LastSwiftMigration = 0830;
100 | };
101 | };
102 | };
103 | buildConfigurationList = 9D149E401B82226B00FF68B2 /* Build configuration list for PBXProject "ffttest" */;
104 | compatibilityVersion = "Xcode 5.2";
105 | developmentRegion = English;
106 | hasScannedForEncodings = 0;
107 | knownRegions = (
108 | en,
109 | );
110 | mainGroup = 9D149E3C1B82226B00FF68B2;
111 | productRefGroup = 9D149E461B82226B00FF68B2 /* Products */;
112 | projectDirPath = "";
113 | projectRoot = "";
114 | targets = (
115 | 9D149E441B82226B00FF68B2 /* ffttest */,
116 | );
117 | };
118 | /* End PBXProject section */
119 |
120 | /* Begin PBXSourcesBuildPhase section */
121 | 9D149E411B82226B00FF68B2 /* Sources */ = {
122 | isa = PBXSourcesBuildPhase;
123 | buildActionMask = 2147483647;
124 | files = (
125 | 9D149E501B8222B100FF68B2 /* fft.swift in Sources */,
126 | 9D149E491B82226B00FF68B2 /* main.swift in Sources */,
127 | );
128 | runOnlyForDeploymentPostprocessing = 0;
129 | };
130 | /* End PBXSourcesBuildPhase section */
131 |
132 | /* Begin XCBuildConfiguration section */
133 | 9D149E4A1B82226B00FF68B2 /* Debug */ = {
134 | isa = XCBuildConfiguration;
135 | buildSettings = {
136 | ALWAYS_SEARCH_USER_PATHS = NO;
137 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
138 | CLANG_CXX_LIBRARY = "libc++";
139 | CLANG_ENABLE_MODULES = YES;
140 | CLANG_ENABLE_OBJC_ARC = YES;
141 | CLANG_WARN_BOOL_CONVERSION = YES;
142 | CLANG_WARN_CONSTANT_CONVERSION = YES;
143 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
144 | CLANG_WARN_EMPTY_BODY = YES;
145 | CLANG_WARN_ENUM_CONVERSION = YES;
146 | CLANG_WARN_INFINITE_RECURSION = YES;
147 | CLANG_WARN_INT_CONVERSION = YES;
148 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
149 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
150 | CLANG_WARN_UNREACHABLE_CODE = YES;
151 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
152 | COPY_PHASE_STRIP = NO;
153 | DEBUG_INFORMATION_FORMAT = dwarf;
154 | ENABLE_STRICT_OBJC_MSGSEND = YES;
155 | ENABLE_TESTABILITY = YES;
156 | GCC_C_LANGUAGE_STANDARD = gnu99;
157 | GCC_DYNAMIC_NO_PIC = NO;
158 | GCC_NO_COMMON_BLOCKS = YES;
159 | GCC_OPTIMIZATION_LEVEL = 0;
160 | GCC_PREPROCESSOR_DEFINITIONS = (
161 | "DEBUG=1",
162 | "$(inherited)",
163 | );
164 | GCC_SYMBOLS_PRIVATE_EXTERN = NO;
165 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
166 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
167 | GCC_WARN_UNDECLARED_SELECTOR = YES;
168 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
169 | GCC_WARN_UNUSED_FUNCTION = YES;
170 | GCC_WARN_UNUSED_VARIABLE = YES;
171 | MACOSX_DEPLOYMENT_TARGET = 10.12;
172 | MTL_ENABLE_DEBUG_INFO = YES;
173 | ONLY_ACTIVE_ARCH = YES;
174 | SDKROOT = macosx;
175 | SWIFT_OPTIMIZATION_LEVEL = "-Onone";
176 | };
177 | name = Debug;
178 | };
179 | 9D149E4B1B82226B00FF68B2 /* Release */ = {
180 | isa = XCBuildConfiguration;
181 | buildSettings = {
182 | ALWAYS_SEARCH_USER_PATHS = NO;
183 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
184 | CLANG_CXX_LIBRARY = "libc++";
185 | CLANG_ENABLE_MODULES = YES;
186 | CLANG_ENABLE_OBJC_ARC = YES;
187 | CLANG_WARN_BOOL_CONVERSION = YES;
188 | CLANG_WARN_CONSTANT_CONVERSION = YES;
189 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
190 | CLANG_WARN_EMPTY_BODY = YES;
191 | CLANG_WARN_ENUM_CONVERSION = YES;
192 | CLANG_WARN_INFINITE_RECURSION = YES;
193 | CLANG_WARN_INT_CONVERSION = YES;
194 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
195 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
196 | CLANG_WARN_UNREACHABLE_CODE = YES;
197 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
198 | COPY_PHASE_STRIP = NO;
199 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
200 | ENABLE_NS_ASSERTIONS = NO;
201 | ENABLE_STRICT_OBJC_MSGSEND = YES;
202 | GCC_C_LANGUAGE_STANDARD = gnu99;
203 | GCC_NO_COMMON_BLOCKS = YES;
204 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
205 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
206 | GCC_WARN_UNDECLARED_SELECTOR = YES;
207 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
208 | GCC_WARN_UNUSED_FUNCTION = YES;
209 | GCC_WARN_UNUSED_VARIABLE = YES;
210 | MACOSX_DEPLOYMENT_TARGET = 10.12;
211 | MTL_ENABLE_DEBUG_INFO = NO;
212 | SDKROOT = macosx;
213 | SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
214 | };
215 | name = Release;
216 | };
217 | 9D149E4D1B82226B00FF68B2 /* Debug */ = {
218 | isa = XCBuildConfiguration;
219 | buildSettings = {
220 | PRODUCT_NAME = "$(TARGET_NAME)";
221 | SWIFT_VERSION = 5.2;
222 | };
223 | name = Debug;
224 | };
225 | 9D149E4E1B82226B00FF68B2 /* Release */ = {
226 | isa = XCBuildConfiguration;
227 | buildSettings = {
228 | PRODUCT_NAME = "$(TARGET_NAME)";
229 | SWIFT_VERSION = 5.2;
230 | };
231 | name = Release;
232 | };
233 | /* End XCBuildConfiguration section */
234 |
235 | /* Begin XCConfigurationList section */
236 | 9D149E401B82226B00FF68B2 /* Build configuration list for PBXProject "ffttest" */ = {
237 | isa = XCConfigurationList;
238 | buildConfigurations = (
239 | 9D149E4A1B82226B00FF68B2 /* Debug */,
240 | 9D149E4B1B82226B00FF68B2 /* Release */,
241 | );
242 | defaultConfigurationIsVisible = 0;
243 | defaultConfigurationName = Release;
244 | };
245 | 9D149E4C1B82226B00FF68B2 /* Build configuration list for PBXNativeTarget "ffttest" */ = {
246 | isa = XCConfigurationList;
247 | buildConfigurations = (
248 | 9D149E4D1B82226B00FF68B2 /* Debug */,
249 | 9D149E4E1B82226B00FF68B2 /* Release */,
250 | );
251 | defaultConfigurationIsVisible = 0;
252 | defaultConfigurationName = Release;
253 | };
254 | /* End XCConfigurationList section */
255 | };
256 | rootObject = 9D149E3D1B82226B00FF68B2 /* Project object */;
257 | }
258 |
--------------------------------------------------------------------------------
/ffttest.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/ffttest.xcodeproj/project.xcworkspace/xcuserdata/christopher.xcuserdatad/UserInterfaceState.xcuserstate:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/christopherhelf/Swift-FFT-Example/81b5eee9408a999e049be57c261de319252cf63e/ffttest.xcodeproj/project.xcworkspace/xcuserdata/christopher.xcuserdatad/UserInterfaceState.xcuserstate
--------------------------------------------------------------------------------
/ffttest.xcodeproj/xcuserdata/christopher.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
--------------------------------------------------------------------------------
/ffttest.xcodeproj/xcuserdata/christopher.xcuserdatad/xcschemes/ffttest.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
32 |
33 |
39 |
40 |
41 |
42 |
51 |
53 |
59 |
60 |
61 |
62 |
63 |
64 |
70 |
72 |
78 |
79 |
80 |
81 |
83 |
84 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/ffttest.xcodeproj/xcuserdata/christopher.xcuserdatad/xcschemes/xcschememanagement.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SchemeUserState
6 |
7 | ffttest.xcscheme
8 |
9 | orderHint
10 | 0
11 |
12 |
13 | SuppressBuildableAutocreation
14 |
15 | 9D149E441B82226B00FF68B2
16 |
17 | primary
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/ffttest/fft.swift:
--------------------------------------------------------------------------------
1 | //
2 | // fft.swift
3 | // ffttest
4 | //
5 | // Created by Christopher Helf on 17.08.15.
6 | // Copyright (c) 2015-Present Christopher Helf. All rights reserved.
7 | // Adapted From https://gerrybeauregard.wordpress.com/2013/01/28/using-apples-vdspaccelerate-fft/
8 |
9 | import Foundation
10 | import Accelerate
11 |
12 | class FFT {
13 |
14 | fileprivate func getFrequencies(_ N: Int, fps: Double) -> [Double] {
15 | // Create an Array with the Frequencies
16 | let freqs = (0.. ([Double], Int, Int) {
24 | var minIdx = freqs.count+1
25 | var maxIdx = -1
26 |
27 | let bandPassFilter: [Double] = freqs.map {
28 | if ($0 >= self.lowerFreq && $0 <= self.higherFreq) {
29 | return 1.0
30 | } else {
31 | return 0.0
32 | }
33 | }
34 |
35 | for (i, element) in bandPassFilter.enumerated() {
36 | if (element == 1.0) {
37 | if(imaxIdx || maxIdx == -1) {
41 | maxIdx=i
42 | }
43 | }
44 | }
45 |
46 | assert(maxIdx != -1)
47 | assert(minIdx != freqs.count+1)
48 |
49 | return (bandPassFilter, minIdx, maxIdx)
50 | }
51 |
52 | func calculate(_ _values: [Double], fps: Double) {
53 | // ----------------------------------------------------------------
54 | // Copy of our input
55 | // ----------------------------------------------------------------
56 | let values1 = _values
57 | var values = values1 // need this to avoid error below
58 |
59 | // ----------------------------------------------------------------
60 | // Size Variables
61 | // ----------------------------------------------------------------
62 | let N = values.count
63 | let N2 = vDSP_Length(N/2)
64 | let LOG_N = vDSP_Length(log2(Float(values.count)))
65 |
66 | // ----------------------------------------------------------------
67 | // FFT & Variables Setup
68 | // ----------------------------------------------------------------
69 | let fftSetup: FFTSetupD = vDSP_create_fftsetupD(LOG_N, FFTRadix(kFFTRadix2))!
70 |
71 | // We need complex buffers in two different formats!
72 | var tempComplex : [DSPDoubleComplex] = [DSPDoubleComplex](repeating: DSPDoubleComplex(), count: N/2)
73 |
74 | var tempSplitComplexReal : [Double] = [Double](repeating: 0.0, count: N/2)
75 | var tempSplitComplexImag : [Double] = [Double](repeating: 0.0, count: N/2)
76 | var tempSplitComplex : DSPDoubleSplitComplex = DSPDoubleSplitComplex(realp: &tempSplitComplexReal, imagp: &tempSplitComplexImag)
77 |
78 | // For polar coordinates
79 | var mag : [Double] = [Double](repeating: 0.0, count: N/2)
80 | var phase : [Double] = [Double](repeating: 0.0, count: N/2)
81 |
82 | // ----------------------------------------------------------------
83 | // Forward FFT
84 | // ----------------------------------------------------------------
85 |
86 | var valuesAsComplex : UnsafeMutablePointer? = nil
87 |
88 | values.withUnsafeMutableBytes {
89 | valuesAsComplex = $0.baseAddress?.bindMemory(to: DSPDoubleComplex.self, capacity: values1.count)
90 | }
91 |
92 | // Scramble-pack the real data into complex buffer in just the way that's
93 | // required by the real-to-complex FFT function that follows.
94 | vDSP_ctozD(valuesAsComplex!, 2, &tempSplitComplex, 1, N2);
95 |
96 | // Do real->complex forward FFT
97 | vDSP_fft_zripD(fftSetup, &tempSplitComplex, 1, LOG_N, FFTDirection(FFT_FORWARD));
98 |
99 | // ----------------------------------------------------------------
100 | // Get the Frequency Spectrum
101 | // ----------------------------------------------------------------
102 |
103 | var fftMagnitudes = [Double](repeating: 0.0, count: N/2)
104 | vDSP_zvmagsD(&tempSplitComplex, 1, &fftMagnitudes, 1, N2);
105 |
106 | // vDSP_zvmagsD returns squares of the FFT magnitudes, so take the root here
107 | let roots = sqrt(fftMagnitudes)
108 |
109 | // Normalize the Amplitudes
110 | var fullSpectrum = [Double](repeating: 0.0, count: N/2)
111 | vDSP_vsmulD(roots, vDSP_Stride(1), [1.0 / Double(N)], &fullSpectrum, 1, N2)
112 |
113 | // ----------------------------------------------------------------
114 | // Convert from complex/rectangular (real, imaginary) coordinates
115 | // to polar (magnitude and phase) coordinates.
116 | // ----------------------------------------------------------------
117 |
118 | vDSP_zvabsD(&tempSplitComplex, 1, &mag, 1, N2);
119 |
120 | // Beware: Outputted phase here between -PI and +PI
121 | // https://developer.apple.com/library/prerelease/ios/documentation/Accelerate/Reference/vDSPRef/index.html#//apple_ref/c/func/vDSP_zvphasD
122 | vDSP_zvphasD(&tempSplitComplex, 1, &phase, 1, N2);
123 |
124 | // ----------------------------------------------------------------
125 | // Bandpass Filtering
126 | // ----------------------------------------------------------------
127 |
128 | // Get the Frequencies for the current Framerate
129 | let freqs = getFrequencies(N,fps: fps)
130 | // Get a Bandpass Filter
131 | let bandPassFilter = generateBandPassFilter(freqs)
132 |
133 | // Multiply phase and magnitude with the bandpass filter
134 | mag = mul(mag, y: bandPassFilter.0)
135 | phase = mul(phase, y: bandPassFilter.0)
136 |
137 | // Output Variables
138 | let filteredSpectrum = mul(fullSpectrum, y: bandPassFilter.0)
139 | var filteredPhase = phase
140 |
141 | // ----------------------------------------------------------------
142 | // Determine Maximum Frequency
143 | // ----------------------------------------------------------------
144 | let maxFrequencyResult = max(filteredSpectrum)
145 | let maxFrequency = freqs[maxFrequencyResult.1]
146 | let maxPhase = filteredPhase[maxFrequencyResult.1]
147 |
148 | print("Amplitude: \(maxFrequencyResult.0)")
149 | print("Frequency: \(maxFrequency)")
150 | print("Phase: \(maxPhase + .pi / 2)")
151 |
152 | // ----------------------------------------------------------------
153 | // Convert from polar coordinates back to rectangular coordinates.
154 | // ----------------------------------------------------------------
155 |
156 | tempSplitComplex = DSPDoubleSplitComplex(realp: &mag, imagp: &phase)
157 |
158 | var complexAsValue : UnsafeMutablePointer? = nil
159 |
160 | tempComplex.withUnsafeMutableBytes {
161 | complexAsValue = $0.baseAddress?.bindMemory(to: Double.self, capacity: values.count)
162 | }
163 |
164 | vDSP_ztocD(&tempSplitComplex, 1, &tempComplex, 2, N2);
165 | vDSP_rectD(complexAsValue!, 2, complexAsValue!, 2, N2);
166 | vDSP_ctozD(&tempComplex, 2, &tempSplitComplex, 1, N2);
167 |
168 | // ----------------------------------------------------------------
169 | // Do Inverse FFT
170 | // ----------------------------------------------------------------
171 |
172 | // Create result
173 | var result : [Double] = [Double](repeating: 0.0, count: N)
174 | var resultAsComplex : UnsafeMutablePointer? = nil
175 |
176 | result.withUnsafeMutableBytes {
177 | resultAsComplex = $0.baseAddress?.bindMemory(to: DSPDoubleComplex.self, capacity: values.count)
178 | }
179 |
180 | // Do complex->real inverse FFT.
181 | vDSP_fft_zripD(fftSetup, &tempSplitComplex, 1, LOG_N, FFTDirection(FFT_INVERSE));
182 |
183 | // This leaves result in packed format. Here we unpack it into a real vector.
184 | vDSP_ztocD(&tempSplitComplex, 1, resultAsComplex!, 2, N2);
185 |
186 | // Neither the forward nor inverse FFT does any scaling. Here we compensate for that.
187 | var scale : Double = 0.5/Double(N);
188 | var copyOfResult = result;
189 | vDSP_vsmulD(&result, 1, &scale, ©OfResult, 1, vDSP_Length(N));
190 | result = copyOfResult
191 |
192 | // Print Result
193 | for k in 0 ..< N {
194 | print("\(k) \(values[k]) \(result[k])")
195 | }
196 | }
197 |
198 | // The bandpass frequencies
199 | let lowerFreq : Double = 3
200 | let higherFreq: Double = 5
201 |
202 | // Some Math functions on Arrays
203 | func mul(_ x: [Double], y: [Double]) -> [Double] {
204 | var results = [Double](repeating: 0.0, count: x.count)
205 | vDSP_vmulD(x, 1, y, 1, &results, 1, vDSP_Length(x.count))
206 |
207 | return results
208 | }
209 |
210 | func sqrt(_ x: [Double]) -> [Double] {
211 | var results = [Double](repeating: 0.0, count: x.count)
212 | vvsqrt(&results, x, [Int32(x.count)])
213 |
214 | return results
215 | }
216 |
217 | func max(_ x: [Double]) -> (Double, Int) {
218 | var result: Double = 0.0
219 | var idx : vDSP_Length = vDSP_Length(0)
220 | vDSP_maxviD(x, 1, &result, &idx, vDSP_Length(x.count))
221 |
222 | return (result, Int(idx))
223 | }
224 | }
225 |
--------------------------------------------------------------------------------
/ffttest/main.swift:
--------------------------------------------------------------------------------
1 | //
2 | // main.swift
3 | // ffttest
4 | //
5 | // Created by Christopher Helf on 17.08.15.
6 | // Copyright (c) 2015-Present Christopher Helf. All rights reserved.
7 | //
8 |
9 | import Foundation
10 | import Accelerate
11 |
12 | var fft = FFT()
13 |
14 | let n = 512 // Should be power of two for the FFT
15 | let frequency1 = 4.0
16 | let phase1 = 0.0
17 | let amplitude1 = 8.0
18 | let seconds = 2.0
19 | let fps = Double(n)/seconds
20 |
21 | var sineWave = (0..