sphear_fir_design.m 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. %%
  2. %% *SpHEAR Project
  3. %%
  4. %% sphear_fir_design: design a matrix of FIR filters that equalizes the microphone
  5. %%
  6. %% usage:
  7. %% [FIR] = sphear_fir_design(F, A2BF, n, Fs, Fl, plot_on, W, X, Y, Z)
  8. %%
  9. %% F: array of filter section center frequencies
  10. %% A2BF: vector of A2B matrixes, one for each frequency
  11. %% n: order of the FIR filter being created
  12. %% maxboost: max high and low frequency boost in dB of the final filter
  13. %% Fs: sampling rate
  14. %% Fl: frequency limit, below it use A2B matrixes, above it use W, X, Y, Z shapes
  15. %% plot_on: plot frequency response of components, default is "epsc"
  16. %% can be one of 0, "eps", "epsc" (color), "png", "pngc" (color)
  17. %%
  18. %% for the first run do not supply W/X/Y/Z, render the filters and then run
  19. %% sphear_fir_extract to extract the W, X, Y and Z filter shapes, finally run
  20. %% this again with the extra parameters below
  21. %%
  22. %% W: extracted shape of W filter (used above Fl)
  23. %% X: extracted shape of X filter (used above Fl)
  24. %% Y: extracted shape of Y filter (used above Fl)
  25. %% Z: extracted shape of Z filter (used above Fl)
  26. %% Z is optional, if not supplied X and Y are averaged to obtain Z
  27. %%
  28. %% Copyright 2016, Fernando Lopez-Lezcano, All Rights Reserved
  29. %% nando@ccrma.stanford.edu
  30. %%
  31. %% This program is free software: you can redistribute it and/or modify
  32. %% it under the terms of the GNU General Public License as published by
  33. %% the Free Software Foundation, either version 3 of the License, or
  34. %% (at your option) any later version.
  35. %%
  36. %% This program is distributed in the hope that it will be useful,
  37. %% but WITHOUT ANY WARRANTY; without even the implied warranty of
  38. %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  39. %% GNU General Public License for more details.
  40. %%
  41. %% You should have received a copy of the GNU General Public License
  42. %% along with this program. If not, see <http://www.gnu.org/licenses/>.
  43. function [FIR] = sphear_fir_design(F, A2BF, n, maxboost, Fs, Fl, plot_on, W, X, Y, Z)
  44. minphase = 1;
  45. if (plot_on != 0)
  46. fig = figure;
  47. end
  48. if (exist("W") == 1 && ! exist("Z"))
  49. %% Z was not supplied, just average X and Y data
  50. Z = (X + Y) / 2;
  51. end
  52. %% all b format components
  53. for b = 1:4
  54. %% all capsules
  55. for c = 1:4
  56. %% all frequency bands
  57. for d = 1:size(A2BF(:,1,1))(1)
  58. %% create an array of points to design the filter
  59. if (F(d) <= Fl)
  60. %% below the limit frequency we use the A2B coefficients
  61. vlast = A2BF(d, c, b);
  62. dlast = d;
  63. if (exist("W") == 1)
  64. wlast = W(d);
  65. xlast = X(d);
  66. ylast = Y(d);
  67. zlast = Z(d);
  68. end
  69. else
  70. %% above the limit frequency we insert the W, X, Y and Z
  71. %% data if they exist, otherwise keep the last valid value
  72. %% from the A2B coefficients (ie: flat above the transition
  73. %% frequency
  74. if (b == 1)
  75. if (exist("W") == 1)
  76. A2BF(d, c, b) = vlast * (W(d)/wlast);
  77. else
  78. A2BF(d, c, b) = vlast;
  79. end
  80. end
  81. if (b == 2)
  82. if (exist("X") == 1)
  83. A2BF(d, c, b) = vlast * (X(d)/xlast);
  84. else
  85. A2BF(d, c, b) = vlast;
  86. end
  87. end
  88. if (b == 3)
  89. if (exist("Y") == 1)
  90. A2BF(d, c, b) = vlast * (Y(d)/ylast);
  91. else
  92. A2BF(d, c, b) = vlast;
  93. end
  94. end
  95. if (b == 4)
  96. if (exist("Z") == 1)
  97. A2BF(d, c, b) = vlast * (Z(d)/zlast);
  98. else
  99. A2BF(d, c, b) = vlast;
  100. end
  101. end
  102. end
  103. end
  104. end
  105. end
  106. %% normalize all components to the average of W levels for all
  107. %% capsules around the transition frequency
  108. if ((dlast+1) > size(A2BF(:,1,1))(1))
  109. %% special case for testing with a very high transition frequency
  110. avg = [dlast-3, dlast-2, dlast-1];
  111. else
  112. avg = [dlast-1, dlast, dlast+1];
  113. end
  114. nrm = mean([mean(A2BF(avg,1,1))
  115. mean(A2BF(avg,2,1))
  116. mean(A2BF(avg,3,1))
  117. mean(A2BF(avg,4,1))]);
  118. for b = 1:4
  119. for c = 1:4
  120. %% normalize coefficients
  121. for dn = 1:size(A2BF(:,1,1))(1)
  122. A2BF(dn,c,b) = A2BF(dn,c,b) ./ nrm;
  123. end
  124. %% fit a spline to the W, X, Y and Z data and extrapolate
  125. %% highest frequency if it does not exist in the measurements
  126. %%
  127. %% the 200Hz spacing of the points is arbitrary, we should
  128. %% select something that makes more sense
  129. %%
  130. fh = (F(dlast-1)/(Fs/2):200/(Fs/2):1)';
  131. %% make the end really 1.0
  132. fh(end) = 1;
  133. rh = interp1(F(dlast-1:end)/(Fs/2), A2BF(dlast-1:end,c,b)', fh, "spline", "extrap");
  134. %% we fit the spline taking into account one additional point
  135. %% on the bottom edge so that it will fit better with the existing
  136. %% low frequency points, now we need to find the exact transition
  137. %% frequency in the interpolated array
  138. for idx = 1:size(fh(:))
  139. if (fh(idx) <= F(dlast)/(Fs/2))
  140. istart = idx;
  141. end
  142. end
  143. %% extract the low frequency A2B coefficients
  144. fl = [0 F(1:dlast-1)']' ./ (Fs/2);
  145. rl = [A2BF(1,c,b) A2BF(1:dlast-1,c,b)']';
  146. %% concatenate low and high frequency arrays
  147. fi = cat(1, fl, fh(istart:end));
  148. ri = cat(1, rl, rh(istart:end));
  149. printf("low frequency boost %f, high frequency boost %f\n", 20*log10(ri(1)), 20*log10(ri(end)));
  150. %% force a max boost at low and high frequencies
  151. if (maxboost != 0)
  152. if (abs(ri(1)) > 10^(maxboost/20))
  153. printf("limit low freq boost from %f to %f dB (%f)\n", 20*log10(ri(1)), maxboost, ri(1));
  154. ri(1) = sign(ri(1)) * 10^(maxboost/20);
  155. printf("new limit %f\n", ri(1));
  156. end
  157. if (abs(ri(end)) > 10^(maxboost/20))
  158. printf("limit high freq boost from %f dB to %f dB (%f)\n", 20*log10(ri(end)), maxboost, ri(end));
  159. ri(end) = sign(ri(end)) * 10^(maxboost/20);
  160. printf("new limit %f\n", ri(end));
  161. end
  162. end
  163. if (plot_on != 0)
  164. if (strcmp(plot_on, "epsc") || strcmp(plot_on, "pngc"))
  165. %% color plot
  166. popts = '.k';
  167. wopts = 'b';
  168. xyopts = 'r';
  169. zopts = 'g';
  170. copt = '-color';
  171. cext = "_color";
  172. else
  173. %% mono plot
  174. popts = '.k';
  175. wopts = '-';
  176. xyopts = '--';
  177. zopts = ':';
  178. copt = '-mono';
  179. cext = "_mono";
  180. end
  181. grid on;
  182. axis([400, 20000]);
  183. xticks = [300, 500, 1000, 2000, 3000, 5000, 7000, 10000, 20000];
  184. set(gca, 'XTick', xticks);
  185. set(gca, 'XTickLabel', sprintf('%d|', xticks));
  186. ca=get (gcf, "currentaxes");
  187. set(ca,"fontweight","bold","linewidth",1.5)
  188. pbaspect([16, 9, 1])
  189. %% title(sprintf("B format FIR filters (transition frequency: %d Hz)", Fl));
  190. hold on;
  191. %% plot real measured points
  192. %% ph = semilogx(F, 20*log10(abs(A2BF(:,c,b)))', popts, "linewidth", 1.5);
  193. %% plot extrapolated filter
  194. if (b == 1)
  195. %% W
  196. wh = semilogx(fi*(Fs/2), 20*log10(abs(ri)), wopts, "linewidth", 1.5);
  197. else
  198. if (b == 4)
  199. %% Z
  200. zh = semilogx(fi*(Fs/2), 20*log10(abs(ri)), zopts, "linewidth", 1.5);
  201. else
  202. %% XY
  203. xyh = semilogx(fi*(Fs/2), 20*log10(abs(ri)), xyopts, "linewidth", 1.5);
  204. end
  205. end
  206. end
  207. %% design the filter
  208. FIR(b, c, :) = fir2(n, fi, ri);
  209. if (minphase != 0)
  210. %% try to get it close to minimum phase
  211. %%
  212. %% "Two alternative minimum-phase filters tested perceptually"
  213. %% Robert Mores and Ralf Hendrych, AES Convertion paper 9554
  214. %%
  215. IR = reshape(FIR(b, c, :), 257, 1);
  216. %% number of samples in the sin transition
  217. %%
  218. %% 8 seems to be the sweet spot for a FIR filter size of 256,
  219. %% 16 leads to bigger phase shift, 4 starts to impact negatively
  220. %% the flattness of the frequency response
  221. %%
  222. N = 16;
  223. M = size(IR)(1);
  224. R = 0.5 + (0.5 * sin(pi * ((1:(2*N)) - N) / (2 * N)));
  225. ramp = [zeros(M/2 - N + 1, 1); R'; ones(M/2 - N, 1)];
  226. IRR = (IR .* ramp * 2);
  227. FIR(b, c, :) = IRR(:);
  228. end
  229. end
  230. end
  231. if (plot_on != 0)
  232. l = legend([wh, zh, xyh], {'W', 'XY', 'Z'});
  233. legend(l, 'location', 'west');
  234. if (exist("W") == 1)
  235. if (strcmp(plot_on, 'eps') || strcmp(plot_on, 'epsc') || plot_on == 1)
  236. print(fig, '-deps','-tight',copt,["figures/wxyz_filter_ff" cext ".eps"]);
  237. else
  238. print(fig, '-dpng',copt,["figures/wxyz_filter_ff" cext ".png"]);
  239. end
  240. else
  241. if (strcmp(plot_on, 'eps') || strcmp(plot_on, 'epsc') || plot_on == 1)
  242. print(fig, '-deps','-tight',copt,["figures/wxyz_filter_lf" cext ".eps"]);
  243. else
  244. print(fig, '-dpng',copt,["figures/wxyz_filter_lf" cext ".png"]);
  245. end
  246. end
  247. end
  248. end