Skip to content
Snippets Groups Projects
ffplay.c 99 KiB
Newer Older
  • Learn to ignore specific revisions
  •                 avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
    
                    if (fabs(avg_diff) >= is->audio_diff_threshold) {
    
                        wanted_size = samples_size + ((int)(diff * is->audio_st->codec->sample_rate) * n);
    
                        min_size = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
                        max_size = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX)) / 100) * n;
                        if (wanted_size < min_size)
                            wanted_size = min_size;
                        else if (wanted_size > max_size)
                            wanted_size = max_size;
    
                        /* add or remove samples to correction the synchro */
                        if (wanted_size < samples_size) {
                            /* remove samples */
                            samples_size = wanted_size;
                        } else if (wanted_size > samples_size) {
                            uint8_t *samples_end, *q;
                            int nb;
    
                            /* add samples */
                            nb = (samples_size - wanted_size);
                            samples_end = (uint8_t *)samples + samples_size - n;
                            q = samples_end + n;
                            while (nb > 0) {
                                memcpy(q, samples_end, n);
                                q += n;
                                nb -= n;
                            }
                            samples_size = wanted_size;
                        }
                    }
    #if 0
    
                    printf("diff=%f adiff=%f sample_diff=%d apts=%0.3f vpts=%0.3f %f\n",
                           diff, avg_diff, samples_size - samples_size1,
    
                           is->audio_clock, is->video_clock, is->audio_diff_threshold);
    #endif
    
            } else {
                /* too big difference : may be initial PTS errors, so
                   reset A-V filter */
                is->audio_diff_avg_count = 0;
                is->audio_diff_cum = 0;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            }
        }
    
        return samples_size;
    }
    
    /* decode one audio frame and returns its uncompressed size */
    
    static int audio_decode_frame(VideoState *is, double *pts_ptr)
    
        AVPacket *pkt_temp = &is->audio_pkt_temp;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        AVPacket *pkt = &is->audio_pkt;
    
        AVCodecContext *dec= is->audio_st->codec;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        int n, len1, data_size;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        double pts;
    
        for(;;) {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            /* NOTE: the audio packet can contain several frames */
    
            while (pkt_temp->size > 0) {
    
                data_size = sizeof(is->audio_buf1);
    
                len1 = avcodec_decode_audio3(dec,
    
                                            (int16_t *)is->audio_buf1, &data_size,
    
                                            pkt_temp);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                if (len1 < 0) {
                    /* if error, we skip the frame */
    
                    pkt_temp->size = 0;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                    break;
    
                pkt_temp->data += len1;
                pkt_temp->size -= len1;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                if (data_size <= 0)
                    continue;
    
    
                if (dec->sample_fmt != is->audio_src_fmt) {
                    if (is->reformat_ctx)
                        av_audio_convert_free(is->reformat_ctx);
                    is->reformat_ctx= av_audio_convert_alloc(SAMPLE_FMT_S16, 1,
                                                             dec->sample_fmt, 1, NULL, 0);
                    if (!is->reformat_ctx) {
                        fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
                            avcodec_get_sample_fmt_name(dec->sample_fmt),
                            avcodec_get_sample_fmt_name(SAMPLE_FMT_S16));
                            break;
                    }
                    is->audio_src_fmt= dec->sample_fmt;
                }
    
                if (is->reformat_ctx) {
                    const void *ibuf[6]= {is->audio_buf1};
                    void *obuf[6]= {is->audio_buf2};
                    int istride[6]= {av_get_bits_per_sample_format(dec->sample_fmt)/8};
                    int ostride[6]= {2};
                    int len= data_size/istride[0];
                    if (av_audio_convert(is->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
                        printf("av_audio_convert() failed\n");
                        break;
                    }
                    is->audio_buf= is->audio_buf2;
                    /* FIXME: existing code assume that data_size equals framesize*channels*2
                              remove this legacy cruft */
                    data_size= len*2;
                }else{
                    is->audio_buf= is->audio_buf1;
                }
    
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                /* if no pts, then compute it */
                pts = is->audio_clock;
                *pts_ptr = pts;
    
                is->audio_clock += (double)data_size /
    
                    (double)(n * dec->sample_rate);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                {
                    static double last_clock;
                    printf("audio: delay=%0.3f clock=%0.3f pts=%0.3f\n",
                           is->audio_clock - last_clock,
                           is->audio_clock, pts);
                    last_clock = is->audio_clock;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    #endif
                return data_size;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            /* free the current packet */
            if (pkt->data)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                av_free_packet(pkt);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            if (is->paused || is->audioq.abort_request) {
                return -1;
            }
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            /* read next packet */
            if (packet_queue_get(&is->audioq, pkt, 1) < 0)
                return -1;
    
            if(pkt->data == flush_pkt.data){
    
            pkt_temp->data = pkt->data;
            pkt_temp->size = pkt->size;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            /* if update the audio clock with the pts */
            if (pkt->pts != AV_NOPTS_VALUE) {
    
                is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts;
    
    /* get the current audio output buffer size, in samples. With SDL, we
       cannot have a precise information */
    static int audio_write_get_buf_size(VideoState *is)
    
        return is->audio_buf_size - is->audio_buf_index;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    }
    
    
    /* prepare a new audio buffer */
    
    static void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        VideoState *is = opaque;
        int audio_size, len1;
        double pts;
    
        audio_callback_time = av_gettime();
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        while (len > 0) {
            if (is->audio_buf_index >= is->audio_buf_size) {
    
               audio_size = audio_decode_frame(is, &pts);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
               if (audio_size < 0) {
                    /* if error, just output silence */
    
                   is->audio_buf = is->audio_buf1;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                   is->audio_buf_size = 1024;
                   memset(is->audio_buf, 0, is->audio_buf_size);
               } else {
                   if (is->show_audio)
                       update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
    
                   audio_size = synchronize_audio(is, (int16_t *)is->audio_buf, audio_size,
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                                                  pts);
                   is->audio_buf_size = audio_size;
               }
               is->audio_buf_index = 0;
            }
            len1 = is->audio_buf_size - is->audio_buf_index;
            if (len1 > len)
                len1 = len;
            memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
            len -= len1;
            stream += len1;
            is->audio_buf_index += len1;
        }
    }
    
    /* open a given stream. Return 0 if OK */
    static int stream_component_open(VideoState *is, int stream_index)
    {
        AVFormatContext *ic = is->ic;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        AVCodec *codec;
        SDL_AudioSpec wanted_spec, spec;
    
        if (stream_index < 0 || stream_index >= ic->nb_streams)
            return -1;
    
        avctx = ic->streams[stream_index]->codec;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        /* prepare audio output */
    
        if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
    
            if (avctx->channels > 0) {
                avctx->request_channels = FFMIN(2, avctx->channels);
    
        codec = avcodec_find_decoder(avctx->codec_id);
        avctx->debug_mv = debug_mv;
        avctx->debug = debug;
        avctx->workaround_bugs = workaround_bugs;
        avctx->lowres = lowres;
        if(lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
        avctx->idct_algo= idct;
        if(fast) avctx->flags2 |= CODEC_FLAG2_FAST;
        avctx->skip_frame= skip_frame;
        avctx->skip_idct= skip_idct;
        avctx->skip_loop_filter= skip_loop_filter;
        avctx->error_recognition= error_recognition;
        avctx->error_concealment= error_concealment;
        avcodec_thread_init(avctx, thread_count);
    
        set_context_opts(avctx, avcodec_opts[avctx->codec_type], 0);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        if (!codec ||
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            return -1;
    
        if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
    
            wanted_spec.freq = avctx->sample_rate;
    
            wanted_spec.format = AUDIO_S16SYS;
    
            wanted_spec.channels = avctx->channels;
    
            wanted_spec.silence = 0;
            wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
            wanted_spec.callback = sdl_audio_callback;
            wanted_spec.userdata = is;
            if (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
                fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
                return -1;
            }
            is->audio_hw_buf_size = spec.size;
    
            is->audio_src_fmt= SAMPLE_FMT_S16;
    
        ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            is->audio_stream = stream_index;
            is->audio_st = ic->streams[stream_index];
            is->audio_buf_size = 0;
            is->audio_buf_index = 0;
    
    
            /* init averaging filter */
            is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
            is->audio_diff_avg_count = 0;
            /* since we do not have a precise anough audio fifo fullness,
               we correct audio sync only if larger than this threshold */
    
            is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / avctx->sample_rate;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
            packet_queue_init(&is->audioq);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            break;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            is->video_stream = stream_index;
            is->video_st = ic->streams[stream_index];
    
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            packet_queue_init(&is->videoq);
            is->video_tid = SDL_CreateThread(video_thread, is);
            break;
    
            is->subtitle_stream = stream_index;
            is->subtitle_st = ic->streams[stream_index];
            packet_queue_init(&is->subtitleq);
    
            is->subtitle_tid = SDL_CreateThread(subtitle_thread, is);
            break;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        default:
            break;
        }
        return 0;
    }
    
    static void stream_component_close(VideoState *is, int stream_index)
    {
        AVFormatContext *ic = is->ic;
    
        if (stream_index < 0 || stream_index >= ic->nb_streams)
            return;
    
        avctx = ic->streams[stream_index]->codec;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            packet_queue_abort(&is->audioq);
    
            SDL_CloseAudio();
    
            packet_queue_end(&is->audioq);
    
            if (is->reformat_ctx)
                av_audio_convert_free(is->reformat_ctx);
    
            is->reformat_ctx = NULL;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            break;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            packet_queue_abort(&is->videoq);
    
            /* note: we also signal this mutex to make sure we deblock the
               video thread in all cases */
            SDL_LockMutex(is->pictq_mutex);
            SDL_CondSignal(is->pictq_cond);
            SDL_UnlockMutex(is->pictq_mutex);
    
            SDL_WaitThread(is->video_tid, NULL);
    
            packet_queue_end(&is->videoq);
            break;
    
            packet_queue_abort(&is->subtitleq);
    
            /* note: we also signal this mutex to make sure we deblock the
               video thread in all cases */
            SDL_LockMutex(is->subpq_mutex);
            is->subtitle_stream_changed = 1;
    
            SDL_CondSignal(is->subpq_cond);
            SDL_UnlockMutex(is->subpq_mutex);
    
            SDL_WaitThread(is->subtitle_tid, NULL);
    
            packet_queue_end(&is->subtitleq);
            break;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        default:
            break;
        }
    
    
        ic->streams[stream_index]->discard = AVDISCARD_ALL;
    
        avcodec_close(avctx);
        switch(avctx->codec_type) {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            is->audio_st = NULL;
            is->audio_stream = -1;
            break;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            is->video_st = NULL;
            is->video_stream = -1;
            break;
    
            is->subtitle_st = NULL;
            is->subtitle_stream = -1;
            break;
    
    /* since we have only one decoding thread, we can use a global
       variable instead of a thread local variable */
    static VideoState *global_video_state;
    
    static int decode_interrupt_cb(void)
    {
        return (global_video_state && global_video_state->abort_request);
    }
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
    /* this thread gets the stream from the disk or the network */
    static int decode_thread(void *arg)
    {
        VideoState *is = arg;
        AVFormatContext *ic;
    
        int st_index[AVMEDIA_TYPE_NB];
        int st_count[AVMEDIA_TYPE_NB]={0};
        int st_best_packet_count[AVMEDIA_TYPE_NB];
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        AVPacket pkt1, *pkt = &pkt1;
    
    Robert Krüger's avatar
    Robert Krüger committed
        int pkt_in_play_range = 0;
    
        ic = avformat_alloc_context();
    
    
        memset(st_index, -1, sizeof(st_index));
    
        memset(st_best_packet_count, -1, sizeof(st_best_packet_count));
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        is->video_stream = -1;
        is->audio_stream = -1;
    
        global_video_state = is;
        url_set_interrupt_cb(decode_interrupt_cb);
    
    
        ap->prealloced_context = 1;
    
        ap->width = frame_width;
        ap->height= frame_height;
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
        ap->time_base= (AVRational){1, 25};
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
    
    
        set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM);
    
    
        err = av_open_input_file(&ic, is->filename, is->iformat, 0, ap);
    
        if (err < 0) {
            print_error(is->filename, err);
            ret = -1;
            goto fail;
        }
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        is->ic = ic;
    
    
        if(genpts)
            ic->flags |= AVFMT_FLAG_GENPTS;
    
    
        err = av_find_stream_info(ic);
        if (err < 0) {
            fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
            ret = -1;
            goto fail;
        }
    
        if(ic->pb)
            ic->pb->eof_reached= 0; //FIXME hack, ffplay maybe should not use url_feof() to test for the end
    
        if(seek_by_bytes<0)
            seek_by_bytes= !!(ic->iformat->flags & AVFMT_TS_DISCONT);
    
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        /* if seeking requested, we execute it */
        if (start_time != AV_NOPTS_VALUE) {
            int64_t timestamp;
    
            timestamp = start_time;
            /* add the stream start time */
            if (ic->start_time != AV_NOPTS_VALUE)
                timestamp += ic->start_time;
    
            ret = avformat_seek_file(ic, -1, INT64_MIN, timestamp, INT64_MAX, 0);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            if (ret < 0) {
    
                fprintf(stderr, "%s: could not seek to position %0.3f\n",
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                        is->filename, (double)timestamp / AV_TIME_BASE);
            }
        }
    
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        for(i = 0; i < ic->nb_streams; i++) {
    
            AVStream *st= ic->streams[i];
            AVCodecContext *avctx = st->codec;
    
            if(avctx->codec_type >= (unsigned)AVMEDIA_TYPE_NB)
    
            if(st_count[avctx->codec_type]++ != wanted_stream[avctx->codec_type] && wanted_stream[avctx->codec_type] >= 0)
                continue;
    
    
            if(st_best_packet_count[avctx->codec_type] >= st->codec_info_nb_frames)
                continue;
            st_best_packet_count[avctx->codec_type]= st->codec_info_nb_frames;
    
    
                if (!audio_disable)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                break;
    
            case AVMEDIA_TYPE_VIDEO:
            case AVMEDIA_TYPE_SUBTITLE:
    
                if (!video_disable)
                    st_index[avctx->codec_type] = i;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            default:
                break;
            }
        }
        if (show_status) {
            dump_format(ic, 0, is->filename, 0);
        }
    
        /* open the streams */
    
        if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
            stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
        ret=-1;
    
        if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
            ret= stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
        }
    
        is->refresh_tid = SDL_CreateThread(refresh_thread, is);
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
        if(ret<0) {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            if (!display_disable)
    
        if (st_index[AVMEDIA_TYPE_SUBTITLE] >= 0) {
            stream_component_open(is, st_index[AVMEDIA_TYPE_SUBTITLE]);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        if (is->video_stream < 0 && is->audio_stream < 0) {
    
            fprintf(stderr, "%s: could not open codecs\n", is->filename);
            ret = -1;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            goto fail;
        }
    
        for(;;) {
            if (is->abort_request)
                break;
    
            if (is->paused != is->last_paused) {
                is->last_paused = is->paused;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                if (is->paused)
    
                    is->read_pause_return= av_read_pause(ic);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                else
                    av_read_play(ic);
    
    #if CONFIG_RTSP_DEMUXER
            if (is->paused && !strcmp(ic->iformat->name, "rtsp")) {
    
                /* wait 10 ms to avoid trying to get another packet */
                /* XXX: horrible */
                SDL_Delay(10);
                continue;
            }
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            if (is->seek_req) {
    
                int64_t seek_min= is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;
                int64_t seek_max= is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;
    //FIXME the +-2 is due to rounding being not done in the correct direction in generation
    //      of the seek_pos/seek_rel variables
    
                ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                if (ret < 0) {
                    fprintf(stderr, "%s: error while seeking\n", is->ic->filename);
    
                }else{
                    if (is->audio_stream >= 0) {
                        packet_queue_flush(&is->audioq);
    
                        packet_queue_put(&is->audioq, &flush_pkt);
    
                    if (is->subtitle_stream >= 0) {
                        packet_queue_flush(&is->subtitleq);
    
                        packet_queue_put(&is->subtitleq, &flush_pkt);
    
                    if (is->video_stream >= 0) {
                        packet_queue_flush(&is->videoq);
    
                        packet_queue_put(&is->videoq, &flush_pkt);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                }
                is->seek_req = 0;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            /* if the queue are full, no need to read more */
    
            if (   is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE
                || (   (is->audioq   .size  > MIN_AUDIOQ_SIZE || is->audio_stream<0)
                    && (is->videoq   .nb_packets > MIN_FRAMES || is->video_stream<0)
                    && (is->subtitleq.nb_packets > MIN_FRAMES || is->subtitle_stream<0))) {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                /* wait 10 ms */
                SDL_Delay(10);
                continue;
            }
    
            if(url_feof(ic->pb) || eof) {
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
                    av_init_packet(pkt);
                    pkt->data=NULL;
                    pkt->size=0;
                    pkt->stream_index= is->video_stream;
                    packet_queue_put(&is->videoq, pkt);
    
                SDL_Delay(10);
    
                if(is->audioq.size + is->videoq.size + is->subtitleq.size ==0){
                    if(loop!=1 && (!loop || --loop)){
                        stream_seek(cur_stream, start_time != AV_NOPTS_VALUE ? start_time : 0, 0, 0);
                    }else if(autoexit){
                        ret=AVERROR_EOF;
                        goto fail;
                    }
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
                }
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            ret = av_read_frame(ic, pkt);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            if (ret < 0) {
    
                if (ret == AVERROR_EOF)
                    eof=1;
                if (url_ferror(ic->pb))
    
                SDL_Delay(100); /* wait for user event */
                continue;
    
    Robert Krüger's avatar
    Robert Krüger committed
            /* check if packet is in play range specified by user, then queue, otherwise discard */
            pkt_in_play_range = duration == AV_NOPTS_VALUE ||
                    (pkt->pts - ic->streams[pkt->stream_index]->start_time) *
                    av_q2d(ic->streams[pkt->stream_index]->time_base) -
                    (double)(start_time != AV_NOPTS_VALUE ? start_time : 0)/1000000
                    <= ((double)duration/1000000);
            if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                packet_queue_put(&is->audioq, pkt);
    
    Robert Krüger's avatar
    Robert Krüger committed
            } else if (pkt->stream_index == is->video_stream && pkt_in_play_range) {
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                packet_queue_put(&is->videoq, pkt);
    
    Robert Krüger's avatar
    Robert Krüger committed
            } else if (pkt->stream_index == is->subtitle_stream && pkt_in_play_range) {
    
                packet_queue_put(&is->subtitleq, pkt);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            } else {
                av_free_packet(pkt);
            }
        }
        /* wait until the end */
        while (!is->abort_request) {
            SDL_Delay(100);
        }
    
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
     fail:
    
        /* disable interrupting */
        global_video_state = NULL;
    
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        /* close each stream */
        if (is->audio_stream >= 0)
            stream_component_close(is, is->audio_stream);
        if (is->video_stream >= 0)
            stream_component_close(is, is->video_stream);
    
        if (is->subtitle_stream >= 0)
            stream_component_close(is, is->subtitle_stream);
    
        if (is->ic) {
            av_close_input_file(is->ic);
            is->ic = NULL; /* safety */
        }
    
            event.type = FF_QUIT_EVENT;
            event.user.data1 = is;
            SDL_PushEvent(&event);
        }
    
    static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        VideoState *is;
    
        is = av_mallocz(sizeof(VideoState));
        if (!is)
            return NULL;
    
        av_strlcpy(is->filename, filename, sizeof(is->filename));
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        is->ytop = 0;
        is->xleft = 0;
    
        /* start video display */
        is->pictq_mutex = SDL_CreateMutex();
        is->pictq_cond = SDL_CreateCond();
    
        is->subpq_mutex = SDL_CreateMutex();
        is->subpq_cond = SDL_CreateCond();
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        is->parse_tid = SDL_CreateThread(decode_thread, is);
        if (!is->parse_tid) {
            av_free(is);
            return NULL;
        }
        return is;
    }
    
    static void stream_close(VideoState *is)
    {
        VideoPicture *vp;
        int i;
        /* XXX: use a special url_shutdown call to abort parse cleanly */
        is->abort_request = 1;
        SDL_WaitThread(is->parse_tid, NULL);
    
        SDL_WaitThread(is->refresh_tid, NULL);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
        /* free all pictures */
        for(i=0;i<VIDEO_PICTURE_QUEUE_SIZE; i++) {
            vp = &is->pictq[i];
    
    #if CONFIG_AVFILTER
            if (vp->picref) {
                avfilter_unref_pic(vp->picref);
                vp->picref = NULL;
            }
    #endif
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            if (vp->bmp) {
                SDL_FreeYUVOverlay(vp->bmp);
                vp->bmp = NULL;
            }
        }
        SDL_DestroyMutex(is->pictq_mutex);
        SDL_DestroyCond(is->pictq_cond);
    
        SDL_DestroyMutex(is->subpq_mutex);
        SDL_DestroyCond(is->subpq_cond);
    
    #if !CONFIG_AVFILTER
    
        if (is->img_convert_ctx)
            sws_freeContext(is->img_convert_ctx);
    
    static void stream_cycle_channel(VideoState *is, int codec_type)
    
    {
        AVFormatContext *ic = is->ic;
        int start_index, stream_index;
        AVStream *st;
    
    
        if (codec_type == AVMEDIA_TYPE_VIDEO)
    
        else if (codec_type == AVMEDIA_TYPE_AUDIO)
    
        if (start_index < (codec_type == AVMEDIA_TYPE_SUBTITLE ? -1 : 0))
    
            return;
        stream_index = start_index;
        for(;;) {
            if (++stream_index >= is->ic->nb_streams)
    
                if (codec_type == AVMEDIA_TYPE_SUBTITLE)
    
                {
                    stream_index = -1;
                    goto the_end;
                } else
                    stream_index = 0;
            }
    
            if (stream_index == start_index)
                return;
            st = ic->streams[stream_index];
    
            if (st->codec->codec_type == codec_type) {
    
                /* check that parameters are OK */
                switch(codec_type) {
    
                    if (st->codec->sample_rate != 0 &&
                        st->codec->channels != 0)
    
                case AVMEDIA_TYPE_VIDEO:
                case AVMEDIA_TYPE_SUBTITLE:
    
                    goto the_end;
                default:
                    break;
                }
            }
        }
     the_end:
        stream_component_close(is, start_index);
        stream_component_open(is, stream_index);
    }
    
    
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        is_full_screen = !is_full_screen;
    
        if (!fs_screen_width) {
            /* use default SDL method */
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        if (cur_stream)
            stream_pause(cur_stream);
    
            /* if the stream is paused unpause it, then step */
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        if (cur_stream) {
            stream_close(cur_stream);
            cur_stream = NULL;
        }
    
        for (i = 0; i < AVMEDIA_TYPE_NB; i++)
    
            av_free(avcodec_opts[i]);
        av_free(avformat_opts);
        av_free(sws_opts);
    
    #if CONFIG_AVFILTER
        avfilter_uninit();
    #endif
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        if (show_status)
            printf("\n");
        SDL_Quit();
        exit(0);
    }
    
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        if (cur_stream) {
    
            int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
    
            cur_stream->show_audio = (cur_stream->show_audio + 1) % 3;
    
            fill_rectangle(screen,
                        cur_stream->xleft, cur_stream->ytop, cur_stream->width, cur_stream->height,
                        bgcolor);
            SDL_UpdateRect(screen, cur_stream->xleft, cur_stream->ytop, cur_stream->width, cur_stream->height);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
        }
    }
    
    /* handle an event sent by the GUI */
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    {
        SDL_Event event;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    
        for(;;) {
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
            double x;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            SDL_WaitEvent(&event);
            switch(event.type) {
            case SDL_KEYDOWN:
                switch(event.key.keysym.sym) {
                case SDLK_ESCAPE:
                case SDLK_q:
                    do_exit();
                    break;
                case SDLK_f:
                    toggle_full_screen();
                    break;
                case SDLK_p:
                case SDLK_SPACE:
                    toggle_pause();
                    break;
    
                case SDLK_s: //S: Step to next frame
                    step_to_next_frame();
                    break;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                case SDLK_a:
    
                    if (cur_stream)
    
                        stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
    
                    if (cur_stream)
    
                        stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
    
                    if (cur_stream)
    
                        stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                    toggle_audio_display();
                    break;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                case SDLK_LEFT:
                    incr = -10.0;
                    goto do_seek;
                case SDLK_RIGHT:
                    incr = 10.0;
                    goto do_seek;
                case SDLK_UP:
                    incr = 60.0;
                    goto do_seek;
                case SDLK_DOWN:
                    incr = -60.0;
                do_seek:
                    if (cur_stream) {
    
                        if (seek_by_bytes) {
    
                            if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos>=0){
                                pos= cur_stream->video_current_pos;
                            }else if(cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos>=0){
                                pos= cur_stream->audio_pkt.pos;
                            }else
                                pos = url_ftell(cur_stream->ic->pb);
    
                            if (cur_stream->ic->bit_rate)
    
                                incr *= cur_stream->ic->bit_rate / 8.0;
    
                            else
                                incr *= 180000.0;
                            pos += incr;
    
                        } else {
                            pos = get_master_clock(cur_stream);
                            pos += incr;
    
                            stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                    }
                    break;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                default:
                    break;
                }
                break;
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
            case SDL_MOUSEMOTION:
                if(event.type ==SDL_MOUSEBUTTONDOWN){
                    x= event.button.x;
                }else{
                    if(event.motion.state != SDL_PRESSED)
                        break;
                    x= event.motion.x;
                }
    
                    if(seek_by_bytes || cur_stream->ic->duration<=0){
                        uint64_t size=  url_fsize(cur_stream->ic->pb);
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
                        stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
                        int64_t ts;
                        int ns, hh, mm, ss;
                        int tns, thh, tmm, tss;
                        tns = cur_stream->ic->duration/1000000LL;
                        thh = tns/3600;
                        tmm = (tns%3600)/60;
                        tss = (tns%60);
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
                        frac = x/cur_stream->width;
    
    Michael Niedermayer's avatar
    Michael Niedermayer committed
                        ns = frac*tns;
                        hh = ns/3600;
                        mm = (ns%3600)/60;
                        ss = (ns%60);
                        fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d)       \n", frac*100,
                                hh, mm, ss, thh, tmm, tss);
                        ts = frac*cur_stream->ic->duration;
                        if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
                            ts += cur_stream->ic->start_time;
                        stream_seek(cur_stream, ts, 0, 0);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
            case SDL_VIDEORESIZE:
                if (cur_stream) {
    
                    screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                                              SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
    
                    screen_width = cur_stream->width = event.resize.w;
                    screen_height= cur_stream->height= event.resize.h;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                }
                break;
            case SDL_QUIT:
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                do_exit();
                break;
            case FF_ALLOC_EVENT:
    
                video_open(event.user.data1);
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
                alloc_picture(event.user.data1);
                break;
            case FF_REFRESH_EVENT:
                video_refresh_timer(event.user.data1);
    
                cur_stream->refresh=0;
    
    static void opt_frame_size(const char *arg)
    {
    
        if (av_parse_video_frame_size(&frame_width, &frame_height, arg) < 0) {
    
            fprintf(stderr, "Incorrect frame size\n");
            exit(1);
        }
        if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
            fprintf(stderr, "Frame size must be a multiple of 2\n");
            exit(1);
        }
    }
    
    
    static int opt_width(const char *opt, const char *arg)
    
        screen_width = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
        return 0;
    
    static int opt_height(const char *opt, const char *arg)
    
        screen_height = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
        return 0;
    
    Fabrice Bellard's avatar
    Fabrice Bellard committed
    }
    
    static void opt_format(const char *arg)
    {
        file_iformat = av_find_input_format(arg);
        if (!file_iformat) {
            fprintf(stderr, "Unknown input format: %s\n", arg);
            exit(1);
        }
    }
    
    static void opt_frame_pix_fmt(const char *arg)
    {
    
        frame_pix_fmt = av_get_pix_fmt(arg);
    
    static int opt_sync(const char *opt, const char *arg)
    
    {
        if (!strcmp(arg, "audio"))
            av_sync_type = AV_SYNC_AUDIO_MASTER;
        else if (!strcmp(arg, "video"))
            av_sync_type = AV_SYNC_VIDEO_MASTER;
        else if (!strcmp(arg, "ext"))
            av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
    
            fprintf(stderr, "Unknown value for %s: %s\n", opt, arg);