Ticket #8318: getframe.patch

File getframe.patch, 73.1 KB (added by foobum <foobum@…>, 16 years ago)
  • mythtv/libs/libmythtv/avformatdecoder.cpp

    diff --git a/mythtv/libs/libmythtv/avformatdecoder.cpp b/mythtv/libs/libmythtv/avformatdecoder.cpp
    index a2e5c1c..1d6e644 100644
    a b AvFormatDecoder::AvFormatDecoder(NuppelVideoPlayer *parent,  
    472472      is_db_ignored(gContext->IsDatabaseIgnored()),
    473473      m_h264_parser(new H264Parser()),
    474474      ic(NULL),
    475       frame_decoded(0),             decoded_video_frame(NULL),
     475      decoded_video_frame(NULL),
    476476      avfRingBuffer(NULL),
    477       directrendering(false),       drawband(false),
     477      directrendering(false),
    478478      gopset(false),                seen_gop(false),
    479       seq_count(0),                 firstgoppos(0),
    480       prevgoppos(0),                gotvideo(false),
     479      seq_count(0),                 prevgoppos(0),
     480      wantaudio(false),             wantvideo(false),
     481      gotvideo(false),              skipaudio(false),
     482      allowedquit(false),
    481483      start_code_state(0xffffffff),
    482484      lastvpts(0),                  lastapts(0),
    483485      lastccptsu(0),
    AvFormatDecoder::AvFormatDecoder(NuppelVideoPlayer *parent,  
    496498      audioSamples(NULL),           audioSamplesResampled(NULL),
    497499      reformat_ctx(NULL),           audio_src_fmt(SAMPLE_FMT_NONE),
    498500      allow_ac3_passthru(false),    allow_dts_passthru(false),
    499       internal_vol(false),
    500       disable_passthru(false),      max_channels(2),
    501       last_ac3_channels(0),         last_framesRead(0),
    502       dummy_frame(NULL),
     501      internal_vol(false),          disable_passthru(false),
     502      max_channels(2),              last_ac3_channels(0),
     503      last_framesRead(0),           dummy_frame(NULL),
    503504      // DVD
    504505      lastdvdtitle(-1),
    505506      decodeStillFrame(false),
    506       dvd_xvmc_enabled(false), dvd_video_codec_changed(false),
    507       dvdTitleChanged(false), mpeg_seq_end_seen(false)
     507      dvd_xvmc_enabled(false),      dvd_video_codec_changed(false),
     508      dvdTitleChanged(false),       mpeg_seq_end_seen(false)
    508509{
    509510    bzero(&params, sizeof(AVFormatParameters));
    510511    // using preallocated AVFormatContext for our own ByteIOContext
    int AvFormatDecoder::ScanStreams(bool novideo)  
    18981899                    if  (!skip_loop_filter)
    18991900                    {
    19001901                        enc->skip_loop_filter = AVDISCARD_NONKEY;
    1901                     } 
     1902                    }
    19021903                }
    19031904
    19041905                bool handled = false;
    bool AvFormatDecoder::H264PreProcessPkt(AVStream *stream, AVPacket *pkt)  
    31003101    return on_frame;
    31013102}
    31023103
     3104bool AvFormatDecoder::PreProcessVideoPacket(AVPacket *pkt, AVStream *stream)
     3105{
     3106
     3107    AVCodecContext *ctx = stream->codec;
     3108    bool on_frame = true;
     3109
     3110    if (CODEC_IS_FFMPEG_MPEG(ctx->codec_id))
     3111    {
     3112        if (!ringBuffer->isDVD())
     3113            MpegPreProcessPkt(stream, pkt);
     3114    }
     3115    else if (CODEC_IS_H264(ctx->codec_id))
     3116        on_frame = H264PreProcessPkt(stream, pkt);
     3117    else
     3118    {
     3119        if (pkt->flags & PKT_FLAG_KEY)
     3120        {
     3121            HandleGopStart(pkt, false);
     3122            seen_gop = true;
     3123        }
     3124        else
     3125        {
     3126            seq_count++;
     3127            if (!seen_gop && seq_count > 1)
     3128                HandleGopStart(pkt, false);
     3129        }
     3130    }
     3131
     3132    if (framesRead == 0 && !justAfterChange && !(pkt->flags & PKT_FLAG_KEY))
     3133    {
     3134        av_free_packet(pkt);
     3135        return false;
     3136    }
     3137
     3138    if (on_frame)
     3139        framesRead++;
     3140    justAfterChange = false;
     3141
     3142    if (exitafterdecoded)
     3143        gotvideo = 1;
     3144
     3145    return true;
     3146}
     3147
     3148int AvFormatDecoder::ProcessVideoPacket(const AVPacket *pkt,
     3149                                        const AVStream *stream,
     3150                                        long long pts,  bool firstloop)
     3151{
     3152    AVCodecContext *ctx = stream->codec;
     3153    uchar *ptr          = pkt->data;
     3154    int len             = pkt->size;
     3155    int ret             = 0;
     3156
     3157    if (pkt->stream_index != selectedVideoIndex)
     3158        return len;
     3159
     3160    if (firstloop && pts != (int64_t) AV_NOPTS_VALUE)
     3161        lastccptsu = (long long)
     3162            (av_q2d(stream->time_base) * pkt->pts * 1000000);
     3163
     3164    if (!wantvideo)
     3165    {
     3166        framesPlayed++;
     3167        gotvideo = 1;
     3168        return len;
     3169    }
     3170
     3171    AVFrame mpa_pic;
     3172    bzero(&mpa_pic, sizeof(AVFrame));
     3173
     3174    int gotpicture = 0;
     3175
     3176    avcodeclock->lock();
     3177    if (d->HasDecoder())
     3178    {
     3179        if (decodeStillFrame)
     3180        {
     3181            int count = 0;
     3182            // HACK
     3183            while (!gotpicture && count < 5)
     3184            {
     3185                ret = d->DecodeMPEG2Video(ctx, &mpa_pic, &gotpicture, ptr, len);
     3186                count++;
     3187            }
     3188        }
     3189        else
     3190            ret = d->DecodeMPEG2Video(ctx, &mpa_pic, &gotpicture, ptr, len);
     3191    }
     3192    else
     3193    {
     3194        ret = avcodec_decode_video(ctx, &mpa_pic, &gotpicture, ptr, len);
     3195        // Reparse it to not drop the DVD still frame
     3196        if (decodeStillFrame)
     3197            ret = avcodec_decode_video(ctx, &mpa_pic, &gotpicture, ptr, len);
     3198    }
     3199    avcodeclock->unlock();
     3200
     3201    if (ret < 0)
     3202    {
     3203        VERBOSE(VB_IMPORTANT, LOC_ERR + "Unknown decoding error");
     3204        return len;
     3205    }
     3206
     3207    if (!gotpicture)
     3208        return len;
     3209
     3210    // Decode ATSC captions
     3211    for (uint i = 0; i < (uint)mpa_pic.atsc_cc_len;
     3212         i += ((mpa_pic.atsc_cc_buf[i] & 0x1f) * 3) + 2)
     3213        DecodeDTVCC(mpa_pic.atsc_cc_buf + i);
     3214
     3215    // Decode DVB captions from MPEG user data
     3216    if (mpa_pic.dvb_cc_len > 0)
     3217    {
     3218        unsigned long long utc = lastccptsu;
     3219
     3220        for (uint i = 0; i < (uint)mpa_pic.dvb_cc_len; i += 2)
     3221        {
     3222            uint8_t  cc_lo = mpa_pic.dvb_cc_buf[i];
     3223            uint8_t  cc_hi = mpa_pic.dvb_cc_buf[i+1];
     3224            uint16_t cc_dt = (cc_hi << 8) | cc_lo;
     3225
     3226            if (cc608_good_parity(cc608_parity_table, cc_dt))
     3227            {
     3228                ccd608->FormatCCField(utc/1000, 0, cc_dt);
     3229                utc += 33367;
     3230            }
     3231        }
     3232        lastccptsu = utc;
     3233        UpdateCaptionTracksFromStreams(true, false);
     3234    }
     3235
     3236    VideoFrame *picframe = (VideoFrame *)(mpa_pic.opaque);
     3237
     3238    if (!directrendering)
     3239    {
     3240        AVPicture tmppicture;
     3241
     3242        VideoFrame *xf = picframe;
     3243        picframe = GetNVP()->GetNextVideoFrame(false);
     3244
     3245        unsigned char *buf     = picframe->buf;
     3246        tmppicture.data[0]     = buf + picframe->offsets[0];
     3247        tmppicture.data[1]     = buf + picframe->offsets[1];
     3248        tmppicture.data[2]     = buf + picframe->offsets[2];
     3249        tmppicture.linesize[0] = picframe->pitches[0];
     3250        tmppicture.linesize[1] = picframe->pitches[1];
     3251        tmppicture.linesize[2] = picframe->pitches[2];
     3252
     3253        myth_sws_img_convert(&tmppicture, PIX_FMT_YUV420P,
     3254                             (AVPicture *)&mpa_pic,
     3255                             ctx->pix_fmt, ctx->width, ctx->height);
     3256
     3257        if (xf)
     3258        {
     3259            // Set the frame flags, but then discard it
     3260            // since we are not using it for display.
     3261            xf->interlaced_frame = mpa_pic.interlaced_frame;
     3262            xf->top_field_first = mpa_pic.top_field_first;
     3263            xf->frameNumber = framesPlayed;
     3264            GetNVP()->DiscardVideoFrame(xf);
     3265        }
     3266    }
     3267
     3268    long long temppts = pts;
     3269
     3270    // Validate the video pts against the last pts. If it's
     3271    // a little bit smaller, equal or not available, compute
     3272    // it from the last. Otherwise assume a wraparound.
     3273    if (!ringBuffer->isDVD() && temppts <= lastvpts &&
     3274        (temppts + 10000 > lastvpts || temppts <= 0))
     3275    {
     3276        temppts = lastvpts;
     3277        temppts += (long long)(1000 / fps);
     3278        // MPEG2/H264 frames can be repeated, update pts accordingly
     3279        temppts += (long long)(mpa_pic.repeat_pict * 500 / fps);
     3280    }
     3281
     3282    VERBOSE(VB_PLAYBACK+VB_TIMESTAMP, LOC +
     3283                QString("video timecode %1 %2 %3 %4")
     3284                .arg(pkt->pts).arg(pkt->dts).arg(temppts).arg(lastvpts));
     3285
     3286/* XXX: Broken.
     3287    if (mpa_pic.qscale_table != NULL && mpa_pic.qstride > 0 &&
     3288        context->height == picframe->height)
     3289    {
     3290        int tblsize = mpa_pic.qstride *
     3291                      ((picframe->height + 15) / 16);
     3292
     3293        if (picframe->qstride != mpa_pic.qstride ||
     3294            picframe->qscale_table == NULL)
     3295        {
     3296            picframe->qstride = mpa_pic.qstride;
     3297            if (picframe->qscale_table)
     3298                delete [] picframe->qscale_table;
     3299            picframe->qscale_table = new unsigned char[tblsize];
     3300        }
     3301
     3302        memcpy(picframe->qscale_table, mpa_pic.qscale_table,
     3303               tblsize);
     3304    }
     3305*/
     3306
     3307    picframe->interlaced_frame = mpa_pic.interlaced_frame;
     3308    picframe->top_field_first  = mpa_pic.top_field_first;
     3309    picframe->repeat_pict      = mpa_pic.repeat_pict;
     3310    picframe->frameNumber      = framesPlayed;
     3311
     3312    GetNVP()->ReleaseNextVideoFrame(picframe, temppts);
     3313    if (d->HasMPEG2Dec() && mpa_pic.data[3])
     3314        ctx->release_buffer(ctx, &mpa_pic);
     3315
     3316    decoded_video_frame = picframe;
     3317    gotvideo            = true;
     3318    lastvpts            = temppts;
     3319    framesPlayed++;
     3320
     3321    return ret;
     3322
     3323}
     3324
     3325static void extract_mono_channel(uint channel, AudioInfo *audioInfo,
     3326                                 char *buffer, int bufsize)
     3327{
     3328    // Only stereo -> mono (left or right) is supported
     3329    if (audioInfo->channels != 2)
     3330        return;
     3331
     3332    if (channel >= (uint)audioInfo->channels)
     3333        return;
     3334
     3335    const uint samplesize = audioInfo->sample_size;
     3336    const uint samples    = bufsize / samplesize;
     3337    const uint halfsample = samplesize >> 1;
     3338
     3339    const char *from = (channel == 1) ? buffer + halfsample : buffer;
     3340    char *to         = (channel == 0) ? buffer + halfsample : buffer;
     3341
     3342    for (uint sample = 0; sample < samples;
     3343         (sample++), (from += samplesize), (to += samplesize))
     3344    {
     3345        memmove(to, from, halfsample);
     3346    }
     3347}
     3348
     3349int AvFormatDecoder::ProcessAudioPacket(const AVPacket *pkt,
     3350                                        const AVStream *stream,
     3351                                        uchar *ptr, int len, int *decoded,
     3352                                        bool firstloop)
     3353{
     3354    AVCodecContext *ctx     = stream->codec;
     3355    int ret                 = 0;
     3356    bool reselectAudioTrack = false, dts = false;
     3357    AC3HeaderInfo hdr;
     3358    char *s;
     3359
     3360    avcodeclock->lock();
     3361    int audIdx = selectedTrack[kTrackTypeAudio].av_stream_index;
     3362    int audSubIdx = selectedTrack[kTrackTypeAudio].av_substream_index;
     3363    avcodeclock->unlock();
     3364    /// HACK HACK HACK -- begin See #3731
     3365    if (!GetNVP()->HasAudioIn())
     3366    {
     3367        VERBOSE(VB_AUDIO, LOC + "Audio is disabled - trying to restart it");
     3368        reselectAudioTrack = true;
     3369    }
     3370    /// HACK HACK HACK -- end
     3371
     3372    // detect switches between stereo and dual languages
     3373    bool wasDual = audSubIdx != -1;
     3374    bool isDual  = ctx->avcodec_dual_language;
     3375    if ((wasDual && !isDual) || (!wasDual &&  isDual))
     3376    {
     3377        SetupAudioStreamSubIndexes(audIdx);
     3378        reselectAudioTrack = true;
     3379    }
     3380
     3381    // detect channels on streams that need
     3382    // to be decoded before we can know this
     3383    bool already_decoded = false;
     3384    if (!ctx->channels)
     3385    {
     3386        QMutexLocker locker(avcodeclock);
     3387        VERBOSE(VB_IMPORTANT,
     3388            LOC + QString("Setting channels to %1")
     3389                    .arg(audioOut.channels));
     3390
     3391        if (DoPassThrough(ctx))
     3392            ctx->channels = ctx->request_channels = 0;
     3393        else
     3394            ctx->channels = ctx->request_channels = audioOut.channels;
     3395
     3396        *decoded = AVCODEC_MAX_AUDIO_FRAME_SIZE;
     3397        ret = avcodec_decode_audio2(ctx, audioSamples, decoded, ptr, len);
     3398        already_decoded = true;
     3399        reselectAudioTrack |= ctx->channels;
     3400    }
     3401
     3402    if (ctx->codec_id == CODEC_ID_AC3)
     3403    {
     3404        GetBitContext gbc;
     3405        init_get_bits(&gbc, ptr, len << 3);
     3406        if (!ff_ac3_parse_header(&gbc, &hdr)   &&
     3407            hdr.channels != last_ac3_channels)
     3408        {
     3409            VERBOSE(VB_AUDIO, LOC +
     3410                QString("AC3 changed from %1 to %2 channels (frame %3)")
     3411                    .arg(last_ac3_channels).arg(hdr.channels).arg(framesRead));
     3412
     3413            if ((framesRead - last_framesRead) > AUDIOMAXFRAMES ||
     3414                hdr.channels < last_ac3_channels)
     3415            {
     3416                ctx->channels = hdr.channels;
     3417            }
     3418
     3419            last_ac3_channels = hdr.channels;
     3420            last_framesRead = framesRead;
     3421            SetupAudioStream();
     3422        }
     3423    }
     3424
     3425    if (reselectAudioTrack)
     3426    {
     3427        QMutexLocker locker(avcodeclock);
     3428        currentTrack[kTrackTypeAudio]                  = -1;
     3429        selectedTrack[kTrackTypeAudio].av_stream_index = -1;
     3430        audIdx = audSubIdx = -1;
     3431        AutoSelectAudioTrack();
     3432        audIdx    = selectedTrack[kTrackTypeAudio].av_stream_index;
     3433        audSubIdx = selectedTrack[kTrackTypeAudio].av_substream_index;
     3434    }
     3435
     3436    if (!wantaudio || pkt->stream_index != audIdx)
     3437    {
     3438        *decoded = 0;
     3439        return len;
     3440    }
     3441
     3442    if (firstloop && pkt->pts != (int64_t)AV_NOPTS_VALUE)
     3443        lastapts = (long long)(av_q2d(stream->time_base) * pkt->pts * 1000);
     3444
     3445    if (skipaudio)
     3446    {
     3447        if ((lastapts < lastvpts - (10.0 / fps)) || lastvpts == 0)
     3448        {
     3449            *decoded = 0;
     3450            return len;
     3451        }
     3452        else
     3453            skipaudio = false;
     3454    }
     3455
     3456    avcodeclock->lock();
     3457    *decoded = 0;
     3458
     3459    if (audioOut.do_passthru)
     3460    {
     3461        *decoded = pkt->size;
     3462        dts = CODEC_ID_DTS == ctx->codec_id;
     3463        ret = encode_frame(dts, ptr, len, audioSamples, *decoded);
     3464        s = (char *)audioSamples;
     3465    }
     3466    else
     3467    {
     3468        if (!ctx->channels || ctx->channels > audioOut.channels)
     3469            ctx->channels = audioOut.channels;
     3470
     3471        if (!already_decoded)
     3472        {
     3473            ctx->request_channels = audioOut.channels;
     3474            *decoded = AVCODEC_MAX_AUDIO_FRAME_SIZE;
     3475            ret = avcodec_decode_audio2(ctx, audioSamples, decoded, ptr, len);
     3476        }
     3477
     3478        // Convert sample format if required (Myth only handles 8 and 16 bits audio)
     3479        if (ctx->sample_fmt == SAMPLE_FMT_S16 ||
     3480            ctx->sample_fmt == SAMPLE_FMT_U8  ||
     3481            (s = ConvertSampleFormat(ctx, decoded)) == NULL)
     3482        {
     3483            s = (char *)audioSamples;
     3484        }
     3485        // When decoding some audio streams the number of
     3486        // channels, etc isn't known until we try decoding it.
     3487        if ((ctx->sample_rate != audioOut.sample_rate) ||
     3488            (ctx->channels    != audioOut.channels))
     3489        {
     3490            VERBOSE(VB_IMPORTANT, LOC + "Audio stream changed");
     3491            currentTrack[kTrackTypeAudio]                  = -1;
     3492            selectedTrack[kTrackTypeAudio].av_stream_index = -1;
     3493            audIdx   = -1;
     3494            *decoded =  0;
     3495            AutoSelectAudioTrack();
     3496        }
     3497    }
     3498    avcodeclock->unlock();
     3499
     3500    if (ret < 0)
     3501    {
     3502        if (!dts)
     3503            VERBOSE(VB_IMPORTANT, LOC_ERR + "Unknown audio decoding error");
     3504        *decoded = 0;
     3505        return len;
     3506    }
     3507
     3508    if (*decoded <= 0)
     3509        return ret;
     3510
     3511    long long temppts = lastapts;
     3512
     3513    // calc for next frame
     3514    lastapts += (long long)((double)(*decoded * 1000) /
     3515                (ctx->sample_rate * ctx->channels *
     3516                 av_get_bits_per_sample_format(ctx->sample_fmt)>>3));
     3517
     3518    VERBOSE(VB_PLAYBACK+VB_TIMESTAMP,
     3519            LOC + QString("audio timecode %1 %2 %3 %4")
     3520                    .arg(pkt->pts).arg(pkt->dts).arg(temppts).arg(lastapts));
     3521
     3522    if (audSubIdx != -1)
     3523        extract_mono_channel(audSubIdx, &audioOut, s, *decoded);
     3524
     3525    GetNVP()->AddAudioData(s, *decoded, temppts);
     3526
     3527    return ret;
     3528
     3529}
     3530
     3531bool AvFormatDecoder::TopUpAudioBuffer(int decoded, uint total_decoded,
     3532                                       uint ofill,  uint othresh)
     3533{
     3534    uint fill, total;
     3535
     3536    if (ofill + total_decoded > othresh)
     3537        return true;
     3538
     3539    if (!GetNVP()->GetAudioBufferStatus(fill, total))
     3540    {
     3541        VERBOSE(VB_IMPORTANT, LOC_ERR + "GetFrame() : Failed to top off "
     3542                                        "buffers in audio only mode");
     3543        return false;
     3544    }
     3545
     3546    total /= 6; // HACK needed for some audio files
     3547    return (fill == 0) || (fill > (total>>1))    ||
     3548           ((total - fill) < (uint)decoded)      ||
     3549           (ofill + total_decoded > (total>>2))  ||
     3550           ((total - fill) < (uint)decoded * 2);
     3551}
     3552
    31033553/** \fn AvFormatDecoder::ProcessVBIDataPacket(const AVStream*, const AVPacket*)
    31043554 *  \brief Process ivtv proprietary embedded vertical blanking
    31053555 *         interval captions.
    void AvFormatDecoder::ProcessDSMCCPacket(  
    32583708#endif // USING_MHEG
    32593709}
    32603710
     3711int AvFormatDecoder::ProcessSubtitlePacket(const AVPacket *pkt,
     3712                                           const AVStream *stream,
     3713                                           long long pts)
     3714{
     3715    uchar *ptr       = pkt->data;
     3716    int len          = pkt->size;
     3717    int gotSubtitles = 0;
     3718    AVSubtitle subtitle;
     3719    memset(&subtitle, 0, sizeof(AVSubtitle));
     3720    avcodeclock->lock();
     3721    int subIdx = selectedTrack[kTrackTypeSubtitle].av_stream_index;
     3722    avcodeclock->unlock();
     3723
     3724    if (ringBuffer->isDVD())
     3725    {
     3726        if (ringBuffer->DVD()->NumMenuButtons() > 0)
     3727            ringBuffer->DVD()->GetMenuSPUPkt(ptr, len, stream->id);
     3728        else
     3729        {
     3730            if (pkt->stream_index == subIdx)
     3731            {
     3732                QMutexLocker locker(avcodeclock);
     3733                ringBuffer->DVD()->DecodeSubtitles(&subtitle, &gotSubtitles,
     3734                                                   ptr, len);
     3735            }
     3736        }
     3737    }
     3738    else if (pkt->stream_index == subIdx)
     3739    {
     3740        QMutexLocker locker(avcodeclock);
     3741        avcodec_decode_subtitle(stream->codec, &subtitle, &gotSubtitles,
     3742                                ptr, len);
     3743    }
     3744
     3745    if (gotSubtitles)
     3746    {
     3747        subtitle.start_display_time += pts;
     3748        subtitle.end_display_time   += pts;
     3749        GetNVP()->AddAVSubtitle(subtitle);
     3750
     3751        VERBOSE(VB_PLAYBACK|VB_TIMESTAMP, LOC +
     3752                QString("subtl timecode %1 %2 %3 %4")
     3753                    .arg(pkt->pts).arg(pkt->dts)
     3754                    .arg(subtitle.start_display_time)
     3755                    .arg(subtitle.end_display_time));
     3756    }
     3757
     3758    return len;
     3759}
     3760
     3761bool AvFormatDecoder::ProcessDataPacket(AVPacket *pkt, const AVStream *stream)
     3762{
     3763    AVCodecContext *ctx = stream->codec;
     3764
     3765    if (ctx->codec_id == CODEC_ID_MPEG2VBI)
     3766    {
     3767        ProcessVBIDataPacket(stream, pkt);
     3768        av_free_packet(pkt);
     3769        return true;
     3770    }
     3771
     3772    if (ctx->codec_id == CODEC_ID_DVB_VBI ||
     3773        ctx->codec_id == CODEC_ID_DVB_TELETEXT)
     3774    {
     3775        ProcessDVBDataPacket(stream, pkt);
     3776        av_free_packet(pkt);
     3777        return true;
     3778    }
     3779
     3780#ifdef USING_MHEG
     3781    if (ctx->codec_id == CODEC_ID_DSMCC_B)
     3782    {
     3783        ProcessDSMCCPacket(stream, pkt);
     3784        av_free_packet(pkt);
     3785        // Have to return regularly to ensure that the OSD is updated.
     3786        // This applies both to MHEG and also channel browsing.
     3787        if (!wantvideo)
     3788        {
     3789            allowedquit |= (itv && itv->ImageHasChanged());
     3790            OSD *osd = NULL;
     3791            if (!allowedquit && GetNVP() && (osd = GetNVP()->GetOSD()))
     3792                allowedquit |= osd->HasChanged();
     3793        }
     3794        return true;
     3795    }
     3796#endif // USING_MHEG
     3797
     3798    // we don't care about other data streams
     3799    if (ctx->codec_type == CODEC_TYPE_DATA)
     3800    {
     3801        av_free_packet(pkt);
     3802        return true;
     3803    }
     3804
     3805    return false;
     3806}
     3807
    32613808int AvFormatDecoder::SetTrack(uint type, int trackNo)
    32623809{
    32633810    bool ret = DecoderBase::SetTrack(type, trackNo);
    int AvFormatDecoder::AutoSelectAudioTrack(void)  
    36274174    return selTrack;
    36284175}
    36294176
    3630 static void extract_mono_channel(uint channel, AudioInfo *audioInfo,
    3631                                  char *buffer, int bufsize)
     4177AVPacket* AvFormatDecoder::GetPacket(AVPacket *pkt, bool storevideoframes)
    36324178{
    3633     // Only stereo -> mono (left or right) is supported
    3634     if (audioInfo->channels != 2)
    3635         return;
    3636 
    3637     if (channel >= (uint)audioInfo->channels)
    3638         return;
     4179    if (!storevideoframes && storedPackets.count() > 0)
     4180    {
     4181        if (pkt)
     4182        {
     4183            av_free_packet(pkt);
     4184            delete pkt;
     4185        }
     4186        pkt = storedPackets.takeFirst();
     4187        return pkt;
     4188    }
    36394189
    3640     const uint samplesize = audioInfo->sample_size;
    3641     const uint samples    = bufsize / samplesize;
    3642     const uint halfsample = samplesize >> 1;
     4190    if (!pkt)
     4191    {
     4192        pkt = new AVPacket;
     4193        bzero(pkt, sizeof(AVPacket));
     4194        av_init_packet(pkt);
     4195    }
    36434196
    3644     const char *from = (channel == 1) ? buffer + halfsample : buffer;
    3645     char *to         = (channel == 0) ? buffer + halfsample : buffer;
     4197    if (!ic || (av_read_frame(ic, pkt) < 0))
     4198    {
     4199        ateof = true;
     4200        GetNVP()->SetEof();
     4201        delete pkt;
     4202        return NULL;
     4203    }
    36464204
    3647     for (uint sample = 0; sample < samples;
    3648          (sample++), (from += samplesize), (to += samplesize))
     4205    if (ringBuffer->isDVD() && ringBuffer->DVD()->InStillFrame())
    36494206    {
    3650         memmove(to, from, halfsample);
     4207        AVStream *curstream = ic->streams[pkt->stream_index];
     4208        if (curstream && curstream->codec->codec_type == CODEC_TYPE_VIDEO)
     4209        {
     4210            mpeg_seq_end_seen = decodeStillFrame = false;
     4211            ringBuffer->DVD()->InStillFrame(false);
     4212        }
    36514213    }
     4214
     4215    if (waitingForChange && pkt->pos >= readAdjust)
     4216        FileChanged();
     4217
     4218    if (pkt->pos > readAdjust)
     4219        pkt->pos -= readAdjust;
     4220
     4221    return pkt;
    36524222}
    36534223
    36544224// documented in decoderbase.h
    36554225bool AvFormatDecoder::GetFrame(DecodeType decodetype)
    36564226{
    3657     AVPacket *pkt = NULL;
    3658     AC3HeaderInfo hdr;
    3659     int len;
    3660     unsigned char *ptr;
    3661     int data_size = 0;
     4227    AVPacket *pkt  = NULL;
     4228    int len, ret;
    36624229    long long pts;
    3663     bool firstloop = false, have_err = false;
    3664 
    3665     gotvideo = false;
     4230    unsigned char *ptr;
     4231    bool firstloop = false;
     4232    bool storevideoframes = false;
     4233    bool has_video = HasVideo(ic);
    36664234
    3667     frame_decoded = 0;
     4235    wantvideo           = decodetype & kDecodeVideo;
     4236    wantaudio           = decodetype & kDecodeAudio;
     4237    gotvideo            = false;
     4238    skipaudio           = (lastvpts == 0);
    36684239    decoded_video_frame = NULL;
    3669 
    3670     bool allowedquit = false;
    3671     bool storevideoframes = false;
     4240    allowedquit         = false;
    36724241
    36734242    avcodeclock->lock();
    36744243    AutoSelectTracks();
    36754244    avcodeclock->unlock();
    36764245
    3677     bool skipaudio = (lastvpts == 0);
    3678 
    3679     bool has_video = HasVideo(ic);
    3680 
    3681     if (!has_video && (decodetype & kDecodeVideo))
     4246    if (wantvideo && !has_video)
    36824247    {
    3683         gotvideo = GenerateDummyVideoFrame();
    3684         decodetype = (DecodeType)((int)decodetype & ~kDecodeVideo);
    3685         skipaudio = false;
     4248        gotvideo   = GenerateDummyVideoFrame();
     4249        wantvideo  = skipaudio = false;
    36864250    }
    36874251
    36884252    uint ofill = 0, ototal = 0, othresh = 0, total_decoded_audio = 0;
    36894253    if (GetNVP()->GetAudioBufferStatus(ofill, ototal))
    36904254    {
    3691         othresh = ((ototal>>1) + (ototal>>2));
    3692         allowedquit = (!(decodetype & kDecodeAudio)) && (ofill > othresh);
     4255        othresh     = ((ototal>>1) + (ototal>>2));
     4256        allowedquit = !wantaudio && (ofill > othresh);
    36934257    }
    36944258
    36954259    while (!allowedquit)
    36964260    {
    3697         if ((decodetype & kDecodeAudio) &&
     4261        if (wantaudio &&
    36984262            ((currentTrack[kTrackTypeAudio] < 0) ||
    36994263             (selectedTrack[kTrackTypeAudio].av_stream_index < 0)))
    37004264        {
    37014265            // disable audio request if there are no audio streams anymore
    37024266            // and we have video, otherwise allow decoding to stop
    37034267            if (has_video)
    3704                 decodetype = (DecodeType)((int)decodetype & ~kDecodeAudio);
     4268                wantaudio = false;
    37054269            else
    37064270                allowedquit = true;
    37074271        }
    37084272
    37094273        if (ringBuffer->isDVD())
    3710         {
    3711             int dvdtitle  = 0;
    3712             int dvdpart = 0;
    3713             ringBuffer->DVD()->GetPartAndTitle(dvdpart, dvdtitle);
    3714             bool cellChanged = ringBuffer->DVD()->CellChanged();
    3715             bool inDVDStill = ringBuffer->DVD()->InStillFrame();
    3716             bool inDVDMenu  = ringBuffer->DVD()->IsInMenu();
    3717             int storedPktCount = storedPackets.count();
    3718             selectedVideoIndex = 0;
    3719             if (dvdTitleChanged)
    3720             {
    3721                 if ((storedPktCount > 10 && !decodeStillFrame) ||
    3722                     decodeStillFrame)
    3723                 {
    3724                     storevideoframes = false;
    3725                     dvdTitleChanged = false;
    3726                     ScanStreams(true);
    3727                 }
    3728                 else
    3729                     storevideoframes = true;
    3730             }
    3731             else
    3732             {
    3733                 storevideoframes = false;
    3734 
    3735                 if (storedPktCount < 2 && !decodeStillFrame)
    3736                     storevideoframes = true;
    3737 
    3738                 VERBOSE(VB_PLAYBACK+VB_EXTRA, QString("DVD Playback Debugging "
    3739                     "inDVDMenu %1 storedPacketcount %2 dvdstill %3")
    3740                     .arg(inDVDMenu).arg(storedPktCount).arg(inDVDStill));
    3741 
    3742                 if (inDVDStill && (storedPktCount == 0) &&
    3743                     (GetNVP()->getVideoOutput()->ValidVideoFrames() == 0))
    3744                 {
    3745                     ringBuffer->DVD()->RunSeekCellStart();
    3746                 }
    3747             }
    3748             if (GetNVP()->AtNormalSpeed() &&
    3749                 ((cellChanged) || (lastdvdtitle != dvdtitle)))
    3750             {
    3751                 if (dvdtitle != lastdvdtitle)
    3752                 {
    3753                     VERBOSE(VB_PLAYBACK, LOC + "DVD Title Changed");
    3754                     lastdvdtitle = dvdtitle;
    3755                     if (lastdvdtitle != -1 )
    3756                         dvdTitleChanged = true;
    3757                     if (GetNVP() && GetNVP()->getVideoOutput())
    3758                     {
    3759                         if (ringBuffer->DVD()->InStillFrame())
    3760                             GetNVP()->getVideoOutput()->SetPrebuffering(false);
    3761                         else
    3762                             GetNVP()->getVideoOutput()->SetPrebuffering(true);
    3763                     }
    3764                 }
    3765 
    3766                 if (ringBuffer->DVD()->PGCLengthChanged())
    3767                 {
    3768                     {
    3769                         QMutexLocker locker(&m_positionMapLock);
    3770                         posmapStarted = false;
    3771                         m_positionMap.clear();
    3772                     }
    3773                     SyncPositionMap();
    3774                 }
    3775 
    3776                 UpdateDVDFramesPlayed();
    3777                 VERBOSE(VB_PLAYBACK, QString(LOC + "DVD Cell Changed. "
    3778                                              "Update framesPlayed: %1 ")
    3779                                              .arg(framesPlayed));
    3780             }
    3781         }
     4274            storevideoframes = UpdateDVDStatus();
    37824275
    37834276        if (gotvideo)
    37844277        {
    3785             if (decodetype == kDecodeNothing)
     4278            if (!wantvideo && !wantaudio)
    37864279            {
    37874280                // no need to buffer audio or video if we
    37884281                // only care about building a keyframe map.
    37894282                allowedquit = true;
    37904283                continue;
    37914284            }
    3792             else if (lowbuffers && ((decodetype & kDecodeAV) == kDecodeAV) &&
     4285            else if (lowbuffers && wantaudio && wantvideo &&
    37934286                     storedPackets.count() < max_video_queue_size &&
    37944287                     lastapts < lastvpts + 100 &&
    37954288                     !ringBuffer->InDVDMenuOrStillFrame())
    37964289            {
    37974290                storevideoframes = true;
    37984291            }
    3799             else if (decodetype & kDecodeVideo)
     4292            else if (wantvideo)
    38004293            {
    38014294                if (storedPackets.count() >= max_video_queue_size)
    38024295                    VERBOSE(VB_IMPORTANT,
    bool AvFormatDecoder::GetFrame(DecodeType decodetype)  
    38084301            }
    38094302        }
    38104303
    3811         if (!storevideoframes && storedPackets.count() > 0)
    3812         {
    3813             if (pkt)
    3814             {
    3815                 av_free_packet(pkt);
    3816                 delete pkt;
    3817             }
    3818             pkt = storedPackets.takeFirst();
    3819         }
    3820         else
    3821         {
    3822             if (!pkt)
    3823             {
    3824                 pkt = new AVPacket;
    3825                 bzero(pkt, sizeof(AVPacket));
    3826                 av_init_packet(pkt);
    3827             }
    3828 
    3829             if (!ic || (av_read_frame(ic, pkt) < 0))
    3830             {
    3831                 ateof = true;
    3832                 GetNVP()->SetEof();
    3833                 delete pkt;
    3834                 return false;
    3835             }
    3836 
    3837             if (ringBuffer->isDVD() &&
    3838                 ringBuffer->DVD()->InStillFrame())
    3839             {
    3840                 AVStream *curstream = ic->streams[pkt->stream_index];
    3841                 if (curstream &&
    3842                     curstream->codec->codec_type == CODEC_TYPE_VIDEO)
    3843                 {
    3844                     mpeg_seq_end_seen = false;
    3845                     decodeStillFrame = false;
    3846                     ringBuffer->DVD()->InStillFrame(false);
    3847                 }
    3848             }
    3849 
    3850             if (waitingForChange && pkt->pos >= readAdjust)
    3851                 FileChanged();
    3852 
    3853             if (pkt->pos > readAdjust)
    3854                 pkt->pos -= readAdjust;
    3855         }
     4304        if ((pkt = GetPacket(pkt, storevideoframes)) == NULL)
     4305            return false;
    38564306
    38574307        if (pkt->stream_index > (int) ic->nb_streams)
    38584308        {
    3859             VERBOSE(VB_IMPORTANT, LOC_ERR + "Bad stream");
     4309            VERBOSE(VB_IMPORTANT, LOC_ERR + "Packet stream index out of bounds");
    38604310            av_free_packet(pkt);
    38614311            continue;
    38624312        }
    bool AvFormatDecoder::GetFrame(DecodeType decodetype)  
    38654315        ptr = pkt->data;
    38664316        pts = 0;
    38674317
    3868         AVStream *curstream = ic->streams[pkt->stream_index];
     4318        AVStream *stream = ic->streams[pkt->stream_index];
     4319        AVCodecContext *ctx = stream->codec;
    38694320
    3870         if (!curstream)
     4321        if (!stream)
    38714322        {
    38724323            VERBOSE(VB_IMPORTANT, LOC_ERR + "Bad stream (NULL)");;
    38734324            av_free_packet(pkt);
    bool AvFormatDecoder::GetFrame(DecodeType decodetype)  
    38754326        }
    38764327
    38774328        if (pkt->dts != (int64_t)AV_NOPTS_VALUE)
    3878             pts = (long long)(av_q2d(curstream->time_base) * pkt->dts * 1000);
    3879 
    3880         if (ringBuffer->isDVD() &&
    3881             curstream->codec->codec_type == CODEC_TYPE_VIDEO)
    3882         {
    3883             MpegPreProcessPkt(curstream, pkt);
    3884 
    3885             if (mpeg_seq_end_seen)
    3886                 ringBuffer->DVD()->InStillFrame(true);
    3887 
    3888             bool inDVDStill = ringBuffer->DVD()->InStillFrame();
    3889 
    3890             VERBOSE(VB_PLAYBACK+VB_EXTRA,
    3891                 QString("DVD Playback Debugging: mpeg seq end %1 "
    3892                 " inDVDStill %2 decodeStillFrame %3")
    3893                 .arg(mpeg_seq_end_seen).arg(inDVDStill).arg(decodeStillFrame));
    3894 
    3895             if (!decodeStillFrame && inDVDStill)
    3896             {
    3897                 decodeStillFrame = true;
    3898                 d->ResetMPEG2();
    3899             }
    3900 
    3901             if (!d->HasMPEG2Dec())
    3902             {
    3903                 int current_width = curstream->codec->width;
    3904                 int video_width = GetNVP()->GetVideoSize().width();
    3905                 if (dvd_xvmc_enabled && GetNVP() && GetNVP()->getVideoOutput())
    3906                 {
    3907                     bool dvd_xvmc_active = false;
    3908                     if (codec_is_xvmc(video_codec_id))
    3909                     {
    3910                         dvd_xvmc_active = true;
    3911                     }
    3912 
    3913                     bool indvdmenu   = ringBuffer->InDVDMenuOrStillFrame();
    3914                     if ((indvdmenu && dvd_xvmc_active) ||
    3915                         ((!indvdmenu && !dvd_xvmc_active)))
    3916                     {
    3917                         VERBOSE(VB_PLAYBACK, LOC + QString("DVD Codec Change "
    3918                                     "indvdmenu %1 dvd_xvmc_active %2")
    3919                                 .arg(indvdmenu).arg(dvd_xvmc_active));
    3920                         dvd_video_codec_changed = true;
    3921                     }
    3922                 }
    3923 
    3924                 if ((video_width > 0) && dvd_video_codec_changed)
    3925                 {
    3926                     VERBOSE(VB_PLAYBACK, LOC + QString("DVD Stream/Codec Change "
    3927                                 "video_width %1 current_width %2 "
    3928                                 "dvd_video_codec_changed %3")
    3929                             .arg(video_width).arg(current_width)
    3930                             .arg(dvd_video_codec_changed));
    3931                     av_free_packet(pkt);
    3932                     if (current_width > 0) {
    3933                         CloseCodecs();
    3934                         ScanStreams(false);
    3935                         allowedquit = true;
    3936                         dvd_video_codec_changed = false;
    3937                     }
    3938                     continue;
    3939                 }
    3940             }
    3941         }
     4329            pts = (long long)(av_q2d(stream->time_base) * pkt->dts * 1000);
    39424330
    3943         if (storevideoframes &&
    3944             curstream->codec->codec_type == CODEC_TYPE_VIDEO)
     4331        if (len <= 0)
    39454332        {
    3946             av_dup_packet(pkt);
    3947             storedPackets.append(pkt);
    3948             pkt = NULL;
     4333            av_free_packet(pkt);
    39494334            continue;
    39504335        }
    39514336
    3952         if (len > 0 && curstream->codec->codec_type == CODEC_TYPE_VIDEO &&
    3953             pkt->stream_index == selectedVideoIndex)
     4337        if (ctx->codec_type == CODEC_TYPE_VIDEO)
    39544338        {
    3955             AVCodecContext *context = curstream->codec;
    3956             bool on_frame = true;
    3957 
    3958             if (CODEC_IS_FFMPEG_MPEG(context->codec_id))
    3959             {
    3960                 if (!ringBuffer->isDVD())
    3961                     MpegPreProcessPkt(curstream, pkt);
    3962             }
    3963             else if (CODEC_IS_H264(context->codec_id))
    3964             {
    3965                 on_frame = H264PreProcessPkt(curstream, pkt);
    3966             }
    3967             else
    3968             {
    3969                 if (pkt->flags & PKT_FLAG_KEY)
    3970                 {
    3971                     HandleGopStart(pkt, false);
    3972                     seen_gop = true;
    3973                 }
    3974                 else
    3975                 {
    3976                     seq_count++;
    3977                     if (!seen_gop && seq_count > 1)
    3978                     {
    3979                         HandleGopStart(pkt, false);
    3980                     }
    3981                 }
    3982             }
    3983 
    3984             if (framesRead == 0 && !justAfterChange &&
    3985                 !(pkt->flags & PKT_FLAG_KEY))
    3986             {
    3987                 av_free_packet(pkt);
     4339            if (ringBuffer->isDVD() && !PreProcessDVDVideoPacket(pkt, stream))
    39884340                continue;
    3989             }
    39904341
    3991             if (on_frame)
    3992                 framesRead++;
    3993             justAfterChange = false;
    3994 
    3995             if (exitafterdecoded)
    3996                 gotvideo = 1;
    3997 
    3998             // If the resolution changed in XXXPreProcessPkt, we may
    3999             // have a fatal error, so check for this before continuing.
    4000             if (GetNVP()->IsErrored())
     4342            if (storevideoframes)
    40014343            {
    4002                 av_free_packet(pkt);
    4003                 delete pkt;
    4004                 return false;
     4344                av_dup_packet(pkt);
     4345                storedPackets.append(pkt);
     4346                pkt = NULL;
     4347                continue;
    40054348            }
    4006         }
    4007 
    4008         if (len > 0 &&
    4009             curstream->codec->codec_type == CODEC_TYPE_DATA &&
    4010             curstream->codec->codec_id   == CODEC_ID_MPEG2VBI)
    4011         {
    4012             ProcessVBIDataPacket(curstream, pkt);
    4013 
    4014             av_free_packet(pkt);
    4015             continue;
    4016         }
    4017 
    4018         if (len > 0 &&
    4019             ((curstream->codec->codec_type == CODEC_TYPE_DATA &&
    4020               curstream->codec->codec_id   == CODEC_ID_DVB_VBI) ||
    4021              (curstream->codec->codec_type == CODEC_TYPE_SUBTITLE &&
    4022               curstream->codec->codec_id   == CODEC_ID_DVB_TELETEXT)))
    4023         {
    4024             ProcessDVBDataPacket(curstream, pkt);
    4025 
    4026             av_free_packet(pkt);
    4027             continue;
    4028         }
    4029 
    4030 #ifdef USING_MHEG
    4031         if (len > 0 &&
    4032             curstream->codec->codec_type == CODEC_TYPE_DATA &&
    4033             curstream->codec->codec_id   == CODEC_ID_DSMCC_B)
    4034         {
    4035             ProcessDSMCCPacket(curstream, pkt);
    4036 
    4037             av_free_packet(pkt);
    40384349
    4039             // Have to return regularly to ensure that the OSD is updated.
    4040             // This applies both to MHEG and also channel browsing.
    4041             if (!(decodetype & kDecodeVideo))
     4350            if (pkt->stream_index == selectedVideoIndex)
    40424351            {
    4043                 allowedquit |= (itv && itv->ImageHasChanged());
    4044                 OSD *osd = NULL;
    4045                 if (!allowedquit && GetNVP() && (osd = GetNVP()->GetOSD()))
    4046                     allowedquit |=  osd->HasChanged();
     4352                if (!PreProcessVideoPacket(pkt, stream))
     4353                    continue;
     4354                // If the resolution changed in XXXPreProcessPkt, we may
     4355                // have a fatal error, so check for this before continuing.
     4356                if (GetNVP()->IsErrored())
     4357                {
     4358                    av_free_packet(pkt);
     4359                    delete pkt;
     4360                    return false;
     4361                }
    40474362            }
    4048 
    4049             continue;
    40504363        }
    4051 #endif // USING_MHEG
    4052 
    4053         // we don't care about other data streams
    4054         if (curstream->codec->codec_type == CODEC_TYPE_DATA)
    4055         {
    4056             av_free_packet(pkt);
     4364        else if ((ctx->codec_type == CODEC_TYPE_DATA      ||
     4365                  ctx->codec_type == CODEC_TYPE_SUBTITLE) &&
     4366                 ProcessDataPacket(pkt, stream))
    40574367            continue;
    4058         }
    40594368
    4060         if (!curstream->codec->codec)
     4369        if (!ctx->codec)
    40614370        {
    40624371            VERBOSE(VB_PLAYBACK, LOC +
    40634372                    QString("No codec for stream index %1, type(%2) id(%3:%4)")
    40644373                    .arg(pkt->stream_index)
    4065                     .arg(codec_type_string(curstream->codec->codec_type))
    4066                     .arg(codec_id_string(curstream->codec->codec_id))
    4067                     .arg(curstream->codec->codec_id));
     4374                    .arg(codec_type_string(ctx->codec_type))
     4375                    .arg(codec_id_string(ctx->codec_id))
     4376                    .arg(ctx->codec_id));
    40684377            av_free_packet(pkt);
    40694378            continue;
    40704379        }
    40714380
     4381        int ctype = ctx->codec_type;
    40724382        firstloop = true;
    4073         have_err = false;
    4074 
    4075         avcodeclock->lock();
    4076         int ctype  = curstream->codec->codec_type;
    4077         int audIdx = selectedTrack[kTrackTypeAudio].av_stream_index;
    4078         int audSubIdx = selectedTrack[kTrackTypeAudio].av_substream_index;
    4079         int subIdx = selectedTrack[kTrackTypeSubtitle].av_stream_index;
    4080         avcodeclock->unlock();
    40814383
    4082         while (!have_err && len > 0)
     4384        while (len > 0)
    40834385        {
    4084             int ret = 0;
    4085             bool dts = false;
    40864386            switch (ctype)
    40874387            {
    40884388                case CODEC_TYPE_AUDIO:
    4089                 {
    4090                     bool reselectAudioTrack = false;
    4091                     char *s;
    4092 
    4093                     /// HACK HACK HACK -- begin See #3731
    4094                     if (!GetNVP()->HasAudioIn())
    4095                     {
    4096                         VERBOSE(VB_AUDIO, LOC + "Audio is disabled - trying to restart it");
    4097                         reselectAudioTrack = true;
    4098                     }
    4099                     /// HACK HACK HACK -- end
    4100 
    4101                     // detect switches between stereo and dual languages
    4102                     bool wasDual = audSubIdx != -1;
    4103                     bool isDual = curstream->codec->avcodec_dual_language;
    4104                     if ((wasDual && !isDual) || (!wasDual &&  isDual))
    4105                     {
    4106                         SetupAudioStreamSubIndexes(audIdx);
    4107                         reselectAudioTrack = true;
    4108                     }
    4109 
    4110                     // detect channels on streams that need
    4111                     // to be decoded before we can know this
    4112                     bool already_decoded = false;
    4113                     if (!curstream->codec->channels)
    4114                     {
    4115                         QMutexLocker locker(avcodeclock);
    4116                         VERBOSE(VB_IMPORTANT, LOC +
    4117                                 QString("Setting channels to %1")
    4118                                 .arg(audioOut.channels));
    4119 
    4120                         if (DoPassThrough(curstream->codec))
    4121                         {
    4122                             // for passthru let it select the max number
    4123                             // of channels
    4124                             curstream->codec->channels = 0;
    4125                             curstream->codec->request_channels = 0;
    4126                         }
    4127                         else
    4128                         {
    4129                             curstream->codec->channels = audioOut.channels;
    4130                             curstream->codec->request_channels =
    4131                                 audioOut.channels;
    4132                         }
    4133                         data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
    4134                         ret = avcodec_decode_audio2(curstream->codec,
    4135                                                     audioSamples, &data_size,
    4136                                                     ptr, len);
    4137                         already_decoded = true;
    4138 
    4139                         reselectAudioTrack |= curstream->codec->channels;
    4140                     }
    4141 
    4142                     if (curstream->codec->codec_id == CODEC_ID_AC3)
    4143                     {
    4144                         GetBitContext gbc;
    4145                         init_get_bits(&gbc, ptr, len * 8);
    4146                         if (!ff_ac3_parse_header(&gbc, &hdr))
    4147                         {
    4148                             if (hdr.channels != last_ac3_channels)
    4149                             {
    4150                                 VERBOSE(VB_AUDIO, LOC + QString("AC3 changed from %1 to %2 channels (frame %3)")
    4151                                         .arg(last_ac3_channels).arg(hdr.channels).arg(framesRead));
    4152                                 if ((framesRead - last_framesRead) > AUDIOMAXFRAMES ||
    4153                                     hdr.channels < last_ac3_channels)
    4154                                     curstream->codec->channels = hdr.channels;
    4155                                 last_ac3_channels = hdr.channels;
    4156                                 last_framesRead = framesRead;
    4157                                 SetupAudioStream();
    4158                             }
    4159                         }
    4160                     }
    4161 
    4162                     if (reselectAudioTrack)
    4163                     {
    4164                         QMutexLocker locker(avcodeclock);
    4165                         currentTrack[kTrackTypeAudio] = -1;
    4166                         selectedTrack[kTrackTypeAudio]
    4167                             .av_stream_index = -1;
    4168                         audIdx = -1;
    4169                         audSubIdx = -1;
    4170                         AutoSelectAudioTrack();
    4171                         audIdx = selectedTrack[kTrackTypeAudio]
    4172                             .av_stream_index;
    4173                         audSubIdx = selectedTrack[kTrackTypeAudio]
    4174                             .av_substream_index;
    4175                     }
    4176 
    4177                     if (!(decodetype & kDecodeAudio) ||
    4178                         (pkt->stream_index != audIdx))
    4179                     {
    4180                         ptr += len;
    4181                         len = 0;
    4182                         continue;
    4183                     }
    4184 
    4185                     if (firstloop && pkt->pts != (int64_t)AV_NOPTS_VALUE)
    4186                         lastapts = (long long)(av_q2d(curstream->time_base) *
    4187                                                pkt->pts * 1000);
    4188 
    4189                     if (skipaudio)
    4190                     {
    4191                         if ((lastapts < lastvpts - (10.0 / fps)) ||
    4192                             lastvpts == 0)
    4193                         {
    4194                             ptr += len;
    4195                             len = 0;
    4196                             continue;
    4197                         }
    4198                         else
    4199                             skipaudio = false;
    4200                     }
    4201 
    4202                     avcodeclock->lock();
    4203                     data_size = 0;
    4204 
    4205                     if (audioOut.do_passthru)
    4206                     {
    4207                         data_size = pkt->size;
    4208                         dts = CODEC_ID_DTS == curstream->codec->codec_id;
    4209                         ret = encode_frame(dts, ptr, len,
    4210                                            audioSamples, data_size);
    4211                         s = (char *)audioSamples;
    4212                     }
    4213                     else
    4214                     {
    4215                         AVCodecContext *ctx = curstream->codec;
    4216 
    4217                         if ((ctx->channels == 0) ||
    4218                             (ctx->channels > audioOut.channels))
    4219                         {
    4220                             ctx->channels = audioOut.channels;
    4221                         }
    4222 
    4223                         if (!already_decoded)
    4224                         {
    4225                             curstream->codec->request_channels =
    4226                                 audioOut.channels;
    4227                             data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
    4228                             ret = avcodec_decode_audio2(ctx, audioSamples,
    4229                                                         &data_size, ptr, len);
    4230                         }
    4231 
    4232                             // Convert sample format if required (Myth only handles 8 and 16 bits audio)
    4233                         if (ctx->sample_fmt != SAMPLE_FMT_S16 && ctx->sample_fmt != SAMPLE_FMT_U8)
    4234                         {
    4235                             if (audio_src_fmt != ctx->sample_fmt)
    4236                             {
    4237                                 if (reformat_ctx)
    4238                                     av_audio_convert_free(reformat_ctx);
    4239                                 reformat_ctx = av_audio_convert_alloc(SAMPLE_FMT_S16, 1,
    4240                                                                       ctx->sample_fmt, 1,
    4241                                                                       NULL, 0);
    4242                                 if (!reformat_ctx ||
    4243                                     (!audioSamplesResampled &&
    4244                                     !(audioSamplesResampled = (short int *)av_mallocz(AVCODEC_MAX_AUDIO_FRAME_SIZE *
    4245                                                                                       sizeof(*audioSamplesResampled)))))
    4246                                 {
    4247                                     VERBOSE(VB_PLAYBACK, QString("Cannot convert %1 sample format to %2 sample format")
    4248                                             .arg(avcodec_get_sample_fmt_name(ctx->sample_fmt))
    4249                                             .arg(avcodec_get_sample_fmt_name(SAMPLE_FMT_S16)));
    4250 
    4251                                     avcodeclock->unlock();
    4252                                     have_err = true;
    4253                                     continue;
    4254                                 }
    4255                                 audio_src_fmt = ctx->sample_fmt;
    4256                             }
    4257                         }
    4258 
    4259                         if (reformat_ctx)
    4260                         {
    4261                             const void *ibuf[6] = {audioSamples};
    4262                             void *obuf[6] = {audioSamplesResampled};
    4263                             int istride[6] = {av_get_bits_per_sample_format(ctx->sample_fmt)/8};
    4264                             int ostride[6] = {2};
    4265                             int len = data_size/istride[0];
    4266                             if (av_audio_convert(reformat_ctx, obuf, ostride,
    4267                                                  ibuf, istride, len) < 0)
    4268                             {
    4269                                 VERBOSE(VB_PLAYBACK, "av_audio_convert() failed");
    4270 
    4271                                 avcodeclock->unlock();
    4272                                 have_err = true;
    4273                                 continue;
    4274                             }
    4275 
    4276                             data_size = len * 2;
    4277                             s = (char *)audioSamplesResampled;
    4278                         }
    4279                         else
    4280                             s = (char *)audioSamples;
    4281 
    4282                         // When decoding some audio streams the number of
    4283                         // channels, etc isn't known until we try decoding it.
    4284                         if ((ctx->sample_rate != audioOut.sample_rate) ||
    4285                             (ctx->channels    != audioOut.channels))
    4286                         {
    4287                             VERBOSE(VB_IMPORTANT, "audio stream changed");
    4288                             currentTrack[kTrackTypeAudio] = -1;
    4289                             selectedTrack[kTrackTypeAudio]
    4290                                 .av_stream_index = -1;
    4291                             audIdx = -1;
    4292                             AutoSelectAudioTrack();
    4293                             data_size = 0;
    4294                         }
    4295                     }
    4296                     avcodeclock->unlock();
    4297 
    4298                     if (ret < 0)
    4299                     {
    4300                         if (!dts)
    4301                         {
    4302                             VERBOSE(VB_IMPORTANT, LOC_ERR +
    4303                                     "Unknown audio decoding error");
    4304                         }
    4305                         have_err = true;
    4306                         continue;
    4307                     }
    4308 
    4309                     if (data_size <= 0)
    4310                     {
    4311                         ptr += ret;
    4312                         len -= ret;
    4313                         continue;
    4314                     }
    4315 
    4316                     long long temppts = lastapts;
    4317 
    4318                     // calc for next frame
    4319                     lastapts += (long long)((double)(data_size * 1000) /
    4320                                 (curstream->codec->channels * 2) /
    4321                                 curstream->codec->sample_rate);
    4322 
    4323                     VERBOSE(VB_PLAYBACK+VB_TIMESTAMP,
    4324                             LOC + QString("audio timecode %1 %2 %3 %4")
    4325                             .arg(pkt->pts).arg(pkt->dts)
    4326                             .arg(temppts).arg(lastapts));
    4327 
    4328                     if (audSubIdx != -1)
    4329                     {
    4330                         extract_mono_channel(audSubIdx, &audioOut,
    4331                                              s, data_size);
    4332                     }
    4333 
    4334                     GetNVP()->AddAudioData(s, data_size, temppts);
    4335 
    4336                     total_decoded_audio += data_size;
     4389                    int decoded;
     4390                    ret = ProcessAudioPacket(pkt, stream, ptr, len,
     4391                                             &decoded, firstloop);
     4392                    if (decoded <= 0)
     4393                        break;
    43374394
     4395                    total_decoded_audio += decoded;
    43384396                    allowedquit |= ringBuffer->InDVDMenuOrStillFrame();
    4339                     allowedquit |= !(decodetype & kDecodeVideo) &&
    4340                         (ofill + total_decoded_audio > othresh);
    4341 
    43424397                    // top off audio buffers initially in audio only mode
    4343                     if (!allowedquit && !(decodetype & kDecodeVideo))
    4344                     {
    4345                         uint fill, total;
    4346                         if (GetNVP()->GetAudioBufferStatus(fill, total))
    4347                         {
    4348                             total /= 6; // HACK needed for some audio files
    4349                             allowedquit =
    4350                                 (fill == 0) || (fill > (total>>1)) ||
    4351                                 ((total - fill) < (uint) data_size) ||
    4352                                 (ofill + total_decoded_audio > (total>>2)) ||
    4353                                 ((total - fill) < (uint) data_size * 2);
    4354                         }
    4355                         else
    4356                         {
    4357                             VERBOSE(VB_IMPORTANT, LOC_ERR +
    4358                                     "GetFrame() : Failed to top off "
    4359                                     "buffers in audio only mode");
    4360                         }
    4361                     }
    4362 
     4398                    if (!allowedquit && !wantvideo)
     4399                        allowedquit = TopUpAudioBuffer(decoded,
     4400                                                       total_decoded_audio,
     4401                                                       ofill, othresh);
    43634402                    break;
    4364                 }
    43654403                case CODEC_TYPE_VIDEO:
    43664404                {
    4367                     if (pkt->stream_index != selectedVideoIndex)
    4368                     {
    4369                         ptr += pkt->size;
    4370                         len -= pkt->size;
    4371                         continue;
    4372                     }
    4373 
    4374                     if (firstloop && pts != (int64_t) AV_NOPTS_VALUE)
    4375                     {
    4376                         lastccptsu = (long long)
    4377                             (av_q2d(curstream->time_base)*pkt->pts*1000000);
    4378                     }
    4379 
    4380                     if (!(decodetype & kDecodeVideo))
    4381                     {
    4382                         framesPlayed++;
    4383                         gotvideo = 1;
    4384                         ptr += pkt->size;
    4385                         len -= pkt->size;
    4386                         continue;
    4387                     }
    4388 
    4389                     AVCodecContext *context = curstream->codec;
    4390                     AVFrame mpa_pic;
    4391                     bzero(&mpa_pic, sizeof(AVFrame));
    4392 
    4393                     int gotpicture = 0;
    4394 
    4395                     avcodeclock->lock();
    4396                     if (d->HasDecoder())
    4397                     {
    4398                         if (decodeStillFrame)
    4399                         {
    4400                             int count = 0;
    4401                             // HACK
    4402                             while (!gotpicture && count < 5)
    4403                             {
    4404                                 ret = d->DecodeMPEG2Video(context, &mpa_pic,
    4405                                                   &gotpicture, ptr, len);
    4406                                 count++;
    4407                             }
    4408                         }
    4409                         else
    4410                         {
    4411                             ret = d->DecodeMPEG2Video(context, &mpa_pic,
    4412                                                 &gotpicture, ptr, len);
    4413                         }
    4414                     }
    4415                     else
    4416                     {
    4417                         ret = avcodec_decode_video(context, &mpa_pic,
    4418                                                    &gotpicture, ptr, len);
    4419                         // Reparse it to not drop the DVD still frame
    4420                         if (decodeStillFrame)
    4421                             ret = avcodec_decode_video(context, &mpa_pic,
    4422                                                         &gotpicture, ptr, len);
    4423                     }
    4424                     avcodeclock->unlock();
    4425 
    4426                     if (ret < 0)
    4427                     {
    4428                         VERBOSE(VB_IMPORTANT, LOC_ERR +
    4429                                 "Unknown decoding error");
    4430                         have_err = true;
    4431                         continue;
    4432                     }
    4433 
    4434                     if (!gotpicture)
    4435                     {
    4436                         ptr += ret;
    4437                         len -= ret;
    4438                         continue;
    4439                     }
    4440 
    4441                     // Decode ATSC captions
    4442                     for (uint i = 0; i < (uint)mpa_pic.atsc_cc_len;
    4443                          i += ((mpa_pic.atsc_cc_buf[i] & 0x1f) * 3) + 2)
    4444                     {
    4445                         DecodeDTVCC(mpa_pic.atsc_cc_buf + i);
    4446                     }
    4447 
    4448                     // Decode DVB captions from MPEG user data
    4449                     if (mpa_pic.dvb_cc_len > 0)
    4450                     {
    4451                         unsigned long long utc = lastccptsu;
    4452 
    4453                         for (uint i = 0; i < (uint)mpa_pic.dvb_cc_len; i += 2)
    4454                         {
    4455                             uint8_t cc_lo = mpa_pic.dvb_cc_buf[i];
    4456                             uint8_t cc_hi = mpa_pic.dvb_cc_buf[i+1];
     4405                    ret = ProcessVideoPacket(pkt, stream, pts, firstloop);
     4406                    break;
     4407                }
     4408                case CODEC_TYPE_SUBTITLE:
     4409                {
     4410                    ret = ProcessSubtitlePacket(pkt, stream, pts);
     4411                    break;
     4412                }
     4413                default:
     4414                {
     4415                    VERBOSE(VB_IMPORTANT, LOC_ERR +
     4416                            QString("Decoding - id(%1) type(%2)")
     4417                                .arg(codec_id_string(ctx->codec_id))
     4418                                .arg(codec_type_string(ctx->codec_type)));
     4419                    ret = len;
     4420                    break;
     4421                }
     4422            }
     4423            ptr += ret;
     4424            len -= ret;
     4425            firstloop = false;
     4426        }
     4427        av_free_packet(pkt);
     4428    }
    44574429
    4458                             uint16_t cc_dt = (cc_hi << 8) | cc_lo;
     4430    if (pkt)
     4431        delete pkt;
    44594432
    4460                             if (cc608_good_parity(cc608_parity_table, cc_dt))
    4461                             {
    4462                                 ccd608->FormatCCField(utc/1000, 0, cc_dt);
    4463                                 utc += 33367;
    4464                             }
    4465                         }
    4466                         lastccptsu = utc;
    4467                         UpdateCaptionTracksFromStreams(true, false);
    4468                     }
     4433    return true;
     4434}
    44694435
    4470                     VideoFrame *picframe = (VideoFrame *)(mpa_pic.opaque);
     4436bool AvFormatDecoder::UpdateDVDStatus()
     4437{
     4438    int dvdtitle          = 0;
     4439    int dvdpart           = 0;
     4440    bool cellChanged      = ringBuffer->DVD()->CellChanged();
     4441    bool inDVDStill       = ringBuffer->DVD()->InStillFrame();
     4442    bool inDVDMenu        = ringBuffer->DVD()->IsInMenu();
     4443    int storedPktCount    = storedPackets.count();
     4444    bool storevideoframes = false;
     4445    selectedVideoIndex    = 0;
    44714446
    4472                     if (!directrendering)
    4473                     {
    4474                         AVPicture tmppicture;
    4475 
    4476                         VideoFrame *xf = picframe;
    4477                         picframe = GetNVP()->GetNextVideoFrame(false);
    4478 
    4479                         unsigned char *buf = picframe->buf;
    4480                         tmppicture.data[0] = buf + picframe->offsets[0];
    4481                         tmppicture.data[1] = buf + picframe->offsets[1];
    4482                         tmppicture.data[2] = buf + picframe->offsets[2];
    4483                         tmppicture.linesize[0] = picframe->pitches[0];
    4484                         tmppicture.linesize[1] = picframe->pitches[1];
    4485                         tmppicture.linesize[2] = picframe->pitches[2];
    4486 
    4487                         myth_sws_img_convert(
    4488                             &tmppicture, PIX_FMT_YUV420P,
    4489                                     (AVPicture *)&mpa_pic,
    4490                                     context->pix_fmt,
    4491                                     context->width,
    4492                                     context->height);
    4493 
    4494                         if (xf)
    4495                         {
    4496                             // Set the frame flags, but then discard it
    4497                             // since we are not using it for display.
    4498                             xf->interlaced_frame = mpa_pic.interlaced_frame;
    4499                             xf->top_field_first = mpa_pic.top_field_first;
    4500                             xf->frameNumber = framesPlayed;
    4501                             GetNVP()->DiscardVideoFrame(xf);
    4502                         }
    4503                     }
     4447    ringBuffer->DVD()->GetPartAndTitle(dvdpart, dvdtitle);
    45044448
    4505                     long long temppts = pts;
     4449    if (dvdTitleChanged)
     4450    {
     4451        if ((storedPktCount > 10 && !decodeStillFrame) || decodeStillFrame)
     4452        {
     4453            storevideoframes = dvdTitleChanged = false;
     4454            ScanStreams(true);
     4455        }
     4456        else
     4457            storevideoframes = true;
     4458    }
     4459    else
     4460    {
     4461        storevideoframes = false;
    45064462
    4507                     // Validate the video pts against the last pts. If it's
    4508                     // a little bit smaller, equal or not available, compute
    4509                     // it from the last. Otherwise assume a wraparound.
    4510                     if (!ringBuffer->isDVD() &&
    4511                         temppts <= lastvpts &&
    4512                         (temppts + 10000 > lastvpts || temppts <= 0))
    4513                     {
    4514                         temppts = lastvpts;
    4515                         temppts += (long long)(1000 / fps);
    4516                         // MPEG2/H264 frames can be repeated, update pts accordingly
    4517                         temppts += (long long)(mpa_pic.repeat_pict * 500 / fps);
    4518                     }
     4463        if (storedPktCount < 2 && !decodeStillFrame)
     4464            storevideoframes = true;
    45194465
    4520                     VERBOSE(VB_PLAYBACK+VB_TIMESTAMP, LOC +
    4521                             QString("video timecode %1 %2 %3 %4")
    4522                             .arg(pkt->pts).arg(pkt->dts).arg(temppts)
    4523                             .arg(lastvpts));
     4466        VERBOSE(VB_PLAYBACK+VB_EXTRA, QString("DVD Playback Debugging "
     4467            "inDVDMenu %1 storedPacketcount %2 dvdstill %3")
     4468            .arg(inDVDMenu).arg(storedPktCount).arg(inDVDStill));
    45244469
    4525 /* XXX: Broken.
    4526                     if (mpa_pic.qscale_table != NULL && mpa_pic.qstride > 0 &&
    4527                         context->height == picframe->height)
    4528                     {
    4529                         int tblsize = mpa_pic.qstride *
    4530                                       ((picframe->height + 15) / 16);
     4470        if (inDVDStill && storedPktCount == 0 &&
     4471            GetNVP()->getVideoOutput()->ValidVideoFrames() == 0)
     4472        {
     4473            ringBuffer->DVD()->RunSeekCellStart();
     4474        }
     4475    }
    45314476
    4532                         if (picframe->qstride != mpa_pic.qstride ||
    4533                             picframe->qscale_table == NULL)
    4534                         {
    4535                             picframe->qstride = mpa_pic.qstride;
    4536                             if (picframe->qscale_table)
    4537                                 delete [] picframe->qscale_table;
    4538                             picframe->qscale_table = new unsigned char[tblsize];
    4539                         }
     4477    if (GetNVP()->AtNormalSpeed() && (cellChanged || lastdvdtitle != dvdtitle))
     4478    {
     4479        if (dvdtitle != lastdvdtitle)
     4480        {
     4481            VERBOSE(VB_PLAYBACK, LOC + "DVD Title Changed");
     4482            lastdvdtitle = dvdtitle;
     4483            if (lastdvdtitle != -1)
     4484                dvdTitleChanged = true;
     4485            if (GetNVP() && GetNVP()->getVideoOutput())
     4486            {
     4487                if (ringBuffer->DVD()->InStillFrame())
     4488                    GetNVP()->getVideoOutput()->SetPrebuffering(false);
     4489                else
     4490                    GetNVP()->getVideoOutput()->SetPrebuffering(true);
     4491            }
     4492        }
    45404493
    4541                         memcpy(picframe->qscale_table, mpa_pic.qscale_table,
    4542                                tblsize);
    4543                     }
    4544 */
     4494        if (ringBuffer->DVD()->PGCLengthChanged())
     4495        {
     4496            {
     4497                QMutexLocker locker(&m_positionMapLock);
     4498                posmapStarted = false;
     4499                m_positionMap.clear();
     4500            }
     4501            SyncPositionMap();
     4502        }
    45454503
    4546                     picframe->interlaced_frame = mpa_pic.interlaced_frame;
    4547                     picframe->top_field_first = mpa_pic.top_field_first;
    4548                     picframe->repeat_pict = mpa_pic.repeat_pict;
     4504        UpdateDVDFramesPlayed();
     4505        VERBOSE(VB_PLAYBACK, QString(LOC + "DVD Cell Changed. "
     4506                                     "Update framesPlayed: %1")
     4507                                     .arg(framesPlayed));
     4508    }
    45494509
    4550                     picframe->frameNumber = framesPlayed;
    4551                     GetNVP()->ReleaseNextVideoFrame(picframe, temppts);
    4552                     if (d->HasMPEG2Dec() && mpa_pic.data[3])
    4553                         context->release_buffer(context, &mpa_pic);
     4510    return storevideoframes;
     4511}
    45544512
    4555                     decoded_video_frame = picframe;
    4556                     gotvideo = 1;
    4557                     framesPlayed++;
     4513bool AvFormatDecoder::PreProcessDVDVideoPacket(AVPacket *pkt, AVStream *stream)
     4514{
    45584515
    4559                     lastvpts = temppts;
    4560                     break;
    4561                 }
    4562                 case CODEC_TYPE_SUBTITLE:
    4563                 {
    4564                     int gotSubtitles = 0;
    4565                     AVSubtitle subtitle;
    4566                     memset(&subtitle, 0, sizeof(AVSubtitle));
     4516    MpegPreProcessPkt(stream, pkt);
    45674517
    4568                     if (ringBuffer->isDVD())
    4569                     {
    4570                         if (ringBuffer->DVD()->NumMenuButtons() > 0)
    4571                         {
    4572                             ringBuffer->DVD()->GetMenuSPUPkt(ptr, len,
    4573                                                              curstream->id);
    4574                         }
    4575                         else
    4576                         {
    4577                             if (pkt->stream_index == subIdx)
    4578                             {
    4579                                 QMutexLocker locker(avcodeclock);
    4580                                 ringBuffer->DVD()->DecodeSubtitles(&subtitle,
    4581                                                                    &gotSubtitles,
    4582                                                                    ptr, len);
    4583                             }
    4584                         }
    4585                     }
    4586                     else if (pkt->stream_index == subIdx)
    4587                     {
    4588                         QMutexLocker locker(avcodeclock);
    4589                         avcodec_decode_subtitle(curstream->codec,
    4590                                                 &subtitle, &gotSubtitles,
    4591                                                 ptr, len);
    4592                     }
     4518    if (mpeg_seq_end_seen)
     4519        ringBuffer->DVD()->InStillFrame(true);
    45934520
    4594                     // the subtitle decoder always consumes the whole packet
    4595                     ptr += len;
    4596                     len = 0;
     4521    bool inDVDStill = ringBuffer->DVD()->InStillFrame();
    45974522
    4598                     if (gotSubtitles)
    4599                     {
    4600                         subtitle.start_display_time += pts;
    4601                         subtitle.end_display_time += pts;
    4602                         GetNVP()->AddAVSubtitle(subtitle);
    4603 
    4604                         VERBOSE(VB_PLAYBACK|VB_TIMESTAMP, LOC +
    4605                                 QString("subtl timecode %1 %2 %3 %4")
    4606                                 .arg(pkt->pts).arg(pkt->dts)
    4607                                 .arg(subtitle.start_display_time)
    4608                                 .arg(subtitle.end_display_time));
    4609                     }
     4523    VERBOSE(VB_PLAYBACK+VB_EXTRA,
     4524            QString("DVD Playback Debugging: mpeg seq end %1 inDVDStill %2 "
     4525                    "decodeStillFrame %3")
     4526                .arg(mpeg_seq_end_seen).arg(inDVDStill).arg(decodeStillFrame));
    46104527
    4611                     break;
    4612                 }
    4613                 default:
    4614                 {
    4615                     AVCodecContext *enc = curstream->codec;
    4616                     VERBOSE(VB_IMPORTANT, LOC_ERR +
    4617                             QString("Decoding - id(%1) type(%2)")
    4618                             .arg(codec_id_string(enc->codec_id))
    4619                             .arg(codec_type_string(enc->codec_type)));
    4620                     have_err = true;
    4621                     break;
    4622                 }
    4623             }
     4528    if (!decodeStillFrame && inDVDStill)
     4529    {
     4530        decodeStillFrame = true;
     4531        d->ResetMPEG2();
     4532    }
    46244533
    4625             if (!have_err)
     4534    if (!d->HasMPEG2Dec())
     4535    {
     4536        int current_width = stream->codec->width;
     4537        int video_width   = GetNVP()->GetVideoSize().width();
     4538        if (dvd_xvmc_enabled && GetNVP() && GetNVP()->getVideoOutput())
     4539        {
     4540            bool dvd_xvmc_active = codec_is_xvmc(video_codec_id);
     4541            bool indvdmenu       = ringBuffer->InDVDMenuOrStillFrame();
     4542            if ((indvdmenu && dvd_xvmc_active) ||
     4543                ((!indvdmenu && !dvd_xvmc_active)))
    46264544            {
    4627                 ptr += ret;
    4628                 len -= ret;
    4629                 frame_decoded = 1;
    4630                 firstloop = false;
     4545                VERBOSE(VB_PLAYBACK, LOC +
     4546                        QString("DVD Codec Change indvdmenu %1 "
     4547                                "dvd_xvmc_active %2")
     4548                                .arg(indvdmenu).arg(dvd_xvmc_active));
     4549                dvd_video_codec_changed = true;
    46314550            }
    46324551        }
    46334552
    4634         av_free_packet(pkt);
    4635     }
     4553        if (video_width > 0 && dvd_video_codec_changed)
     4554        {
     4555            VERBOSE(VB_PLAYBACK, LOC +
     4556                    QString("DVD Stream/Codec Change video_width %1 "
     4557                            "current_width %2 dvd_video_codec_changed %3")
     4558                            .arg(video_width).arg(current_width)
     4559                            .arg(dvd_video_codec_changed));
    46364560
    4637     if (pkt)
    4638         delete pkt;
     4561            av_free_packet(pkt);
     4562            if (current_width > 0) {
     4563                CloseCodecs();
     4564                ScanStreams(false);
     4565                allowedquit = true;
     4566                dvd_video_codec_changed = false;
     4567            }
     4568            return false;
     4569        }
     4570    }
    46394571
    46404572    return true;
    46414573}
    bool AvFormatDecoder::SetupAudioStream(void)  
    48964828    return true;
    48974829}
    48984830
     4831char* AvFormatDecoder::ConvertSampleFormat(const AVCodecContext *ctx,
     4832                                           int *decoded)
     4833{
     4834    if (audio_src_fmt != ctx->sample_fmt)
     4835    {
     4836        if (reformat_ctx)
     4837            av_audio_convert_free(reformat_ctx);
     4838        reformat_ctx = av_audio_convert_alloc(SAMPLE_FMT_S16, 1,
     4839                                              ctx->sample_fmt, 1, NULL, 0);
     4840
     4841        if (!reformat_ctx ||
     4842            (!audioSamplesResampled &&
     4843             !(audioSamplesResampled =
     4844                (short int *)av_mallocz(AVCODEC_MAX_AUDIO_FRAME_SIZE *
     4845                                        sizeof(*audioSamplesResampled)))))
     4846        {
     4847            VERBOSE(VB_PLAYBACK,
     4848                QString("Cannot convert %1 sample format to %2 sample format")
     4849                    .arg(avcodec_get_sample_fmt_name(ctx->sample_fmt))
     4850                    .arg(avcodec_get_sample_fmt_name(SAMPLE_FMT_S16)));
     4851            return NULL;
     4852        }
     4853
     4854        audio_src_fmt = ctx->sample_fmt;
     4855    }
     4856
     4857    if (reformat_ctx)
     4858    {
     4859        const void *ibuf[6] = {audioSamples};
     4860        void *obuf[6]       = {audioSamplesResampled};
     4861        int is[6]         = {av_get_bits_per_sample_format(ctx->sample_fmt)>>3};
     4862        int os[6]           = {2};
     4863        int samples         = *decoded / is[0];
     4864
     4865        if (av_audio_convert(reformat_ctx, obuf, os, ibuf, is, samples) < 0)
     4866        {
     4867            VERBOSE(VB_PLAYBACK, "av_audio_convert() failed");
     4868            return NULL;
     4869        }
     4870
     4871        *decoded = samples << 1;
     4872        return (char *)audioSamplesResampled;
     4873    }
     4874
     4875    return NULL;
     4876}
     4877
    48994878static int encode_frame(bool dts, unsigned char *data, int len,
    49004879                        short *samples, int &samples_size)
    49014880{
  • mythtv/libs/libmythtv/avformatdecoder.h

    diff --git a/mythtv/libs/libmythtv/avformatdecoder.h b/mythtv/libs/libmythtv/avformatdecoder.h
    index 789c8b8..63033b5 100644
    a b class AvFormatDecoder : public DecoderBase  
    9090
    9191    /// Perform an av_probe_input_format on the passed data to see if we
    9292    /// can decode it with this class.
    93     static bool CanHandle(char testbuf[kDecoderProbeBufferSize], 
     93    static bool CanHandle(char testbuf[kDecoderProbeBufferSize],
    9494                          const QString &filename,
    9595                          int testbufsize = kDecoderProbeBufferSize);
    9696
    9797    /// Open our file and set up or audio and video parameters.
    98     int OpenFile(RingBuffer *rbuffer, bool novideo, 
     98    int OpenFile(RingBuffer *rbuffer, bool novideo,
    9999                 char testbuf[kDecoderProbeBufferSize],
    100100                 int testbufsize = kDecoderProbeBufferSize);
    101101
    class AvFormatDecoder : public DecoderBase  
    189189    /// Preprocess a packet, setting the video parms if necessary.
    190190    void MpegPreProcessPkt(AVStream *stream, AVPacket *pkt);
    191191    bool H264PreProcessPkt(AVStream *stream, AVPacket *pkt);
     192    bool PreProcessVideoPacket(AVPacket *pkt, AVStream *stream);
     193    int  ProcessVideoPacket(const AVPacket *pkt, const AVStream *stream,
     194                            long long pts, bool firstloop);
     195    int  ProcessAudioPacket(const AVPacket *pkt, const AVStream *stream,
     196                            uchar *ptr, int len, int *decoded, bool firstloop);
     197    bool TopUpAudioBuffer(int decoded, uint total_decoded, uint ofill, uint othresh);
    192198
    193199    void ProcessVBIDataPacket(const AVStream *stream, const AVPacket *pkt);
    194200    void ProcessDVBDataPacket(const AVStream *stream, const AVPacket *pkt);
    195201    void ProcessDSMCCPacket(const AVStream *stream, const AVPacket *pkt);
     202    int  ProcessSubtitlePacket(const AVPacket *pkt, const AVStream *stream, long long pts);
     203    bool ProcessDataPacket(AVPacket *pkt, const AVStream *stream);
    196204
    197205    float GetMpegAspect(AVCodecContext *context, int aspect_ratio_info,
    198206                        int width, int height);
    class AvFormatDecoder : public DecoderBase  
    201209
    202210    bool DoPassThrough(const AVCodecContext *ctx);
    203211    bool SetupAudioStream(void);
     212    char *ConvertSampleFormat(const AVCodecContext *ctx, int *decoded);
    204213    void SetupAudioStreamSubIndexes(int streamIndex);
    205214    void RemoveAudioStreams();
    206215
    class AvFormatDecoder : public DecoderBase  
    209218    void HandleGopStart(AVPacket *pkt, bool can_reliably_parse_keyframes);
    210219
    211220    bool GenerateDummyVideoFrame(void);
     221    AVPacket *GetPacket(AVPacket *pkt, bool storevideoframes);
     222    bool UpdateDVDStatus(void);
     223    bool PreProcessDVDVideoPacket(AVPacket *pkt, AVStream *stream);
    212224    bool HasVideo(const AVFormatContext *ic);
    213225
    214226  private:
    class AvFormatDecoder : public DecoderBase  
    228240    AVFRingBuffer *avfRingBuffer;
    229241
    230242    bool directrendering;
    231     bool drawband;
    232243
    233244    bool no_dts_hack;
    234245    bool dorewind;
    class AvFormatDecoder : public DecoderBase  
    240251
    241252    QList<AVPacket*> storedPackets;
    242253
    243     int firstgoppos;
    244254    int prevgoppos;
    245255
     256    bool wantaudio;
     257    bool wantvideo;
    246258    bool gotvideo;
     259    bool skipaudio;
     260
     261    bool allowedquit;
    247262
    248263    uint32_t  start_code_state;
    249264