Search code examples
android-ndkmp3decodelame

Using Lame function hip_decode in Android NDK to decode mp3 return 0


I am using Lame's mpglib to decode mp3 to PCM in Android NDK for playing. But when I called hip_decode(), it returen 0 meaning that "need more data before we can complete the decode". I had no idea how to solve it. Can someone helps me? Here is my code:

void CBufferWrapper::ConvertMp3toPCM (AAssetManager* mgr, const char *filename){

    Print ("ConvertMp3toPCM:file:%s", filename);
    AAsset* asset = AAssetManager_open (mgr, filename, AASSET_MODE_UNKNOWN);
    // the asset might not be found
    assert (asset != NULL);

    // open asset as file descriptor
    off_t start, length;
    int fd = AAsset_openFileDescriptor (asset, &start, &length);
    assert (0 <= fd);
    long size = AAsset_getLength (asset);
    char* buffer = (char*)malloc (sizeof(char)*size);
    memset (buffer, 0, size*sizeof(char));
    AAsset_read (asset, buffer, size);
    AAsset_close (asset);

    hip_t ht = hip_decode_init ();
    int count = hip_decode (ht, (unsigned char*)buffer, size, pcm_l, pcm_r);
    free (buffer);
    Print ("ConvertMp3toPCM: length:%ld,pcmcount=%d",length, count);
}

I used MACRO "HAVE_MPGLIB" to compile Lame in NDK. So I think it should work for decoding literally.


Solution

  • Yesterday I had the same problem. Is the same problem but using lame_enc.dll. I did not know how to resolve this 0 returned, this is the reason to this post.

    1. Create a buffer to put mp3 data: unsigned char mp3Data[4096]

    2. Create two buffers for pcm data, but bigger than mp3 one: unsigned short[4096 * 100];

    3. Open mp3 file and initialize hip.

    4. Now, enter in a do while loop until read bytes are 0 (the end of file).

    5. Inside the loop read 4096 bytes into mp3Data and call hip_decode with hip_decode(ht, mp3Data, bytesRead, lpcm, rpcm);

    6. You are right, it returns 0. It is asking you for more data.

    7. You need to repeat the reading of 4096 bytes and the call to hip_decode until it returns a valid samples number.

    Here is the important part of my program:

    int total = 0;
        int hecho = 0;
        int leido = 0;
        int lon = 0;
        int x;
        do
        {
        total = fread(mp3b, 1, MAXIMO, fich);
        leido += total;
        x = hip_decode(hgf, mp3b, total, izquierda, derecha);
        if(x > 0)
        {
            int tamanio;
            int y;
            tamanio = 1.45 * x + 9200;
            unsigned char * bu = (unsigned char *) malloc(tamanio);
            y = lame_encode_buffer(lamglofla, izquierda, derecha, x, bu, tamanio);
            fwrite(bu, 1, y, fichs);
            free(bu);
        }
        }while(total > 0);
    

    My program decodes a mp3 file and encodes the output into another mp3 file.

    I expect that this could be useful.