comparison toolboxes/MIRtoolbox1.3.2/MIRToolbox/mp3read.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:e9a9cd732c1e
1 function [Y,FS,NBITS,OPTS] = mp3read(FILE,N,MONO,DOWNSAMP,DELAY)
2 % MP3READ Read MP3 audio file via use of external binaries.
3 % Y = MP3READ(FILE) reads an mp3-encoded audio file into the
4 % vector Y just like wavread reads a wav-encoded file (one channel
5 % per column). Extension ".mp3" is added if FILE has none.
6 % Also accepts other formats of wavread, such as
7 % Y = MP3READ(FILE,N) to read just the first N sample frames (N
8 % scalar), or the frames from N(1) to N(2) if N is a two-element vector.
9 % Y = MP3READ(FILE,FMT) or Y = mp3read(FILE,N,FMT)
10 % with FMT as 'native' returns int16 samples instead of doubles;
11 % FMT can be 'double' for default behavior (to exactly mirror the
12 % syntax of wavread).
13 %
14 % [Y,FS,NBITS,OPTS] = MP3READ(FILE...) returns extra information:
15 % FS is the sampling rate, NBITS is the bit depth (always 16),
16 % OPTS.fmt is a format info string; OPTS has multiple other
17 % fields, see WAVREAD.
18 %
19 % SIZ = MP3READ(FILE,'size') returns the size of the audio data contained
20 % in the file in place of the actual audio data, returning the
21 % 2-element vector SIZ=[samples channels].
22 %
23 % [Y...] = MP3READ(FILE,N,MONO,DOWNSAMP,DELAY) extends the
24 % WAVREAD syntax to allow access to special features of the
25 % mpg123 engine: MONO = 1 forces output to be mono (by
26 % averaging stereo channels); DOWNSAMP = 2 or 4 downsamples by
27 % a factor of 2 or 4 (thus FS returns as 22050 or 11025
28 % respectively for a 44 kHz mp3 file); DELAY controls how many
29 % "warm up" samples to drop at the start of the file; the
30 % default value of 2257 makes an mp3write/mp3read loop for a 44
31 % kHz mp3 file be as close as possible to being temporally
32 % aligned; specify as 0 to prevent discard of initial samples.
33 %
34 % Example:
35 % To read an mp3 file as doubles at its original width and sampling rate:
36 % [Y,FS] = mp3read('piano.mp3');
37 % To read the first 1 second of the same file, downsampled by a
38 % factor of 4, cast to mono, using the default filename
39 % extension:
40 % [Y,FS4] = mp3read('piano', FS/4, 1, 4);
41 %
42 % Note: Because the mp3 format encodes samples in blocks of 26 ms (at
43 % 44 kHz), and because of the "warm up" period of the encoder,
44 % the file length may not be exactly what you expect.
45 %
46 % Note: requires external binaries mpg123 and mp3info; you
47 % can find binaries for several platforms at:
48 % http://labrosa.ee.columbia.edu/matlab/mp3read.html
49 %
50 % See also mp3write, wavread.
51
52 % 2003-07-20 dpwe@ee.columbia.edu This version calls mpg123.
53 % 2004-08-31 Fixed to read whole files correctly
54 % 2004-09-08 Uses mp3info to get info about mp3 files too
55 % 2004-09-18 Reports all mp3info fields in OPTS.fmt; handles MPG2LSF sizes
56 % + added MONO, DOWNSAMP flags, changed default behavior.
57 % 2005-09-28 Fixed bug reading full-rate stereo as 1ch (thx bjoerns@vjk.dk)
58 % 2006-09-17 Chop off initial 2257 sample delay (for 44.1 kHz mp3)
59 % so read-write loop doesn't get progressively delayed.
60 % You can suppress this with a 5th argument of 0.
61 % 2007-02-04 Added support for FMT argument to match wavread
62 % Added automatic selection of binary etc. to allow it
63 % to work cross-platform without editing prior to
64 % submitting to Matlab File Exchange
65 % 2007-07-23 Tweaks to 'size' mode so it exactly agrees with read data.
66
67 % find our baseline directory
68 path = fileparts(which('mp3read'));
69
70 % %%%%% Directory for temporary file (if needed)
71 % % Try to read from environment, or use /tmp if it exists, or use CWD
72 tmpdir = getenv('TMPDIR');
73 if isempty(tmpdir) || exist(tmpdir,'file')==0
74 tmpdir = '/tmp';
75 end
76 if exist(tmpdir,'file')==0
77 tmpdir = '';
78 end
79 % ensure it exists
80 %if length(tmpdir) > 0 && exist(tmpdir,'file')==0
81 % mkdir(tmpdir);
82 %end
83
84 %%%%%% Command to delete temporary file (if needed)
85 rmcmd = 'rm';
86
87 %%%%%% Location of the binaries - attempt to choose automatically
88 %%%%%% (or edit to be hard-coded for your installation)
89 ext = lower(computer);
90 if ispc
91 ext = 'exe';
92 rmcmd = 'del';
93 end
94 mpg123 = fullfile(path,['mpg123.',ext]);
95 mp3info = fullfile(path,['mp3info.',ext]);
96
97 %%%%% Process input arguments
98 if nargin < 2
99 N = 0;
100 end
101
102 % Check for FMT spec (per wavread)
103 FMT = 'double';
104 if ischar(N)
105 FMT = lower(N);
106 N = 0;
107 end
108
109 if length(N) == 1
110 % Specified N was upper limit
111 N = [1 N];
112 end
113 if nargin < 3
114 forcemono = 0;
115 else
116 % Check for 3rd arg as FMT
117 if ischar(MONO)
118 FMT = lower(MONO);
119 MONO = 0;
120 end
121 forcemono = (MONO ~= 0);
122 end
123 if nargin < 4
124 downsamp = 1;
125 else
126 downsamp = DOWNSAMP;
127 end
128 if downsamp ~= 1 && downsamp ~= 2 && downsamp ~= 4
129 error('DOWNSAMP can only be 1, 2, or 4');
130 end
131 if nargin < 5
132 mpg123delay44kHz = 2257; % empirical delay of lame/mpg123 loop
133 delay = round(mpg123delay44kHz/downsamp);
134 else
135 delay = DELAY;
136 end
137
138 if strcmp(FMT,'native') == 0 && strcmp(FMT,'double') == 0 && ...
139 strcmp(FMT,'size') == 0
140 error(['FMT must be ''native'' or ''double'' (or ''size''), not ''',FMT,'''']);
141 end
142
143
144 %%%%%% Constants
145 NBITS=16;
146
147 %%%%% add extension if none (like wavread)
148 [path,file,ext] = fileparts(FILE);
149 if isempty(ext)
150 FILE = [FILE, '.mp3'];
151 end
152
153 %%%%%% Probe file to find format, size, etc. using "mp3info" utility
154 cmd = ['"',mp3info, '" -r m -p "%Q %u %b %r %v * %C %e %E %L %O %o %p" "', FILE,'"'];
155 % Q = samprate, u = #frames, b = #badframes (needed to get right answer from %u)
156 % r = bitrate, v = mpeg version (1/2/2.5)
157 % C = Copyright, e = emph, E = CRC, L = layer, O = orig, o = mono, p = pad
158 w = mysystem(cmd);
159 % Break into numerical and ascii parts by finding the delimiter we put in
160 starpos = findstr(w,'*');
161 nums = str2num(w(1:(starpos - 2)));
162 strs = tokenize(w((starpos+2):end));
163
164 SR = nums(1);
165 nframes = nums(2);
166 nchans = 2 - strcmp(strs{6}, 'mono');
167 layer = length(strs{4});
168 bitrate = nums(4)*1000;
169 mpgv = nums(5);
170 % Figure samples per frame, after
171 % http://board.mp3-tech.org/view.php3?bn=agora_mp3techorg&key=1019510889
172 if layer == 1
173 smpspfrm = 384;
174 elseif SR < 32000 && layer ==3
175 smpspfrm = 576;
176 if mpgv == 1
177 error('SR < 32000 but mpeg version = 1');
178 end
179 else
180 smpspfrm = 1152;
181 end
182
183 OPTS.fmt.mpgBitrate = bitrate;
184 OPTS.fmt.mpgVersion = mpgv;
185 % fields from wavread's OPTS
186 OPTS.fmt.nAvgBytesPerSec = bitrate/8;
187 OPTS.fmt.nSamplesPerSec = SR;
188 OPTS.fmt.nChannels = nchans;
189 OPTS.fmt.nBlockAlign = smpspfrm/SR*bitrate/8;
190 OPTS.fmt.nBitsPerSample = NBITS;
191 OPTS.fmt.mpgNFrames = nframes;
192 OPTS.fmt.mpgCopyright = strs{1};
193 OPTS.fmt.mpgEmphasis = strs{2};
194 OPTS.fmt.mpgCRC = strs{3};
195 OPTS.fmt.mpgLayer = strs{4};
196 OPTS.fmt.mpgOriginal = strs{5};
197 OPTS.fmt.mpgChanmode = strs{6};
198 OPTS.fmt.mpgPad = strs{7};
199 OPTS.fmt.mpgSampsPerFrame = smpspfrm;
200
201 if SR == 16000 && downsamp == 4
202 error('mpg123 will not downsample 16 kHz files by 4 (only 2)');
203 end
204
205 if downsamp == 1
206 downsampstr = '';
207 else
208 downsampstr = [' -',num2str(downsamp)];
209 end
210 FS = SR/downsamp;
211
212 if forcemono == 1
213 nchans = 1;
214 chansstr = ' -m';
215 else
216 chansstr = '';
217 end
218
219 % Size-reading version
220 if strcmp(FMT,'size') == 1
221 Y = [floor(smpspfrm*nframes/downsamp)-delay, nchans];
222 else
223
224 % Temporary file to use
225 tmpfile = fullfile(tmpdir, ['tmp',num2str(round(1000*rand(1))),'.wav']);
226
227 skipx = 0;
228 skipblks = 0;
229 skipstr = '';
230 sttfrm = N(1)-1;
231
232 % chop off transcoding delay?
233 %sttfrm = sttfrm + delay; % empirically measured
234 % no, we want to *decode* those samples, then drop them
235 % so delay gets added to skipx instead
236
237 if sttfrm > 0
238 skipblks = floor(sttfrm*downsamp/smpspfrm);
239 skipx = sttfrm - (skipblks*smpspfrm/downsamp);
240 skipstr = [' -k ', num2str(skipblks)];
241 end
242 skipx = skipx + delay;
243
244 lenstr = '';
245 endfrm = -1;
246 decblk = 0;
247 if length(N) > 1
248 endfrm = N(2);
249 if endfrm > sttfrm
250 decblk = ceil((endfrm+delay)*downsamp/smpspfrm) - skipblks + 10;
251 % we read 10 extra blks (+10) to cover the case where up to 10 bad
252 % blocks are included in the part we are trying to read (it happened)
253 lenstr = [' -n ', num2str(decblk)];
254 % This generates a spurious "Warn: requested..." if reading right
255 % to the last sample by index (or bad blks), but no matter.
256 end
257 end
258
259 % Run the decode
260 cmd=['"',mpg123,'"', downsampstr, chansstr, skipstr, lenstr, ...
261 ' -q -w "', tmpfile,'" "',FILE,'"'];
262 %w =
263 mysystem(cmd);
264
265 % Load the data
266 Y = wavread(tmpfile);
267
268 % % pad delay on to end, just in case
269 % Y = [Y; zeros(delay,size(Y,2))];
270 % % no, the saved file is just longer
271
272 if decblk > 0 && length(Y) < decblk*smpspfrm/downsamp
273 % This will happen if the selected block range includes >1 bad block
274 disp(['Warn: requested ', num2str(decblk*smpspfrm/downsamp),' frames, returned ',num2str(length(Y))]);
275 end
276
277 % Delete tmp file
278 mysystem([rmcmd,' "', tmpfile,'"']);
279
280 % debug
281 % disp(['sttfrm=',num2str(sttfrm),' endfrm=',num2str(endfrm),' skipx=',num2str(skipx),' delay=',num2str(delay),' len=',num2str(length(Y))]);
282
283 % Select the desired part
284 if skipx+endfrm-sttfrm > length(Y)
285 endfrm = length(Y)+sttfrm-skipx;
286 end
287
288 if endfrm > sttfrm
289 Y = Y(skipx+(1:(endfrm-sttfrm)),:);
290 elseif skipx > 0
291 Y = Y((skipx+1):end,:);
292 end
293
294 % Convert to int if format = 'native'
295 if strcmp(FMT,'native')
296 Y = int16((2^15)*Y);
297 end
298
299 end
300
301 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
302 function w = mysystem(cmd)
303 % Run system command; report error; strip all but last line
304 [s,w] = system(cmd);
305 if s ~= 0
306 error(['unable to execute ',cmd,' (',w,')']);
307 end
308 % Keep just final line
309 w = w((1+max([0,findstr(w,10)])):end);
310 % Debug
311 %disp([cmd,' -> ','*',w,'*']);
312
313 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
314 function a = tokenize(s)
315 % Break space-separated string into cell array of strings
316 % 2004-09-18 dpwe@ee.columbia.edu
317 a = [];
318 p = 1;
319 n = 1;
320 l = length(s);
321 nss = findstr([s(p:end),' '],' ');
322 for ns = nss
323 % Skip initial spaces
324 if ns == p
325 p = p+1;
326 else
327 if p <= l
328 a{n} = s(p:(ns-1));
329 n = n+1;
330 p = ns+1;
331 end
332 end
333 end
334