There may come a situation in video streaming architectures, where we have process something, according to the condition whether a stream is present or not. This can be quite tricky if video publish stream(say RTMP stream) is up and down frequently.

You can achieve such a trick by using a code like below, and you have to just call checkForStream(your_stream_url). It returns non-zero if stream is currently up.

int checkForStream(char *stream_url) {
    char command[1024];
    sprintf(command, "ffmpeg -i %s >teststream.output 2>&1", stream_url); //use ./ffmpeg or path to ffmpeg as appropriate
    system(command);
    return isFoundInFile("test.out", "At least one output file must be specified"); //Return 1 if stream is active
}

int isFoundInFile(const char *filename, const char *stringToSearch) {
    char * buffer = 0;
    long length;
    FILE * f = fopen (filename, "rb");

    if (f)
    {
        fseek (f, 0, SEEK_END);
        length = ftell (f);
        fseek (f, 0, SEEK_SET);
        buffer = (char*)malloc (length);
        if (buffer)
        {
            fread (buffer, 1, length, f);
        }
        char removeCommand[256];
        system(removeCommand);
        fclose (f);
    }

    if (buffer && strlen(buffer)>0)
    {
        if (strstr(buffer, stringToSearch) != NULL)
            return 1;
    }
    return 0;
}
Advertisements