mp3_helix.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * Some mp3 related code for Sega/Mega CD.
  3. * Uses the Helix Fixed-point MP3 decoder
  4. * (C) notaz, 2007-2009
  5. *
  6. * This work is licensed under the terms of MAME license.
  7. * See COPYING file in the top-level directory.
  8. */
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <pico/pico_int.h>
  12. #include <pico/sound/mix.h>
  13. #include "helix/pub/mp3dec.h"
  14. #include "mp3.h"
  15. #include "lprintf.h"
  16. static HMP3Decoder mp3dec;
  17. static unsigned char mp3_input_buffer[2 * 1024];
  18. #ifdef __GP2X__
  19. #define mp3_update mp3_update_local
  20. #define mp3_start_play mp3_start_play_local
  21. #endif
  22. int mp3dec_decode(FILE *f, int *file_pos, int file_len)
  23. {
  24. unsigned char *readPtr;
  25. int bytesLeft;
  26. int offset; // mp3 frame offset from readPtr
  27. int had_err;
  28. int err = 0;
  29. do
  30. {
  31. if (*file_pos >= file_len)
  32. return 1; /* EOF, nothing to do */
  33. fseek(f, *file_pos, SEEK_SET);
  34. bytesLeft = fread(mp3_input_buffer, 1, sizeof(mp3_input_buffer), f);
  35. offset = mp3_find_sync_word(mp3_input_buffer, bytesLeft);
  36. if (offset < 0) {
  37. lprintf("find_sync_word (%i/%i) err %i\n",
  38. *file_pos, file_len, offset);
  39. *file_pos = file_len;
  40. return 1; // EOF
  41. }
  42. readPtr = mp3_input_buffer + offset;
  43. bytesLeft -= offset;
  44. had_err = err;
  45. err = MP3Decode(mp3dec, &readPtr, &bytesLeft, cdda_out_buffer, 0);
  46. if (err) {
  47. if (err == ERR_MP3_MAINDATA_UNDERFLOW && !had_err) {
  48. // just need another frame
  49. *file_pos += readPtr - mp3_input_buffer;
  50. continue;
  51. }
  52. if (err == ERR_MP3_INDATA_UNDERFLOW && !had_err) {
  53. if (offset == 0)
  54. // something's really wrong here, frame had to fit
  55. *file_pos = file_len;
  56. else
  57. *file_pos += offset;
  58. continue;
  59. }
  60. if (-12 <= err && err <= -6) {
  61. // ERR_MP3_INVALID_FRAMEHEADER, ERR_MP3_INVALID_*
  62. // just try to skip the offending frame..
  63. *file_pos += offset + 1;
  64. continue;
  65. }
  66. lprintf("MP3Decode err (%i/%i) %i\n",
  67. *file_pos, file_len, err);
  68. *file_pos = file_len;
  69. return 1;
  70. }
  71. *file_pos += readPtr - mp3_input_buffer;
  72. }
  73. while (0);
  74. return 0;
  75. }
  76. int mp3dec_start(FILE *f, int fpos_start)
  77. {
  78. // must re-init decoder for new track
  79. if (mp3dec)
  80. MP3FreeDecoder(mp3dec);
  81. mp3dec = MP3InitDecoder();
  82. return (mp3dec == 0) ? -1 : 0;
  83. }