Search code examples
androidffmpegstorage-access-framework

Passing a native fd int to FFMPEG from openable URI


I am trying to open a file descriptor from a CATEGORY_OPENABLE URI from the Storage Access Framework. I am first trying with a file on the sdcard, which I can already resolve to a file path using the _data column and open (I am trying to get away from doing this, and use the file descriptor instead).

I get the the native int fd like this:

int fd = getContentResolver().openFileDescriptor(data.getData(), "r").detachFd();

Then in C++, I am trying to open it like this, the idea taken from How to properly pass an asset FileDescriptor to FFmpeg using JNI in Android:

pFormatCtx = avformat_alloc_context();
pFormatCtx->iformat = av_find_input_format("mp3");

char path[50];
sprintf(path, "pipe:%d", fd);

int e;
if(e=(avformat_open_input(&pFormatCtx,path,NULL,NULL)!=0)){
    av_strerror(e, path, 50);
    return error;
}

This yields an "Unknown error" from avformat_open_input. The same thing happens if I use the jni method jniGetFDFromFileDescriptor from the above linked on a FileDescriptor object to get the int fd instead. How can I open an openable URI with FFMPEG correctly without using the file path?


Solution

  • My project (FFmpegMediaMetadataRetriever) accomplishes this. See this gist or the full file here.

    Note: make sure you have built FFmpeg with the pipe protocol enabled!

    I used avformat_open_input, dup() the file descriptor and made sure to set the offset via:

     if (state->offset > 0) {
            state->pFormatCtx = avformat_alloc_context();
            state->pFormatCtx->skip_initial_bytes = state->offset;
     }