Skip to content

Instantly share code, notes, and snippets.

@alenstarx
Created February 24, 2016 12:22
Show Gist options
  • Save alenstarx/3507f97cc90479c07c45 to your computer and use it in GitHub Desktop.
Save alenstarx/3507f97cc90479c07c45 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#ifdef __cplusplus
extern "C"{
#endif
#include <opencore-amrnb/interf_dec.h>
#ifdef __cplusplus
}
#endif
#define ALOGE(...) printf(__VA_ARGS__);printf("\n")
#define AMR_MAGIC_NUMBER "#!AMR\n"
// load_file to memory, free memory by caller
unsigned char *load_file(const char *path, int *data_size)
{
FILE *fd;
struct stat sb;
unsigned char *buffer;
size_t size;
size_t n;
fd = fopen(path, "rb");
if (!fd) {
ALOGE("fopen: %s", strerror(errno));
//perror(path);
//exit(EXIT_FAILURE);
return NULL;
}
if (stat(path, &sb)) {
ALOGE("stat: %s", strerror(errno));
//perror(path);
// exit(EXIT_FAILURE);
return NULL;
}
size = sb.st_size;
buffer = (unsigned char*)malloc(size);
if (!buffer) {
ALOGE("Unable to allocate %lld bytes\n",
(long long)size);
//exit(EXIT_FAILURE);
return NULL;
}
n = fread(buffer, 1, size, fd);
if (n != size) {
ALOGE("fread: %s", strerror(errno));
//exit(EXIT_FAILURE);
free(buffer);
return NULL;
}
fclose(fd);
*data_size = size;
return buffer;
}
int main(int argc, char** argv)
{
if (argc != 2){
printf("usage: %s file.mp3\n", argv[0]);
return 0;
}
int file_length = 0;
char* file_buf = (char*)load_file(argv[1], &file_length);
if (! file_buf){
ALOGE("load_file %s error", argv[1]);
return 0;
} else {
if (strncmp(file_buf, AMR_MAGIC_NUMBER,
strlen(AMR_MAGIC_NUMBER) ) ) {
ALOGE("Invalid magic number: %s", argv[1]);
free(file_buf);
return 0;
}
}
int amrnb_len = file_length - strlen(AMR_MAGIC_NUMBER);
char* amrnb_buf = file_buf + strlen(AMR_MAGIC_NUMBER);
void* amr = NULL;
short block_size[16]={ 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0 };
ALOGE("AMR-NB Data lengeth: %d", amrnb_len);
/* init decoder */
amr = Decoder_Interface_init();
if(!amr){
ALOGE("Decoder_Interface_init");
free(file_buf);
return 0;
}
int16_t outbuffer[160];
uint8_t buffer[32];
int size = 0, j = 0;
for(j = 0; j < amrnb_len; j++){
/* Find the packet size */
ALOGE("find the packet size : %d", (amrnb_buf[j] >> 3) & 0x0f);
size = block_size[(amrnb_buf[j] >> 3) & 0x0f];
memcpy(buffer, amrnb_buf + j, size + 1);
j += size;
ALOGE("packet size: %d", size);
/* Decode the packet */
Decoder_Interface_Decode(amr, buffer, outbuffer, 0);
/* Convert to little endian and write to wav */
// TODO save littleendian (size:320) to pcm
}
Decoder_Interface_exit(amr);
ALOGE("AMR-NB Data Decode finished");
free(file_buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment