fifo.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include "fifo.h"
  2. #include <malloc.h>
  3. #include <memory.h>
  4. int pcm_fifo_init(PCMFifoBuffer *f, int size)
  5. {
  6. f->wptr = f->rptr = f->buffer = (unsigned char*)malloc(size);
  7. f->end = f->buffer + size;
  8. if (!f->buffer)
  9. return -1;
  10. return 0;
  11. }
  12. void pcm_fifo_free(PCMFifoBuffer *f)
  13. {
  14. free(f->buffer);
  15. }
  16. int pcm_fifo_size(PCMFifoBuffer *f)
  17. {
  18. int size = f->wptr - f->rptr;
  19. if (size < 0)
  20. size += f->end - f->buffer;
  21. return size;
  22. }
  23. int pcm_fifo_read(PCMFifoBuffer *f, unsigned char *buf, int buf_size)
  24. {
  25. return pcm_fifo_generic_read(f, buf_size, 0, buf);
  26. }
  27. void pcm_fifo_realloc(PCMFifoBuffer *f, unsigned int new_size)
  28. {
  29. unsigned int old_size= f->end - f->buffer;
  30. if(old_size < new_size){
  31. int len= pcm_fifo_size(f);
  32. PCMFifoBuffer f2;
  33. pcm_fifo_init(&f2, new_size);
  34. pcm_fifo_read(f, f2.buffer, len);
  35. f2.wptr += len;
  36. free(f->buffer);
  37. *f= f2;
  38. }
  39. }
  40. void pcm_fifo_write(PCMFifoBuffer *f, const unsigned char *buf, int size)
  41. {
  42. do {
  43. int len = PCMMIN(f->end - f->wptr, size);
  44. memcpy(f->wptr, buf, len);
  45. f->wptr += len;
  46. if (f->wptr >= f->end)
  47. f->wptr = f->buffer;
  48. buf += len;
  49. size -= len;
  50. } while (size > 0);
  51. }
  52. int pcm_fifo_generic_read(PCMFifoBuffer *f, int buf_size, void (*func)(void*, void*, int), void* dest)
  53. {
  54. int size = pcm_fifo_size(f);
  55. if (size < buf_size)
  56. return -1;
  57. do {
  58. int len = PCMMIN(f->end - f->rptr, buf_size);
  59. if(func) func(dest, f->rptr, len);
  60. else{
  61. memcpy(dest, f->rptr, len);
  62. dest = (unsigned char*)dest + len;
  63. }
  64. pcm_fifo_drain(f, len);
  65. buf_size -= len;
  66. } while (buf_size > 0);
  67. return 0;
  68. }
  69. void pcm_fifo_drain(PCMFifoBuffer *f, int size)
  70. {
  71. f->rptr += size;
  72. if (f->rptr >= f->end)
  73. f->rptr -= f->end - f->buffer;
  74. }