Git Inbox Mirror of the ffmpeg-devel mailing list - see https://ffmpeg.org/mailman/listinfo/ffmpeg-devel
 help / color / mirror / Atom feed
From: "Malviya, Janpriya" <Janpriya_Malviya@bose.com>
To: "ffmpeg-devel@ffmpeg.org" <ffmpeg-devel@ffmpeg.org>
Cc: "Banerjee, Debasmit" <Debasmit_Banerjee@bose.com>,
	"Patel, Pratik" <Pratik_Patel@bose.com>,
	"Van Iderstine, David" <David_Van_Iderstine@bose.com>
Subject: [FFmpeg-devel] [PATCH] libavformat/mov.c : Fix issue in mov demuxer which trying to request seek with invalid seek offset ( 9223372036854775799 )
Date: Mon, 11 Apr 2022 14:28:48 +0000
Message-ID: <MWHPR08MB26556A742F5B2D64110024F280EA9@MWHPR08MB2655.namprd08.prod.outlook.com> (raw)


[-- Attachment #1.1: Type: text/plain, Size: 1118 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.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.
  *   In Screen shot below , 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.
[cid:image003.png@01D84DDE.8B612E70]

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

we are using FFmpeg tag n4.3.1 . Please take a look & provide your feedback . All regeneration test with https://samples.ffmpeg.org/ samples get passed on this patch.

Regards
Janpriya.

[-- Attachment #1.2: 208A8FD9FB85445CA4F048EC78B5834A.png --]
[-- Type: image/png, Size: 234068 bytes --]

[-- Attachment #2: 0001-Avoid-seek-request-with-invalid-seek-offset-92233720.patch --]
[-- Type: application/octet-stream, Size: 952 bytes --]

[-- Attachment #3: reproduce_Issue.c.c --]
[-- Type: text/plain, Size: 12638 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
 * libavformat demuxing API use example.
 *
 * Show how to use the libavformat and libavcodec API to demux and
 * decode audio and video data.
 * @example doc/examples/demuxing.c
 */
#include <libavutil/imgutils.h>
#include <libavutil/samplefmt.h>
#include <libavutil/timestamp.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 audio_stream_idx = -1;
static AVFrame *frame = NULL;
static AVPacket pkt;
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;
   }

	//==============
    // 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 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 decode_packet(int *got_frame, int cached)
{
    int ret = 0;
    int decoded = pkt.size;
	
	if (pkt.stream_index == audio_stream_idx) 
	{
        /* decode audio frame */
        ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt);
        if (ret < 0) {
            fprintf(stderr, "Error decoding audio frame\n");
            return ret;
        }
        /* Some audio decoders decode only part of the packet, and have to be
         * called again with the remainder of the packet data.
         * Sample: fate-suite/lossless-audio/luckynight-partial.shn
         * Also, some decoders might over-read the packet. */
        decoded = FFMIN(ret, pkt.size);
        if (*got_frame) 
        {	
			
            size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
            
            
            if( ( audio_frame_count % 100 ) == 0 )
            {
				printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
					   cached ? "(cached)" : "",
					   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);
            audio_frame_count++;
        }
    }
    return decoded;
}
static int open_codec_context(int *stream_idx,
                              AVFormatContext *fmt_ctx, enum AVMediaType type)
{
    int ret;
    AVStream *st;
    AVCodecContext *dec_ctx = NULL;
    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_idx = ret;
        st = fmt_ctx->streams[*stream_idx];
        /* find decoder for the stream */
        dec_ctx = st->codec;
        dec = avcodec_find_decoder(dec_ctx->codec_id);
        if (!dec) {
            fprintf(stderr, "Failed to find %s codec\n",
                    av_get_media_type_string(type));
            return ret;
        }
        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;
        }
    }
    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, got_frame;
    
   AVDictionary* options = NULL;

    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"
                "This program reads frames from a file, decodes them, and writes decoded\n"
                "audio frames to a rawaudio file named audio_output_file.\n"
                "\n", argv[0]);
        exit(1);
    }
    
   
    
    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 );
        
        //Set Probe Size
        fmt_ctx->format_probesize = fmt_ctx->probesize =  2048;
    }

    /* open input file, and allocate format context */
    if (avformat_open_input(&fmt_ctx, src_filename, NULL, &options) < 0) {
        fprintf(stderr, "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, "Could not find stream information\n");
        exit(1);
    }
    

    if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) 
    {
        audio_stream = fmt_ctx->streams[audio_stream_idx];
        audio_dec_ctx = audio_stream->codec;
        audio_dst_file = fopen(audio_dst_filename, "wb");
        if (!audio_dst_file) {
            fprintf(stderr, "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;
    }
    /* initialize packet, set data to NULL, let the demuxer fill it */
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;
    
    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) 
    {
        AVPacket orig_pkt = pkt;
        do {
            ret = decode_packet(&got_frame, 0);
            if (ret < 0)
                break;
            pkt.data += ret;
            pkt.size -= ret;
        } while (pkt.size > 0);
        av_free_packet(&orig_pkt);
    }
    
    
    /* flush cached frames */
    pkt.data = NULL;
    pkt.size = 0;
    do 
    {
        decode_packet(&got_frame, 1);
    } while (got_frame);
    printf("Demuxing succeeded.\n");
    
    if (audio_stream) {
        enum AVSampleFormat sfmt = audio_dec_ctx->sample_fmt;
        int n_channels = audio_dec_ctx->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:
    if (audio_dec_ctx)
        avcodec_close(audio_dec_ctx);
    avformat_close_input(&fmt_ctx);
    if (audio_dst_file)
        fclose(audio_dst_file);
    av_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".

                 reply	other threads:[~2022-04-11 14:29 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=MWHPR08MB26556A742F5B2D64110024F280EA9@MWHPR08MB2655.namprd08.prod.outlook.com \
    --to=janpriya_malviya@bose.com \
    --cc=David_Van_Iderstine@bose.com \
    --cc=Debasmit_Banerjee@bose.com \
    --cc=Pratik_Patel@bose.com \
    --cc=ffmpeg-devel@ffmpeg.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link

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