av_read_frame() in ffmpeg returns -5 while receiving UDP data

I’m working on an app which is using ffmpeg lib. There is a living source keep sending TS stream thru udp. Then I allocated a thread use ffmpeg receive the TS packets. the code for this thread is like:

void* av_source_thread(void *data) {
    char udp_url[50];
    snprintf(udp_url, sizeof(udp_url), "udp://127.0.0.1:12345");
    AVDictionary* options = NULL;
    av_dict_set(&options, "timeout", "500000", 0);  // timeout=0.5s
    av_dict_set(&options, "overrun_nonfatal", "1", 0);
    av_dict_set(&options, "fifo_size", "278876", 0);  //50MB

    AVFormatContext *ffmpeg_source = avformat_alloc_context();
    while (running) {
        if (avformat_open_input(&ffmpeg_source, udp_url, NULL, &options) != 0) {
            continue;
        } else {
            break;
        }
    }
    // Some code fill codec type and alloc context here

    av_format_inject_global_side_data(ffmpeg_source);
    AVPacket *packet = av_packet_alloc();
    while (running) {
        ret = av_read_frame(ffmpeg_source, packet);
        if (ret < 0) {
            char errbuf[AV_ERROR_MAX_STRING_SIZE];
            av_strerror(ret, errbuf, AV_ERROR_MAX_STRING_SIZE);
            usleep(10000);
            log("av_read_frame failed, Exit, %s, %d", errbuf, ret);
            continue;
        }
        putPkt2Q(packet);  
    }
    av_packet_free(&packet);
    avformat_close_input(&ffmpeg_source);
    av_dict_free(&options);
    return nullptr;
}

Then the packets will be sent to Q and other thread will process them. but when I run the program, the av_read_frame will return -5(I/O error) from time to time. and once it returned -5, it can not recover unless I restart this thread.

since this is a real time source, so lost some frames are acceptable, I just want to know how to avoid this kind of issue or how to recover without restart the whole thread. I tried to increase the fifo_size in options, but it does not work.

Leave a Comment