alac_magic_cookie.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "alac_magic_cookie.h"
  2. #include <string.h>
  3. // Build ALAC magic cookie (ALACSpecificConfig) from format parameters.
  4. void build_alac_magic_cookie(uint8_t *cookie, const audio_format_t *fmt) {
  5. memset(cookie, 0, ALAC_MAGIC_COOKIE_SIZE);
  6. uint32_t frame_length =
  7. fmt->max_samples_per_frame
  8. ? fmt->max_samples_per_frame
  9. : (fmt->frame_size > 0 ? (uint32_t)fmt->frame_size : 352);
  10. uint8_t compatible_version = 0;
  11. uint8_t bit_depth = fmt->sample_size
  12. ? fmt->sample_size
  13. : (fmt->bits_per_sample ? fmt->bits_per_sample : 16);
  14. uint8_t pb = fmt->rice_history_mult ? fmt->rice_history_mult : 40;
  15. uint8_t mb = fmt->rice_initial_history ? fmt->rice_initial_history : 10;
  16. uint8_t kb = fmt->rice_limit ? fmt->rice_limit : 14;
  17. uint8_t num_channels = fmt->num_channels
  18. ? fmt->num_channels
  19. : (fmt->channels ? fmt->channels : 2);
  20. uint16_t max_run = fmt->max_run ? fmt->max_run : 255;
  21. uint32_t max_frame_bytes =
  22. fmt->max_coded_frame_size ? fmt->max_coded_frame_size : 0;
  23. uint32_t avg_bit_rate = fmt->avg_bit_rate ? fmt->avg_bit_rate : 0;
  24. uint32_t sample_rate = fmt->sample_rate_config
  25. ? fmt->sample_rate_config
  26. : (fmt->sample_rate ? fmt->sample_rate : 44100);
  27. // ALACSpecificConfig structure (big-endian).
  28. cookie[0] = (frame_length >> 24) & 0xFF;
  29. cookie[1] = (frame_length >> 16) & 0xFF;
  30. cookie[2] = (frame_length >> 8) & 0xFF;
  31. cookie[3] = frame_length & 0xFF;
  32. cookie[4] = compatible_version;
  33. cookie[5] = bit_depth;
  34. cookie[6] = pb;
  35. cookie[7] = mb;
  36. cookie[8] = kb;
  37. cookie[9] = num_channels;
  38. cookie[10] = (max_run >> 8) & 0xFF;
  39. cookie[11] = max_run & 0xFF;
  40. cookie[12] = (max_frame_bytes >> 24) & 0xFF;
  41. cookie[13] = (max_frame_bytes >> 16) & 0xFF;
  42. cookie[14] = (max_frame_bytes >> 8) & 0xFF;
  43. cookie[15] = max_frame_bytes & 0xFF;
  44. cookie[16] = (avg_bit_rate >> 24) & 0xFF;
  45. cookie[17] = (avg_bit_rate >> 16) & 0xFF;
  46. cookie[18] = (avg_bit_rate >> 8) & 0xFF;
  47. cookie[19] = avg_bit_rate & 0xFF;
  48. cookie[20] = (sample_rate >> 24) & 0xFF;
  49. cookie[21] = (sample_rate >> 16) & 0xFF;
  50. cookie[22] = (sample_rate >> 8) & 0xFF;
  51. cookie[23] = sample_rate & 0xFF;
  52. }