Git Inbox Mirror of the ffmpeg-devel mailing list - see https://ffmpeg.org/mailman/listinfo/ffmpeg-devel
 help / color / mirror / Atom feed
* [FFmpeg-devel] [PATCH] libavformat/mov.c : Avoid seek request with invalid seek offset ( 9223372036854775799 ) after EOS
@ 2022-04-22  8:37 Malviya, Janpriya
  2022-04-26  3:09 ` Malviya, Janpriya
  2022-04-26  8:28 ` "zhilizhao(赵志立)"
  0 siblings, 2 replies; 5+ messages in thread
From: Malviya, Janpriya @ 2022-04-22  8:37 UTC (permalink / raw)
  To: ffmpeg-devel; +Cc: Banerjee, Debasmit, Patel, Pratik, Van Iderstine, David

[-- Attachment #1: Type: text/plain, Size: 1638 bytes --]

Hello ffmpeg Dev team,  

While integrating FFmpeg for M4A , MP4 stream & facing issue that mov demuxer trying to request seek for invalid seek offset.

Issue details:-
	- Modified doc/examples/demuxing_decoding.c example to support Custom IO call-back because we have our  own mechanism to read data from source
	-  In custom IO seek call back , we do not support “whence” values AVSEEK_SIZE & SEEK_END , used to find stream size ( returning -1 in both the cases ).
	- In attached screen shot , where we are observing seek with invalid seek offset and the seek requested after End of stream is detected
	- Seek offset value 9223372036854775799 always the same ( I think INT64_MAX – 8 ,  8 is length Atom type & size field )
	- If we allow to return proper stream size in seek callback then this problem is not observed.

Fix :
In attached patch to verify EOS condition before going to parse atom data.

Signed-off-by: Janpriya Malviya <Janpriya_Malviya@bose.com>
---
 libavformat/mov.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/libavformat/mov.c b/libavformat/mov.c
index 6c847de..9704550 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -7556,6 +7556,10 @@ static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
         if (atom.size >= 8) {
             a.size = avio_rb32(pb);
             a.type = avio_rl32(pb);
+
+            if(avio_feof(pb))
+                continue;
+
             if (((a.type == MKTAG('f','r','e','e') && c->moov_retry) ||
                   a.type == MKTAG('h','o','o','v')) &&
                 a.size >= 8 &&
-- 
2.7.4


[-- Attachment #2: issueImage.png --]
[-- Type: image/png, Size: 191430 bytes --]

[-- Attachment #3: reproduce_issue.c --]
[-- Type: text/plain, Size: 13306 bytes --]

/*
 * Copyright (c) 2012 Stefano Sabatini
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * @file
 * Demuxing and decoding example.
 *
 * Show how to use the libavformat and libavcodec API to demux and
 * decode audio and video data.
 * @example demuxing_decoding.c
 */
//#include <libavutil/imgutils.h>
#include <libavutil/samplefmt.h>
#include <libavutil/timestamp.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>

#include <sys/stat.h>
#include <fcntl.h>

#define IO_BUF_SIZE ( 1024 * 2 )
#define SUPPORT_STREAM_SIZE 0
struct customIO
{
  int file_fd;
  char* name;
};

static AVFormatContext *fmt_ctx = NULL;
static AVCodecContext  *audio_dec_ctx = NULL;
static AVStream *audio_stream = NULL;
static const char *src_filename = NULL;
static const char *audio_dst_filename = NULL;
static FILE *audio_dst_file = NULL;

static int  audio_stream_idx = -1;
static AVFrame *frame = NULL;
static AVPacket *pkt = NULL;
static int audio_frame_count = 0;
static struct customIO input_file_io;


static int read_packet( void *opaque, uint8_t *buf, int buf_size )
{
    struct customIO* in_file = ( struct customIO* )( opaque );
    int length = 0;
  
    //printf( "read_packet : size %d \n", buf_size );
	if( !in_file || ( in_file->file_fd < 0 ) ) {
		printf("read_packet  : invalid fd  or opaque ptr \n " );
            return -1;
        }
        
   errno = 0;
   length = read( in_file->file_fd , &buf[0], buf_size );
   if( length == 0 ) {
      printf( "EOS stream found \n" );
      length = AVERROR_EOF;
   }
   
 return length;
}

static int64_t read_seek( void *opaque, int64_t offset, int whence )
{
    struct customIO* in_file = ( struct customIO* )( opaque );
    off_t  seek_ret = -1;

   if( !in_file || ( in_file->file_fd < 0 ) )
   {
		printf("read_packet  : invalid fd  or opaque ptr \n " );
		return -1;
   }

	printf( "ENTER : offset %" PRId64 " whence %d \n", offset, whence );
	//==============
    // Special case for FFMPGE get stream size but we not supported this
    //==============
    if( whence == AVSEEK_SIZE )
    {	
        #if SUPPORT_STREAM_SIZE
            struct stat st;
            seek_ret = fstat(in_file->file_fd, &st);
            return seek_ret < 0 ? AVERROR(errno) : (S_ISFIFO(st.st_mode) ? 0 : st.st_size);
        #else
            //we not supporting stream size
            return -1;//return in->totalsize;
        #endif 
    }

   //==============
   // Special case for us not supported this
   //==============
   if( whence == SEEK_END )
   {
       return -1;
   }
//	printf( "ENTER : offset %" PRId64 " whence %d \n", offset, whence );
	
   errno = 0;
   seek_ret = lseek( in_file->file_fd , offset, whence );

	if( seek_ret < 0 )
    {
		printf( "Seek Failed at SeekOffset ret: %d errono:%d  offset: %lld \n",seek_ret, errno , offset );// %ll  ret:  %ll  whence: %d errno: %d \n", offset, seek_ret, whence, errono );
	}
    return seek_ret;
}

static int output_audio_frame(AVFrame *frame)
{
    size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
    //printf("audio_frame n:%d nb_samples:%d pts:%s\n",
    //       audio_frame_count++, frame->nb_samples,
    //       av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));

    /* Write the raw audio data samples of the first plane. This works
     * fine for packed formats (e.g. AV_SAMPLE_FMT_S16). However,
     * most audio decoders output planar audio, which uses a separate
     * plane of audio samples for each channel (e.g. AV_SAMPLE_FMT_S16P).
     * In other words, this code will write only the first audio channel
     * in these cases.
     * You should use libswresample or libavfilter to convert the frame
     * to packed data. */
    fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file);

    return 0;
}

static int decode_packet(AVCodecContext *dec, const AVPacket *pkt)
{
    int ret = 0;

    // submit the packet to the decoder
    ret = avcodec_send_packet(dec, pkt);
    if (ret < 0) {
        fprintf(stderr, "Error submitting a packet for decoding (%s)\n", av_err2str(ret));
        return ret;
    }

    // get all the available frames from the decoder
    while (ret >= 0) {
        ret = avcodec_receive_frame(dec, frame);
        if (ret < 0) {
            // those two return values are special and mean there is no output
            // frame available, but there were no errors during decoding
            if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
                return 0;

            fprintf(stderr, "Error during decoding (%s)\n", av_err2str(ret));
            return ret;
        }

        // write the frame data to output file
        ret = output_audio_frame(frame);

        av_frame_unref(frame);
        if (ret < 0)
            return ret;
    }

    return 0;
}

static int open_codec_context(int *stream_idx,
                              AVCodecContext **dec_ctx, AVFormatContext *fmt_ctx, enum AVMediaType type)
{
    int ret, stream_index;
    AVStream *st;
    const AVCodec *dec = NULL;

    ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
    if (ret < 0) {
        fprintf(stderr, "Could not find %s stream in input file '%s'\n",
                av_get_media_type_string(type), src_filename);
        return ret;
    } else {
        stream_index = ret;
        st = fmt_ctx->streams[stream_index];

        /* find decoder for the stream */
        dec = avcodec_find_decoder(st->codecpar->codec_id);
        if (!dec) {
            fprintf(stderr, "Failed to find %s codec\n",
                    av_get_media_type_string(type));
            return AVERROR(EINVAL);
        }

        /* Allocate a codec context for the decoder */
        *dec_ctx = avcodec_alloc_context3(dec);
        if (!*dec_ctx) {
            fprintf(stderr, "Failed to allocate the %s codec context\n",
                    av_get_media_type_string(type));
            return AVERROR(ENOMEM);
        }

        /* Copy codec parameters from input stream to output codec context */
        if ((ret = avcodec_parameters_to_context(*dec_ctx, st->codecpar)) < 0) {
            fprintf(stderr, "Failed to copy %s codec parameters to decoder context\n",
                    av_get_media_type_string(type));
            return ret;
        }

        /* Init the decoders */
        if ((ret = avcodec_open2(*dec_ctx, dec, NULL)) < 0) {
            fprintf(stderr, "Failed to open %s codec\n",
                    av_get_media_type_string(type));
            return ret;
        }
        *stream_idx = stream_index;
    }

    return 0;
}


static int open_input_customIo( AVFormatContext *fmt_ctx , struct customIO* io )
{
    AVIOContext *avio_ctx = NULL;
    size_t avio_ctx_buffer_size = IO_BUF_SIZE;

    uint8_t* avio_ctx_buffer = ( uint8_t* )av_malloc( avio_ctx_buffer_size );
    if( !avio_ctx_buffer )
    {
        return AVERROR( ENOMEM );
    }

   avio_ctx = avio_alloc_context( avio_ctx_buffer, avio_ctx_buffer_size,
                                       0, (void*)(io), &read_packet, NULL, &read_seek );

    if( !avio_ctx )
    {
        return AVERROR( ENOMEM );
    }

    fmt_ctx->pb = avio_ctx;
    fmt_ctx->flags = ( fmt_ctx->flags | AVFMT_FLAG_FAST_SEEK | AVFMT_FLAG_CUSTOM_IO );
    return 0;
}

static int get_format_from_sample_fmt(const char **fmt,
                                      enum AVSampleFormat sample_fmt)
{
    int i;
    struct sample_fmt_entry {
        enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
    } sample_fmt_entries[] = {
        { AV_SAMPLE_FMT_U8,  "u8",    "u8"    },
        { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
        { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
        { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
        { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
    };
    *fmt = NULL;

    for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
        struct sample_fmt_entry *entry = &sample_fmt_entries[i];
        if (sample_fmt == entry->sample_fmt) {
            *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
            return 0;
        }
    }

    fprintf(stderr,
            "sample format %s is not supported as output format\n",
            av_get_sample_fmt_name(sample_fmt));
    return -1;
}

int main (int argc, char **argv)
{
    int ret = 0;

    if (argc != 3) {
        fprintf(stderr, "usage: %s  input_file audio_output_file\n"
                "API example program to show how to read frames from an input file.\n"
                "audio frames to a rawaudio file named audio_output_file.\n",
                argv[0]);
        exit(1);
    }
    
   
	//av_register_all();
    src_filename = argv[1];
    audio_dst_filename = argv[2];
    
	input_file_io.name =  src_filename;
    input_file_io.file_fd = open( input_file_io.name , O_RDONLY );
    if( input_file_io.file_fd < 0 )
    {
		printf(" input file not able to open \n");
		return 0;
	}
	printf(" input_file_io.file_fd %d  \n",input_file_io.file_fd);
    
	/* create input context */
	fmt_ctx = avformat_alloc_context();
	
    //Is FFmpeg parser created ?
    if( fmt_ctx )
    {
		open_input_customIo( fmt_ctx , &input_file_io );
    }
    
    /* open input file, and allocate format context */
    if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
        fprintf(stderr, "avformat_open_input:Could not open source file %s\n", src_filename);
        exit(1);
    }

    /* retrieve stream information */
    if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
        fprintf(stderr, "avformat_find_stream_info:Could not find stream information\n");
        exit(1);
    }

    if (open_codec_context(&audio_stream_idx, &audio_dec_ctx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
        audio_stream = fmt_ctx->streams[audio_stream_idx];
        audio_dst_file = fopen(audio_dst_filename, "wb");
        if (!audio_dst_file) {
            fprintf(stderr, "open_codec_context: Could not open destination file %s\n", audio_dst_filename);
            ret = 1;
            goto end;
        }
    }

    /* dump input information to stderr */
    av_dump_format(fmt_ctx, 0, src_filename, 0);

    if (!audio_stream ) {
        fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
        ret = 1;
        goto end;
    }

    frame = av_frame_alloc();
    if (!frame) {
        fprintf(stderr, "Could not allocate frame\n");
        ret = AVERROR(ENOMEM);
        goto end;
    }

    pkt = av_packet_alloc();
    if (!pkt) {
        fprintf(stderr, "Could not allocate packet\n");
        ret = AVERROR(ENOMEM);
        goto end;
    }

    if (audio_stream)
        printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);

    /* read frames from the file */
    while (av_read_frame(fmt_ctx, pkt) >= 0) {
        // check if the packet belongs to a stream we are interested in, otherwise
        // skip it
		if (pkt->stream_index == audio_stream_idx)
            ret = decode_packet(audio_dec_ctx, pkt);
        av_packet_unref(pkt);
        if (ret < 0)
            break;
    }

    /* flush the decoders */
    if (audio_dec_ctx)
        decode_packet(audio_dec_ctx, NULL);

    printf("Demuxing succeeded.\n");


    if (audio_stream) {
        enum AVSampleFormat sfmt = audio_dec_ctx->sample_fmt;
        int n_channels = audio_dec_ctx->ch_layout.nb_channels;
        const char *fmt;

        if (av_sample_fmt_is_planar(sfmt)) {
            const char *packed = av_get_sample_fmt_name(sfmt);
            printf("Warning: the sample format the decoder produced is planar "
                   "(%s). This example will output the first channel only.\n",
                   packed ? packed : "?");
            sfmt = av_get_packed_sample_fmt(sfmt);
            n_channels = 1;
        }

        if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0)
            goto end;

        printf("Play the output audio file with the command:\n"
               "ffplay -f %s -ac %d -ar %d %s\n",
               fmt, n_channels, audio_dec_ctx->sample_rate,
               audio_dst_filename);
    }

end:
    avcodec_free_context(&audio_dec_ctx);
    avformat_close_input(&fmt_ctx);
    if (audio_dst_file)
        fclose(audio_dst_file);
    av_packet_free(&pkt);
    av_frame_free(&frame);
    return ret < 0;
}

[-- Attachment #4: Type: text/plain, Size: 251 bytes --]

_______________________________________________
ffmpeg-devel mailing list
ffmpeg-devel@ffmpeg.org
https://ffmpeg.org/mailman/listinfo/ffmpeg-devel

To unsubscribe, visit link above, or email
ffmpeg-devel-request@ffmpeg.org with subject "unsubscribe".

^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2022-05-01 17:00 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-04-22  8:37 [FFmpeg-devel] [PATCH] libavformat/mov.c : Avoid seek request with invalid seek offset ( 9223372036854775799 ) after EOS Malviya, Janpriya
2022-04-26  3:09 ` Malviya, Janpriya
2022-04-26  8:28 ` "zhilizhao(赵志立)"
2022-04-28 13:43   ` Malviya, Janpriya
2022-05-01 17:00   ` Malviya, Janpriya

Git Inbox Mirror of the ffmpeg-devel mailing list - see https://ffmpeg.org/mailman/listinfo/ffmpeg-devel

This inbox may be cloned and mirrored by anyone:

	git clone --mirror https://master.gitmailbox.com/ffmpegdev/0 ffmpegdev/git/0.git

	# If you have public-inbox 1.1+ installed, you may
	# initialize and index your mirror using the following commands:
	public-inbox-init -V2 ffmpegdev ffmpegdev/ https://master.gitmailbox.com/ffmpegdev \
		ffmpegdev@gitmailbox.com
	public-inbox-index ffmpegdev

Example config snippet for mirrors.


AGPL code for this site: git clone https://public-inbox.org/public-inbox.git