lpc10codec.cpp
上传用户:zslianheng
上传日期:2013-04-03
资源大小:946k
文件大小:2k
源码类别:

Linux/Unix编程

开发平台:

Visual C++

  1. /***************************************************************************
  2.  *                                                                         *
  3.  *   This program is free software; you can redistribute it and/or modify  *
  4.  *   it under the terms of the GNU General Public License as published by  *
  5.  *   the Free Software Foundation; either version 2 of the License, or     *
  6.  *   (at your option) any later version.                                   *
  7.  *                                                                         *
  8.  *   copyright            : (C) 2002 by Zhang Yong                         *
  9.  *   email                : z-yong163@163.com                              *
  10.  ***************************************************************************/
  11. #include "lpc10codec.h"
  12. #include <malloc.h>
  13. #include <memory.h>
  14. #define LPC10_BYTES_IN_COMPRESSED_FRAME
  15. ((LPC10_BITS_IN_COMPRESSED_FRAME >> 3) + !!(LPC10_BITS_IN_COMPRESSED_FRAME & 7))
  16. Lpc10Codec::Lpc10Codec()
  17. {
  18. encodeState = create_lpc10_encoder_state();
  19. decodeState = create_lpc10_decoder_state();
  20. }
  21. Lpc10Codec::~Lpc10Codec()
  22. {
  23. free(encodeState);
  24. free(decodeState);
  25. }
  26. int Lpc10Codec::encode(const char *in, char *out, int n)
  27. {
  28. float speech[LPC10_SAMPLES_PER_FRAME];
  29. INT32 bits[LPC10_BITS_IN_COMPRESSED_FRAME];
  30. short *data = (short *) in;
  31. n /= sizeof(short);
  32. int i = n % LPC10_SAMPLES_PER_FRAME;
  33. if (i) {
  34. i = LPC10_SAMPLES_PER_FRAME - i;
  35. while (i-- > 0)
  36. data[n++] = 0;
  37. }
  38. char *p = out;
  39. n /= LPC10_SAMPLES_PER_FRAME;
  40. memset(out, 0, n * LPC10_BYTES_IN_COMPRESSED_FRAME);
  41. while (n-- > 0) {
  42. for (i = 0; i < LPC10_SAMPLES_PER_FRAME; ++i)
  43. speech[i] = data[i] / 32768.0f;
  44. lpc10_encode(speech, bits, encodeState);
  45. for (i = 0; i < LPC10_BITS_IN_COMPRESSED_FRAME; ++i)
  46. p[i >> 3] |= (!!bits[i] << (i & 7));
  47. p += LPC10_BYTES_IN_COMPRESSED_FRAME;
  48. data += LPC10_SAMPLES_PER_FRAME;
  49. }
  50. return (p - out);
  51. }
  52. int Lpc10Codec::decode(const char *in, char *out, int n)
  53. {
  54. float speech[LPC10_SAMPLES_PER_FRAME];
  55. INT32 bits[LPC10_BITS_IN_COMPRESSED_FRAME];
  56. short *data = (short *) out;
  57. n /= LPC10_BYTES_IN_COMPRESSED_FRAME;
  58. while (n-- > 0) {
  59. for (int i = 0; i < LPC10_BITS_IN_COMPRESSED_FRAME; ++i)
  60. bits[i] = !!(in[i >> 3] & (1 << (i & 7)));
  61. lpc10_decode(bits, speech, decodeState);
  62. for (i = 0; i < LPC10_SAMPLES_PER_FRAME; ++i)
  63. *data++ = (short) (speech[i] * 32768);
  64. in += LPC10_BYTES_IN_COMPRESSED_FRAME;
  65. }
  66. return ((char *) data - out);
  67. }