]> Creatis software - CreaPhase.git/blob - octave_packages/m/audio/lin2mu.m
update packages
[CreaPhase.git] / octave_packages / m / audio / lin2mu.m
1 ## Copyright (C) 1995-2012 John W. Eaton
2 ##
3 ## This file is part of Octave.
4 ##
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
9 ##
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 ## General Public License for more details.
14 ##
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING.  If not, see
17 ## <http://www.gnu.org/licenses/>.
18
19 ## -*- texinfo -*-
20 ## @deftypefn {Function File} {} lin2mu (@var{x}, @var{n})
21 ## Convert audio data from linear to mu-law.  Mu-law values use 8-bit
22 ## unsigned integers.  Linear values use @var{n}-bit signed integers or
23 ## floating point values in the range -1 @leq{} @var{x} @leq{} 1 if
24 ## @var{n} is 0.
25 ##
26 ## If @var{n} is not specified it defaults to 0, 8, or 16 depending on
27 ## the range of values in @var{x}.
28 ## @seealso{mu2lin, loadaudio, saveaudio}
29 ## @end deftypefn
30
31
32 ## Author: Andreas Weingessel <Andreas.Weingessel@ci.tuwien.ac.at>
33 ## Created: 17 October 1994
34 ## Adapted-By: jwe
35
36 function y = lin2mu (x, n)
37
38   if (nargin == 1)
39     range = max (abs (x (:)));
40     if (range <= 1)
41       n = 0;
42     elseif (range <= 128)
43       n = 8;
44       warning ("lin2mu: no precision specified, so using %d", n);
45     else
46       n = 16;
47     endif
48   elseif (nargin == 2)
49     if (n != 0 && n != 8 && n != 16)
50       error ("lin2mu: N must be either 0, 8 or 16");
51     endif
52   else
53     print_usage ();
54   endif
55
56   ## Transform real and n-bit format to 16-bit.
57   if (n == 0)
58     ## [-1,1] -> [-32768, 32768]
59     x = 32768 * x;
60   elseif (n != 16)
61     x = 2^(16-n) .* x;
62   endif
63
64   ## Determine sign of x, set sign(0) = 1.
65   sig = sign(x) + (x == 0);
66
67   ## Take absolute value of x, but force it to be smaller than 32636;
68   ## add bias.
69   x = min (abs (x), 32635) + 132;
70
71   ## Find exponent and fraction of bineary representation.
72   [f, e] = log2 (x);
73
74   y = 64 * sig - 16 * e - fix (32 * f) + 335;
75
76 endfunction