Ticket #8318: getframe.2.patch

File getframe.2.patch, 67.8 KB (added by JYA, 14 years ago)

Updated for trunk r24111 ; remove whitespace only changes

  • mythtv/libs/libmythtv/avformatdecoder.cpp

    diff --git a/mythtv/libs/libmythtv/avformatdecoder.cpp b/mythtv/libs/libmythtv/avformatdecoder.cpp
    a b  
    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),
     
    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),
     
    13551356    return fmt[i];
    13561357}
    13571358
    1358 static bool IS_DR1_PIX_FMT(const enum PixelFormat fmt)
    1359 {
    1360     switch (fmt)
    1361     {
    1362     case PIX_FMT_YUV420P:
    1363     case PIX_FMT_YUVJ420P:
    1364         return true;
    1365     default:
    1366         return false;
    1367     }
    1368 }
    1369 
    13701359void AvFormatDecoder::InitVideoCodec(AVStream *stream, AVCodecContext *enc,
    13711360                                     bool selectedStream)
    13721361{
     
    14611450        enc->slice_flags     = SLICE_FLAG_CODED_ORDER | SLICE_FLAG_ALLOW_FIELD;
    14621451        directrendering     |= selectedStream;
    14631452    }
    1464     else if (codec && codec->capabilities & CODEC_CAP_DR1 &&
    1465              IS_DR1_PIX_FMT(enc->pix_fmt))
     1453    else if (codec && codec->capabilities & CODEC_CAP_DR1)
    14661454    {
    14671455        enc->flags          |= CODEC_FLAG_EMU_EDGE;
    14681456        enc->get_buffer      = get_avf_buffer;
     
    24462434    VideoFrame *frame = nd->GetNVP()->GetNextVideoFrame(true);
    24472435
    24482436    if (!frame)
    2449         return -1;
     2437        return 0;
    24502438
    24512439    for (int i = 0; i < 3; i++)
    24522440    {
     
    24592447
    24602448    pic->age = 256 * 256 * 256 * 64;
    24612449
    2462     return 0;
     2450    return 1;
    24632451}
    24642452
    24652453/** \brief remove audio streams from the context
     
    25342522    render->next_free_data_block_num = 0;
    25352523#endif
    25362524
    2537     return 0;
     2525    return 1;
    25382526}
    25392527
    25402528void release_avf_buffer_xvmc(struct AVCodecContext *c, AVFrame *pic)
     
    31183106    return on_frame;
    31193107}
    31203108
     3109bool AvFormatDecoder::PreProcessVideoPacket(AVPacket *pkt, AVStream *stream)
     3110{
     3111
     3112    AVCodecContext *ctx = stream->codec;
     3113    bool on_frame = true;
     3114
     3115    if (CODEC_IS_FFMPEG_MPEG(ctx->codec_id))
     3116    {
     3117        if (!ringBuffer->isDVD())
     3118            MpegPreProcessPkt(stream, pkt);
     3119    }
     3120    else if (CODEC_IS_H264(ctx->codec_id))
     3121        on_frame = H264PreProcessPkt(stream, pkt);
     3122    else
     3123    {
     3124        if (pkt->flags & PKT_FLAG_KEY)
     3125        {
     3126            HandleGopStart(pkt, false);
     3127            seen_gop = true;
     3128        }
     3129        else
     3130        {
     3131            seq_count++;
     3132            if (!seen_gop && seq_count > 1)
     3133                HandleGopStart(pkt, false);
     3134        }
     3135    }
     3136
     3137    if (framesRead == 0 && !justAfterChange && !(pkt->flags & PKT_FLAG_KEY))
     3138    {
     3139        av_free_packet(pkt);
     3140        return false;
     3141    }
     3142
     3143    if (on_frame)
     3144        framesRead++;
     3145    justAfterChange = false;
     3146
     3147    if (exitafterdecoded)
     3148        gotvideo = 1;
     3149
     3150    return true;
     3151}
     3152
     3153int AvFormatDecoder::ProcessVideoPacket(const AVPacket *pkt,
     3154                                        const AVStream *stream,
     3155                                        long long pts,  bool firstloop)
     3156{
     3157    AVCodecContext *ctx = stream->codec;
     3158    uchar *ptr          = pkt->data;
     3159    int len             = pkt->size;
     3160    int ret             = 0;
     3161
     3162    if (pkt->stream_index != selectedVideoIndex)
     3163        return len;
     3164
     3165    if (firstloop && pts != (int64_t) AV_NOPTS_VALUE)
     3166        lastccptsu = (long long)
     3167            (av_q2d(stream->time_base) * pkt->pts * 1000000);
     3168
     3169    if (!wantvideo)
     3170    {
     3171        framesPlayed++;
     3172        gotvideo = 1;
     3173        return len;
     3174    }
     3175
     3176    AVFrame mpa_pic;
     3177    bzero(&mpa_pic, sizeof(AVFrame));
     3178
     3179    int gotpicture = 0;
     3180
     3181    avcodeclock->lock();
     3182    if (d->HasDecoder())
     3183    {
     3184        if (decodeStillFrame)
     3185        {
     3186            int count = 0;
     3187            // HACK
     3188            while (!gotpicture && count < 5)
     3189            {
     3190                ret = d->DecodeMPEG2Video(ctx, &mpa_pic, &gotpicture, ptr, len);
     3191                count++;
     3192            }
     3193        }
     3194        else
     3195            ret = d->DecodeMPEG2Video(ctx, &mpa_pic, &gotpicture, ptr, len);
     3196    }
     3197    else
     3198    {
     3199        ret = avcodec_decode_video(ctx, &mpa_pic, &gotpicture, ptr, len);
     3200        // Reparse it to not drop the DVD still frame
     3201        if (decodeStillFrame)
     3202            ret = avcodec_decode_video(ctx, &mpa_pic, &gotpicture, ptr, len);
     3203    }
     3204    avcodeclock->unlock();
     3205
     3206    if (ret < 0)
     3207    {
     3208        VERBOSE(VB_IMPORTANT, LOC_ERR + "Unknown decoding error");
     3209        return len;
     3210    }
     3211
     3212    if (!gotpicture)
     3213        return len;
     3214
     3215    // Decode CEA-608 and CEA-708 captions
     3216    for (uint i = 0; i < (uint)mpa_pic.atsc_cc_len;
     3217         i += ((mpa_pic.atsc_cc_buf[i] & 0x1f) * 3) + 2)
     3218        DecodeDTVCC(mpa_pic.atsc_cc_buf + i, mpa_pic.atsc_cc_len - i);
     3219
     3220    VideoFrame *picframe = (VideoFrame *)(mpa_pic.opaque);
     3221
     3222    if (!directrendering)
     3223    {
     3224        AVPicture tmppicture;
     3225
     3226        VideoFrame *xf = picframe;
     3227        picframe = GetNVP()->GetNextVideoFrame(false);
     3228
     3229        unsigned char *buf     = picframe->buf;
     3230        tmppicture.data[0]     = buf + picframe->offsets[0];
     3231        tmppicture.data[1]     = buf + picframe->offsets[1];
     3232        tmppicture.data[2]     = buf + picframe->offsets[2];
     3233        tmppicture.linesize[0] = picframe->pitches[0];
     3234        tmppicture.linesize[1] = picframe->pitches[1];
     3235        tmppicture.linesize[2] = picframe->pitches[2];
     3236
     3237        myth_sws_img_convert(&tmppicture, PIX_FMT_YUV420P,
     3238                             (AVPicture *)&mpa_pic,
     3239                             ctx->pix_fmt, ctx->width, ctx->height);
     3240
     3241        if (xf)
     3242        {
     3243            // Set the frame flags, but then discard it
     3244            // since we are not using it for display.
     3245            xf->interlaced_frame = mpa_pic.interlaced_frame;
     3246            xf->top_field_first = mpa_pic.top_field_first;
     3247            xf->frameNumber = framesPlayed;
     3248            GetNVP()->DiscardVideoFrame(xf);
     3249        }
     3250    }
     3251
     3252    long long temppts = pts;
     3253
     3254    // Validate the video pts against the last pts. If it's
     3255    // a little bit smaller, equal or not available, compute
     3256    // it from the last. Otherwise assume a wraparound.
     3257    if (!ringBuffer->isDVD() && temppts <= lastvpts &&
     3258        (temppts + 10000 > lastvpts || temppts <= 0))
     3259    {
     3260        temppts = lastvpts;
     3261        temppts += (long long)(1000 / fps);
     3262        // MPEG2/H264 frames can be repeated, update pts accordingly
     3263        temppts += (long long)(mpa_pic.repeat_pict * 500 / fps);
     3264    }
     3265
     3266    VERBOSE(VB_PLAYBACK+VB_TIMESTAMP, LOC +
     3267                QString("video timecode %1 %2 %3 %4")
     3268                .arg(pkt->pts).arg(pkt->dts).arg(temppts).arg(lastvpts));
     3269
     3270/* XXX: Broken.
     3271    if (mpa_pic.qscale_table != NULL && mpa_pic.qstride > 0 &&
     3272        context->height == picframe->height)
     3273    {
     3274        int tblsize = mpa_pic.qstride *
     3275                      ((picframe->height + 15) / 16);
     3276
     3277        if (picframe->qstride != mpa_pic.qstride ||
     3278            picframe->qscale_table == NULL)
     3279        {
     3280            picframe->qstride = mpa_pic.qstride;
     3281            if (picframe->qscale_table)
     3282                delete [] picframe->qscale_table;
     3283            picframe->qscale_table = new unsigned char[tblsize];
     3284        }
     3285
     3286        memcpy(picframe->qscale_table, mpa_pic.qscale_table,
     3287               tblsize);
     3288    }
     3289*/
     3290
     3291    picframe->interlaced_frame = mpa_pic.interlaced_frame;
     3292    picframe->top_field_first  = mpa_pic.top_field_first;
     3293    picframe->repeat_pict      = mpa_pic.repeat_pict;
     3294    picframe->frameNumber      = framesPlayed;
     3295
     3296    GetNVP()->ReleaseNextVideoFrame(picframe, temppts);
     3297    if (d->HasMPEG2Dec() && mpa_pic.data[3])
     3298        ctx->release_buffer(ctx, &mpa_pic);
     3299
     3300    decoded_video_frame = picframe;
     3301    gotvideo            = true;
     3302    lastvpts            = temppts;
     3303    framesPlayed++;
     3304
     3305    return ret;
     3306
     3307}
     3308
     3309static void extract_mono_channel(uint channel, AudioInfo *audioInfo,
     3310                                 char *buffer, int bufsize)
     3311{
     3312    // Only stereo -> mono (left or right) is supported
     3313    if (audioInfo->channels != 2)
     3314        return;
     3315
     3316    if (channel >= (uint)audioInfo->channels)
     3317        return;
     3318
     3319    const uint samplesize = audioInfo->sample_size;
     3320    const uint samples    = bufsize / samplesize;
     3321    const uint halfsample = samplesize >> 1;
     3322
     3323    const char *from = (channel == 1) ? buffer + halfsample : buffer;
     3324    char *to         = (channel == 0) ? buffer + halfsample : buffer;
     3325
     3326    for (uint sample = 0; sample < samples;
     3327         (sample++), (from += samplesize), (to += samplesize))
     3328    {
     3329        memmove(to, from, halfsample);
     3330    }
     3331}
     3332
     3333int AvFormatDecoder::ProcessAudioPacket(const AVPacket *pkt,
     3334                                        const AVStream *stream,
     3335                                        uchar *ptr, int len, int &decoded,
     3336                                        bool firstloop)
     3337{
     3338    AVCodecContext *ctx     = stream->codec;
     3339    int ret                 = 0;
     3340    bool reselectAudioTrack = false, dts = false;
     3341    AC3HeaderInfo hdr;
     3342    char *s;
     3343
     3344    avcodeclock->lock();
     3345    int audIdx = selectedTrack[kTrackTypeAudio].av_stream_index;
     3346    int audSubIdx = selectedTrack[kTrackTypeAudio].av_substream_index;
     3347    avcodeclock->unlock();
     3348    /// HACK HACK HACK -- begin See #3731
     3349    if (!GetNVP()->HasAudioIn())
     3350    {
     3351        VERBOSE(VB_AUDIO, LOC + "Audio is disabled - trying to restart it");
     3352        reselectAudioTrack = true;
     3353    }
     3354    /// HACK HACK HACK -- end
     3355
     3356    // detect switches between stereo and dual languages
     3357    bool wasDual = audSubIdx != -1;
     3358    bool isDual  = ctx->avcodec_dual_language;
     3359    if ((wasDual && !isDual) || (!wasDual &&  isDual))
     3360    {
     3361        SetupAudioStreamSubIndexes(audIdx);
     3362        reselectAudioTrack = true;
     3363    }
     3364
     3365    // detect channels on streams that need
     3366    // to be decoded before we can know this
     3367    bool already_decoded = false;
     3368    if (!ctx->channels)
     3369    {
     3370        QMutexLocker locker(avcodeclock);
     3371        VERBOSE(VB_IMPORTANT,
     3372            LOC + QString("Setting channels to %1")
     3373                    .arg(audioOut.channels));
     3374
     3375        if (DoPassThrough(ctx))
     3376            ctx->channels = ctx->request_channels = 0;
     3377        else
     3378            ctx->channels = ctx->request_channels = audioOut.channels;
     3379
     3380        decoded = AVCODEC_MAX_AUDIO_FRAME_SIZE;
     3381        ret = avcodec_decode_audio2(ctx, audioSamples, &decoded, ptr, len);
     3382        already_decoded = true;
     3383        reselectAudioTrack |= ctx->channels;
     3384    }
     3385
     3386    if (ctx->codec_id == CODEC_ID_AC3)
     3387    {
     3388        GetBitContext gbc;
     3389        init_get_bits(&gbc, ptr, len << 3);
     3390        if (!ff_ac3_parse_header(&gbc, &hdr)   &&
     3391            hdr.channels != last_ac3_channels)
     3392        {
     3393            VERBOSE(VB_AUDIO, LOC +
     3394                QString("AC3 changed from %1 to %2 channels (frame %3)")
     3395                    .arg(last_ac3_channels).arg(hdr.channels).arg(framesRead));
     3396
     3397            if ((framesRead - last_framesRead) > AUDIOMAXFRAMES ||
     3398                hdr.channels < last_ac3_channels)
     3399            {
     3400                ctx->channels = hdr.channels;
     3401            }
     3402
     3403            last_ac3_channels = hdr.channels;
     3404            last_framesRead = framesRead;
     3405            SetupAudioStream();
     3406        }
     3407    }
     3408
     3409    if (reselectAudioTrack)
     3410    {
     3411        QMutexLocker locker(avcodeclock);
     3412        currentTrack[kTrackTypeAudio]                  = -1;
     3413        selectedTrack[kTrackTypeAudio].av_stream_index = -1;
     3414        audIdx = audSubIdx = -1;
     3415        AutoSelectAudioTrack();
     3416        audIdx    = selectedTrack[kTrackTypeAudio].av_stream_index;
     3417        audSubIdx = selectedTrack[kTrackTypeAudio].av_substream_index;
     3418    }
     3419
     3420    if (!wantaudio || pkt->stream_index != audIdx)
     3421    {
     3422        decoded = 0;
     3423        return len;
     3424    }
     3425
     3426    if (firstloop && pkt->pts != (int64_t)AV_NOPTS_VALUE)
     3427        lastapts = (long long)(av_q2d(stream->time_base) * pkt->pts * 1000);
     3428
     3429    if (skipaudio)
     3430    {
     3431        if ((lastapts < lastvpts - (10.0 / fps)) || lastvpts == 0)
     3432        {
     3433            decoded = 0;
     3434            return len;
     3435        }
     3436        else
     3437            skipaudio = false;
     3438    }
     3439
     3440    avcodeclock->lock();
     3441    decoded = 0;
     3442
     3443    if (audioOut.do_passthru)
     3444    {
     3445        decoded = pkt->size;
     3446        dts = CODEC_ID_DTS == ctx->codec_id;
     3447        ret = encode_frame(dts, ptr, len, audioSamples, decoded);
     3448        s = (char *)audioSamples;
     3449    }
     3450    else
     3451    {
     3452        if (!ctx->channels || ctx->channels > audioOut.channels)
     3453            ctx->channels = audioOut.channels;
     3454
     3455        if (!already_decoded)
     3456        {
     3457            ctx->request_channels = audioOut.channels;
     3458            decoded = AVCODEC_MAX_AUDIO_FRAME_SIZE;
     3459            ret = avcodec_decode_audio2(ctx, audioSamples, &decoded, ptr, len);
     3460        }
     3461
     3462        // Convert sample format if required (Myth only handles 8 and 16 bits audio)
     3463        if (ctx->sample_fmt == SAMPLE_FMT_S16 ||
     3464            ctx->sample_fmt == SAMPLE_FMT_U8  ||
     3465            (s = ConvertSampleFormat(ctx, decoded)) == NULL)
     3466        {
     3467            s = (char *)audioSamples;
     3468        }
     3469        // When decoding some audio streams the number of
     3470        // channels, etc isn't known until we try decoding it.
     3471        if ((ctx->sample_rate != audioOut.sample_rate) ||
     3472            (ctx->channels    != audioOut.channels))
     3473        {
     3474            VERBOSE(VB_IMPORTANT, LOC + "Audio stream changed");
     3475            currentTrack[kTrackTypeAudio]                  = -1;
     3476            selectedTrack[kTrackTypeAudio].av_stream_index = -1;
     3477            audIdx  = -1;
     3478            decoded =  0;
     3479            AutoSelectAudioTrack();
     3480        }
     3481    }
     3482    avcodeclock->unlock();
     3483
     3484    if (ret < 0)
     3485    {
     3486        if (!dts)
     3487            VERBOSE(VB_IMPORTANT, LOC_ERR + "Unknown audio decoding error");
     3488        decoded = 0;
     3489        return len;
     3490    }
     3491
     3492    if (decoded <= 0)
     3493        return ret;
     3494
     3495    long long temppts = lastapts;
     3496
     3497    // calc for next frame
     3498    lastapts += (long long)((double)(decoded * 1000) /
     3499                (ctx->sample_rate * ctx->channels *
     3500                 av_get_bits_per_sample_format(ctx->sample_fmt)>>3));
     3501
     3502    VERBOSE(VB_PLAYBACK+VB_TIMESTAMP,
     3503            LOC + QString("audio timecode %1 %2 %3 %4")
     3504                    .arg(pkt->pts).arg(pkt->dts).arg(temppts).arg(lastapts));
     3505
     3506    if (audSubIdx != -1)
     3507        extract_mono_channel(audSubIdx, &audioOut, s, decoded);
     3508
     3509    GetNVP()->AddAudioData(s, decoded, temppts);
     3510
     3511    return ret;
     3512
     3513}
     3514
     3515bool AvFormatDecoder::TopUpAudioBuffer(int decoded, uint total_decoded,
     3516                                       uint ofill,  uint othresh)
     3517{
     3518    uint fill, total;
     3519
     3520    if (ofill + total_decoded > othresh)
     3521        return true;
     3522
     3523    if (!GetNVP()->GetAudioBufferStatus(fill, total))
     3524    {
     3525        VERBOSE(VB_IMPORTANT, LOC_ERR + "GetFrame() : Failed to top off "
     3526                                        "buffers in audio only mode");
     3527        return false;
     3528    }
     3529
     3530    total /= 6; // HACK needed for some audio files
     3531    return (fill == 0) || (fill > (total>>1))    ||
     3532           ((total - fill) < (uint)decoded)      ||
     3533           (ofill + total_decoded > (total>>2))  ||
     3534           ((total - fill) < (uint)decoded * 2);
     3535}
     3536
    31213537/** \fn AvFormatDecoder::ProcessVBIDataPacket(const AVStream*, const AVPacket*)
    31223538 *  \brief Process ivtv proprietary embedded vertical blanking
    31233539 *         interval captions.
     
    32763692#endif // USING_MHEG
    32773693}
    32783694
     3695int AvFormatDecoder::ProcessSubtitlePacket(const AVPacket *pkt,
     3696                                           const AVStream *stream,
     3697                                           long long pts)
     3698{
     3699    uchar *ptr       = pkt->data;
     3700    int len          = pkt->size;
     3701    int gotSubtitles = 0;
     3702    AVSubtitle subtitle;
     3703    memset(&subtitle, 0, sizeof(AVSubtitle));
     3704    avcodeclock->lock();
     3705    int subIdx = selectedTrack[kTrackTypeSubtitle].av_stream_index;
     3706    avcodeclock->unlock();
     3707
     3708    if (ringBuffer->isDVD())
     3709    {
     3710        if (ringBuffer->DVD()->NumMenuButtons() > 0)
     3711            ringBuffer->DVD()->GetMenuSPUPkt(ptr, len, stream->id);
     3712        else
     3713        {
     3714            if (pkt->stream_index == subIdx)
     3715            {
     3716                QMutexLocker locker(avcodeclock);
     3717                ringBuffer->DVD()->DecodeSubtitles(&subtitle, &gotSubtitles,
     3718                                                   ptr, len);
     3719            }
     3720        }
     3721    }
     3722    else if (pkt->stream_index == subIdx)
     3723    {
     3724        QMutexLocker locker(avcodeclock);
     3725        avcodec_decode_subtitle(stream->codec, &subtitle, &gotSubtitles,
     3726                                ptr, len);
     3727    }
     3728
     3729    if (gotSubtitles)
     3730    {
     3731        subtitle.start_display_time += pts;
     3732        subtitle.end_display_time   += pts;
     3733        GetNVP()->AddAVSubtitle(subtitle);
     3734
     3735        VERBOSE(VB_PLAYBACK|VB_TIMESTAMP, LOC +
     3736                QString("subtl timecode %1 %2 %3 %4")
     3737                    .arg(pkt->pts).arg(pkt->dts)
     3738                    .arg(subtitle.start_display_time)
     3739                    .arg(subtitle.end_display_time));
     3740    }
     3741
     3742    return len;
     3743}
     3744
     3745bool AvFormatDecoder::ProcessDataPacket(AVPacket *pkt, const AVStream *stream)
     3746{
     3747    AVCodecContext *ctx = stream->codec;
     3748
     3749    if (ctx->codec_id == CODEC_ID_MPEG2VBI)
     3750    {
     3751        ProcessVBIDataPacket(stream, pkt);
     3752        av_free_packet(pkt);
     3753        return true;
     3754    }
     3755
     3756    if (ctx->codec_id == CODEC_ID_DVB_VBI ||
     3757        ctx->codec_id == CODEC_ID_DVB_TELETEXT)
     3758    {
     3759        ProcessDVBDataPacket(stream, pkt);
     3760        av_free_packet(pkt);
     3761        return true;
     3762    }
     3763
     3764#ifdef USING_MHEG
     3765    if (ctx->codec_id == CODEC_ID_DSMCC_B)
     3766    {
     3767        ProcessDSMCCPacket(stream, pkt);
     3768        av_free_packet(pkt);
     3769        // Have to return regularly to ensure that the OSD is updated.
     3770        // This applies both to MHEG and also channel browsing.
     3771        if (!wantvideo)
     3772        {
     3773            allowedquit |= (itv && itv->ImageHasChanged());
     3774            OSD *osd = NULL;
     3775            if (!allowedquit && GetNVP() && (osd = GetNVP()->GetOSD()))
     3776                allowedquit |= osd->HasChanged();
     3777        }
     3778        return true;
     3779    }
     3780#endif // USING_MHEG
     3781
     3782    // we don't care about other data streams
     3783    if (ctx->codec_type == CODEC_TYPE_DATA)
     3784    {
     3785        av_free_packet(pkt);
     3786        return true;
     3787    }
     3788
     3789    return false;
     3790}
     3791
    32793792int AvFormatDecoder::SetTrack(uint type, int trackNo)
    32803793{
    32813794    bool ret = DecoderBase::SetTrack(type, trackNo);
     
    36454158    return selTrack;
    36464159}
    36474160
    3648 static void extract_mono_channel(uint channel, AudioInfo *audioInfo,
    3649                                  char *buffer, int bufsize)
    3650 {
    3651     // Only stereo -> mono (left or right) is supported
    3652     if (audioInfo->channels != 2)
    3653         return;
    3654 
    3655     if (channel >= (uint)audioInfo->channels)
    3656         return;
    3657 
    3658     const uint samplesize = audioInfo->sample_size;
    3659     const uint samples    = bufsize / samplesize;
    3660     const uint halfsample = samplesize >> 1;
    3661 
    3662     const char *from = (channel == 1) ? buffer + halfsample : buffer;
    3663     char *to         = (channel == 0) ? buffer + halfsample : buffer;
    3664 
    3665     for (uint sample = 0; sample < samples;
    3666          (sample++), (from += samplesize), (to += samplesize))
    3667     {
    3668         memmove(to, from, halfsample);
    3669     }
     4161AVPacket* AvFormatDecoder::GetPacket(AVPacket *pkt, bool storevideoframes)
     4162{
     4163    if (!storevideoframes && storedPackets.count() > 0)
     4164    {
     4165        if (pkt)
     4166        {
     4167            av_free_packet(pkt);
     4168            delete pkt;
     4169        }
     4170        pkt = storedPackets.takeFirst();
     4171        return pkt;
     4172    }
     4173
     4174    if (!pkt)
     4175    {
     4176        pkt = new AVPacket;
     4177        bzero(pkt, sizeof(AVPacket));
     4178        av_init_packet(pkt);
     4179    }
     4180
     4181    if (!ic || (av_read_frame(ic, pkt) < 0))
     4182    {
     4183        ateof = true;
     4184        GetNVP()->SetEof();
     4185        delete pkt;
     4186        return NULL;
     4187    }
     4188
     4189    if (ringBuffer->isDVD() && ringBuffer->DVD()->InStillFrame())
     4190    {
     4191        AVStream *curstream = ic->streams[pkt->stream_index];
     4192        if (curstream && curstream->codec->codec_type == CODEC_TYPE_VIDEO)
     4193        {
     4194            mpeg_seq_end_seen = decodeStillFrame = false;
     4195            ringBuffer->DVD()->InStillFrame(false);
     4196        }
     4197    }
     4198
     4199    if (waitingForChange && pkt->pos >= readAdjust)
     4200        FileChanged();
     4201
     4202    if (pkt->pos > readAdjust)
     4203        pkt->pos -= readAdjust;
     4204
     4205    return pkt;
    36704206}
    36714207
    36724208// documented in decoderbase.h
    36734209bool AvFormatDecoder::GetFrame(DecodeType decodetype)
    36744210{
    36754211    AVPacket *pkt = NULL;
    3676     AC3HeaderInfo hdr;
    3677     int len;
     4212    int len, ret;
     4213    long long pts;
    36784214    unsigned char *ptr;
    3679     int data_size = 0;
    3680     long long pts;
    3681     bool firstloop = false, have_err = false;
    3682 
     4215    bool firstloop = false;
     4216    bool storevideoframes = false;
     4217    bool has_video = HasVideo(ic);
     4218
     4219    wantvideo           = decodetype & kDecodeVideo;
     4220    wantaudio           = decodetype & kDecodeAudio;
    36834221    gotvideo = false;
    3684 
    3685     frame_decoded = 0;
     4222    skipaudio           = (lastvpts == 0);
    36864223    decoded_video_frame = NULL;
    3687 
    3688     bool allowedquit = false;
    3689     bool storevideoframes = false;
     4224    allowedquit         = false;
    36904225
    36914226    avcodeclock->lock();
    36924227    AutoSelectTracks();
    36934228    avcodeclock->unlock();
    36944229
    3695     bool skipaudio = (lastvpts == 0);
    3696 
    3697     bool has_video = HasVideo(ic);
    3698 
    3699     if (!has_video && (decodetype & kDecodeVideo))
     4230    if (wantvideo && !has_video)
    37004231    {
    37014232        gotvideo = GenerateDummyVideoFrame();
    3702         decodetype = (DecodeType)((int)decodetype & ~kDecodeVideo);
    3703         skipaudio = false;
     4233        wantvideo  = skipaudio = false;
    37044234    }
    37054235
    37064236    uint ofill = 0, ototal = 0, othresh = 0, total_decoded_audio = 0;
    37074237    if (GetNVP()->GetAudioBufferStatus(ofill, ototal))
    37084238    {
    37094239        othresh =  ((ototal>>1) + (ototal>>2));
    3710         allowedquit = (!(decodetype & kDecodeAudio)) && (ofill > othresh);
     4240        allowedquit = !wantaudio && (ofill > othresh);
    37114241    }
    37124242
    37134243    while (!allowedquit)
    37144244    {
    3715         if ((decodetype & kDecodeAudio) &&
     4245        if (wantaudio &&
    37164246            ((currentTrack[kTrackTypeAudio] < 0) ||
    37174247             (selectedTrack[kTrackTypeAudio].av_stream_index < 0)))
    37184248        {
    37194249            // disable audio request if there are no audio streams anymore
    37204250            // and we have video, otherwise allow decoding to stop
    37214251            if (has_video)
    3722                 decodetype = (DecodeType)((int)decodetype & ~kDecodeAudio);
     4252                wantaudio = false;
    37234253            else
    37244254                allowedquit = true;
    37254255        }
    37264256
    37274257        if (ringBuffer->isDVD())
    3728         {
    3729             int dvdtitle  = 0;
    3730             int dvdpart = 0;
    3731             ringBuffer->DVD()->GetPartAndTitle(dvdpart, dvdtitle);
    3732             bool cellChanged = ringBuffer->DVD()->CellChanged();
    3733             bool inDVDStill = ringBuffer->DVD()->InStillFrame();
    3734             bool inDVDMenu  = ringBuffer->DVD()->IsInMenu();
    3735             int storedPktCount = storedPackets.count();
    3736             selectedVideoIndex = 0;
    3737             if (dvdTitleChanged)
    3738             {
    3739                 if ((storedPktCount > 10 && !decodeStillFrame) ||
    3740                     decodeStillFrame)
    3741                 {
    3742                     storevideoframes = false;
    3743                     dvdTitleChanged = false;
    3744                     ScanStreams(true);
    3745                 }
    3746                 else
    3747                     storevideoframes = true;
    3748             }
    3749             else
    3750             {
    3751                 storevideoframes = false;
    3752 
    3753                 if (storedPktCount < 2 && !decodeStillFrame)
    3754                     storevideoframes = true;
    3755 
    3756                 VERBOSE(VB_PLAYBACK+VB_EXTRA, QString("DVD Playback Debugging "
    3757                     "inDVDMenu %1 storedPacketcount %2 dvdstill %3")
    3758                     .arg(inDVDMenu).arg(storedPktCount).arg(inDVDStill));
    3759 
    3760                 if (inDVDStill && (storedPktCount == 0) &&
    3761                     (GetNVP()->getVideoOutput()->ValidVideoFrames() == 0))
    3762                 {
    3763                     ringBuffer->DVD()->RunSeekCellStart();
    3764                 }
    3765             }
    3766             if (GetNVP()->AtNormalSpeed() &&
    3767                 ((cellChanged) || (lastdvdtitle != dvdtitle)))
    3768             {
    3769                 if (dvdtitle != lastdvdtitle)
    3770                 {
    3771                     VERBOSE(VB_PLAYBACK, LOC + "DVD Title Changed");
    3772                     lastdvdtitle = dvdtitle;
    3773                     if (lastdvdtitle != -1 )
    3774                         dvdTitleChanged = true;
    3775                     if (GetNVP() && GetNVP()->getVideoOutput())
    3776                     {
    3777                         if (ringBuffer->DVD()->InStillFrame())
    3778                             GetNVP()->getVideoOutput()->SetPrebuffering(false);
    3779                         else
    3780                             GetNVP()->getVideoOutput()->SetPrebuffering(true);
    3781                     }
    3782                 }
    3783 
    3784                 if (ringBuffer->DVD()->PGCLengthChanged())
    3785                 {
    3786                     {
    3787                         QMutexLocker locker(&m_positionMapLock);
    3788                         posmapStarted = false;
    3789                         m_positionMap.clear();
    3790                     }
    3791                     SyncPositionMap();
    3792                 }
    3793 
    3794                 UpdateDVDFramesPlayed();
    3795                 VERBOSE(VB_PLAYBACK, QString(LOC + "DVD Cell Changed. "
    3796                                              "Update framesPlayed: %1 ")
    3797                                              .arg(framesPlayed));
    3798             }
    3799         }
     4258            storevideoframes = UpdateDVDStatus();
    38004259
    38014260        if (gotvideo)
    38024261        {
    3803             if (decodetype == kDecodeNothing)
     4262            if (!wantvideo && !wantaudio)
    38044263            {
    38054264                // no need to buffer audio or video if we
    38064265                // only care about building a keyframe map.
    38074266                allowedquit = true;
    38084267                continue;
    38094268            }
    3810             else if (lowbuffers && ((decodetype & kDecodeAV) == kDecodeAV) &&
     4269            else if (lowbuffers && wantaudio && wantvideo &&
    38114270                     storedPackets.count() < max_video_queue_size &&
    38124271                     lastapts < lastvpts + 100 &&
    38134272                     !ringBuffer->InDVDMenuOrStillFrame())
    38144273            {
    38154274                storevideoframes = true;
    38164275            }
    3817             else if (decodetype & kDecodeVideo)
     4276            else if (wantvideo)
    38184277            {
    38194278                if (storedPackets.count() >= max_video_queue_size)
    38204279                    VERBOSE(VB_IMPORTANT,
     
    38264285            }
    38274286        }
    38284287
    3829         if (!storevideoframes && storedPackets.count() > 0)
    3830         {
    3831             if (pkt)
    3832             {
    3833                 av_free_packet(pkt);
    3834                 delete pkt;
    3835             }
    3836             pkt = storedPackets.takeFirst();
    3837         }
    3838         else
    3839         {
    3840             if (!pkt)
    3841             {
    3842                 pkt = new AVPacket;
    3843                 bzero(pkt, sizeof(AVPacket));
    3844                 av_init_packet(pkt);
    3845             }
    3846 
    3847             if (!ic || (av_read_frame(ic, pkt) < 0))
    3848             {
    3849                 ateof = true;
    3850                 GetNVP()->SetEof();
    3851                 delete pkt;
     4288        if ((pkt = GetPacket(pkt, storevideoframes)) == NULL)
    38524289                return false;
    3853             }
    3854 
    3855             if (ringBuffer->isDVD() &&
    3856                 ringBuffer->DVD()->InStillFrame())
    3857             {
    3858                 AVStream *curstream = ic->streams[pkt->stream_index];
    3859                 if (curstream &&
    3860                     curstream->codec->codec_type == CODEC_TYPE_VIDEO)
    3861                 {
    3862                     mpeg_seq_end_seen = false;
    3863                     decodeStillFrame = false;
    3864                     ringBuffer->DVD()->InStillFrame(false);
    3865                 }
    3866             }
    3867 
    3868             if (waitingForChange && pkt->pos >= readAdjust)
    3869                 FileChanged();
    3870 
    3871             if (pkt->pos > readAdjust)
    3872                 pkt->pos -= readAdjust;
    3873         }
    38744290
    38754291        if (pkt->stream_index > (int) ic->nb_streams)
    38764292        {
    3877             VERBOSE(VB_IMPORTANT, LOC_ERR + "Bad stream");
     4293            VERBOSE(VB_IMPORTANT, LOC_ERR + "Packet stream index out of bounds");
    38784294            av_free_packet(pkt);
    38794295            continue;
    38804296        }
     
    38834299        ptr = pkt->data;
    38844300        pts = 0;
    38854301
    3886         AVStream *curstream = ic->streams[pkt->stream_index];
    3887 
    3888         if (!curstream)
     4302        AVStream *stream = ic->streams[pkt->stream_index];
     4303        AVCodecContext *ctx = stream->codec;
     4304
     4305        if (!stream)
    38894306        {
    38904307            VERBOSE(VB_IMPORTANT, LOC_ERR + "Bad stream (NULL)");;
    38914308            av_free_packet(pkt);
     
    38934310        }
    38944311
    38954312        if (pkt->dts != (int64_t)AV_NOPTS_VALUE)
    3896             pts = (long long)(av_q2d(curstream->time_base) * pkt->dts * 1000);
    3897 
    3898         if (ringBuffer->isDVD() &&
    3899             curstream->codec->codec_type == CODEC_TYPE_VIDEO)
    3900         {
    3901             MpegPreProcessPkt(curstream, pkt);
     4313            pts = (long long)(av_q2d(stream->time_base) * pkt->dts * 1000);
     4314
     4315        if (len <= 0)
     4316        {
     4317            av_free_packet(pkt);
     4318            continue;
     4319        }
     4320
     4321        if (ctx->codec_type == CODEC_TYPE_VIDEO)
     4322        {
     4323            if (ringBuffer->isDVD() && !PreProcessDVDVideoPacket(pkt, stream))
     4324                continue;
     4325
     4326            if (storevideoframes)
     4327            {
     4328                av_dup_packet(pkt);
     4329                storedPackets.append(pkt);
     4330                pkt = NULL;
     4331                continue;
     4332            }
     4333
     4334            if (pkt->stream_index == selectedVideoIndex)
     4335            {
     4336                if (!PreProcessVideoPacket(pkt, stream))
     4337                    continue;
     4338                // If the resolution changed in XXXPreProcessPkt, we may
     4339                // have a fatal error, so check for this before continuing.
     4340                if (GetNVP()->IsErrored())
     4341                {
     4342                    av_free_packet(pkt);
     4343                    delete pkt;
     4344                    return false;
     4345                }
     4346            }
     4347        }
     4348        else if ((ctx->codec_type == CODEC_TYPE_DATA      ||
     4349                  ctx->codec_type == CODEC_TYPE_SUBTITLE) &&
     4350                 ProcessDataPacket(pkt, stream))
     4351            continue;
     4352
     4353        if (!ctx->codec)
     4354        {
     4355            VERBOSE(VB_PLAYBACK, LOC +
     4356                    QString("No codec for stream index %1, type(%2) id(%3:%4)")
     4357                    .arg(pkt->stream_index)
     4358                    .arg(codec_type_string(ctx->codec_type))
     4359                    .arg(codec_id_string(ctx->codec_id))
     4360                    .arg(ctx->codec_id));
     4361            av_free_packet(pkt);
     4362            continue;
     4363        }
     4364
     4365        int ctype = ctx->codec_type;
     4366        firstloop = true;
     4367
     4368        while (len > 0)
     4369        {
     4370            switch (ctype)
     4371            {
     4372                case CODEC_TYPE_AUDIO:
     4373                    int decoded;
     4374                    ret = ProcessAudioPacket(pkt, stream, ptr, len,
     4375                                             decoded, firstloop);
     4376                    if (decoded <= 0)
     4377                        break;
     4378
     4379                    total_decoded_audio += decoded;
     4380                    allowedquit |= ringBuffer->InDVDMenuOrStillFrame();
     4381                    // top off audio buffers initially in audio only mode
     4382                    if (!allowedquit && !wantvideo)
     4383                        allowedquit = TopUpAudioBuffer(decoded,
     4384                                                       total_decoded_audio,
     4385                                                       ofill, othresh);
     4386                    break;
     4387                case CODEC_TYPE_VIDEO:
     4388                {
     4389                    ret = ProcessVideoPacket(pkt, stream, pts, firstloop);
     4390                    break;
     4391                }
     4392                case CODEC_TYPE_SUBTITLE:
     4393                {
     4394                    ret = ProcessSubtitlePacket(pkt, stream, pts);
     4395                    break;
     4396                }
     4397                default:
     4398                {
     4399                    VERBOSE(VB_IMPORTANT, LOC_ERR +
     4400                            QString("Decoding - id(%1) type(%2)")
     4401                                .arg(codec_id_string(ctx->codec_id))
     4402                                .arg(codec_type_string(ctx->codec_type)));
     4403                    ret = len;
     4404                    break;
     4405                }
     4406            }
     4407            ptr += ret;
     4408            len -= ret;
     4409            firstloop = false;
     4410        }
     4411        av_free_packet(pkt);
     4412    }
     4413
     4414    if (pkt)
     4415        delete pkt;
     4416
     4417    return true;
     4418}
     4419
     4420bool AvFormatDecoder::UpdateDVDStatus()
     4421{
     4422    int dvdtitle          = 0;
     4423    int dvdpart           = 0;
     4424    bool cellChanged      = ringBuffer->DVD()->CellChanged();
     4425    bool inDVDStill       = ringBuffer->DVD()->InStillFrame();
     4426    bool inDVDMenu        = ringBuffer->DVD()->IsInMenu();
     4427    int storedPktCount    = storedPackets.count();
     4428    bool storevideoframes = false;
     4429    selectedVideoIndex    = 0;
     4430
     4431    ringBuffer->DVD()->GetPartAndTitle(dvdpart, dvdtitle);
     4432
     4433    if (dvdTitleChanged)
     4434    {
     4435        if ((storedPktCount > 10 && !decodeStillFrame) || decodeStillFrame)
     4436        {
     4437            storevideoframes = dvdTitleChanged = false;
     4438            ScanStreams(true);
     4439        }
     4440        else
     4441            storevideoframes = true;
     4442    }
     4443    else
     4444    {
     4445        storevideoframes = false;
     4446
     4447        if (storedPktCount < 2 && !decodeStillFrame)
     4448            storevideoframes = true;
     4449
     4450        VERBOSE(VB_PLAYBACK+VB_EXTRA, QString("DVD Playback Debugging "
     4451            "inDVDMenu %1 storedPacketcount %2 dvdstill %3")
     4452            .arg(inDVDMenu).arg(storedPktCount).arg(inDVDStill));
     4453
     4454        if (inDVDStill && storedPktCount == 0 &&
     4455            GetNVP()->getVideoOutput()->ValidVideoFrames() == 0)
     4456        {
     4457            ringBuffer->DVD()->RunSeekCellStart();
     4458        }
     4459    }
     4460
     4461    if (GetNVP()->AtNormalSpeed() && (cellChanged || lastdvdtitle != dvdtitle))
     4462    {
     4463        if (dvdtitle != lastdvdtitle)
     4464        {
     4465            VERBOSE(VB_PLAYBACK, LOC + "DVD Title Changed");
     4466            lastdvdtitle = dvdtitle;
     4467            if (lastdvdtitle != -1)
     4468                dvdTitleChanged = true;
     4469            if (GetNVP() && GetNVP()->getVideoOutput())
     4470            {
     4471                if (ringBuffer->DVD()->InStillFrame())
     4472                    GetNVP()->getVideoOutput()->SetPrebuffering(false);
     4473                else
     4474                    GetNVP()->getVideoOutput()->SetPrebuffering(true);
     4475            }
     4476        }
     4477
     4478        if (ringBuffer->DVD()->PGCLengthChanged())
     4479        {
     4480            {
     4481                QMutexLocker locker(&m_positionMapLock);
     4482                posmapStarted = false;
     4483                m_positionMap.clear();
     4484            }
     4485            SyncPositionMap();
     4486        }
     4487
     4488        UpdateDVDFramesPlayed();
     4489        VERBOSE(VB_PLAYBACK, QString(LOC + "DVD Cell Changed. "
     4490                                     "Update framesPlayed: %1")
     4491                                     .arg(framesPlayed));
     4492    }
     4493
     4494    return storevideoframes;
     4495}
     4496
     4497bool AvFormatDecoder::PreProcessDVDVideoPacket(AVPacket *pkt, AVStream *stream)
     4498{
     4499
     4500    MpegPreProcessPkt(stream, pkt);
    39024501
    39034502            if (mpeg_seq_end_seen)
    39044503                ringBuffer->DVD()->InStillFrame(true);
     
    39064505            bool inDVDStill = ringBuffer->DVD()->InStillFrame();
    39074506
    39084507            VERBOSE(VB_PLAYBACK+VB_EXTRA,
    3909                 QString("DVD Playback Debugging: mpeg seq end %1 "
    3910                 " inDVDStill %2 decodeStillFrame %3")
     4508            QString("DVD Playback Debugging: mpeg seq end %1 inDVDStill %2 "
     4509                    "decodeStillFrame %3")
    39114510                .arg(mpeg_seq_end_seen).arg(inDVDStill).arg(decodeStillFrame));
    39124511
    39134512            if (!decodeStillFrame && inDVDStill)
     
    39184517
    39194518            if (!d->HasMPEG2Dec())
    39204519            {
    3921                 int current_width = curstream->codec->width;
     4520        int current_width = stream->codec->width;
    39224521                int video_width = GetNVP()->GetVideoSize().width();
    39234522                if (dvd_xvmc_enabled && GetNVP() && GetNVP()->getVideoOutput())
    39244523                {
    3925                     bool dvd_xvmc_active = false;
    3926                     if (codec_is_xvmc(video_codec_id))
    3927                     {
    3928                         dvd_xvmc_active = true;
    3929                     }
    3930 
     4524            bool dvd_xvmc_active = codec_is_xvmc(video_codec_id);
    39314525                    bool indvdmenu   = ringBuffer->InDVDMenuOrStillFrame();
    39324526                    if ((indvdmenu && dvd_xvmc_active) ||
    39334527                        ((!indvdmenu && !dvd_xvmc_active)))
    39344528                    {
    3935                         VERBOSE(VB_PLAYBACK, LOC + QString("DVD Codec Change "
    3936                                     "indvdmenu %1 dvd_xvmc_active %2")
     4529                VERBOSE(VB_PLAYBACK, LOC +
     4530                        QString("DVD Codec Change indvdmenu %1 "
     4531                                "dvd_xvmc_active %2")
    39374532                                .arg(indvdmenu).arg(dvd_xvmc_active));
    39384533                        dvd_video_codec_changed = true;
    39394534                    }
    39404535                }
    39414536
    3942                 if ((video_width > 0) && dvd_video_codec_changed)
    3943                 {
    3944                     VERBOSE(VB_PLAYBACK, LOC + QString("DVD Stream/Codec Change "
    3945                                 "video_width %1 current_width %2 "
    3946                                 "dvd_video_codec_changed %3")
     4537        if (video_width > 0 && dvd_video_codec_changed)
     4538        {
     4539            VERBOSE(VB_PLAYBACK, LOC +
     4540                    QString("DVD Stream/Codec Change video_width %1 "
     4541                            "current_width %2 dvd_video_codec_changed %3")
    39474542                            .arg(video_width).arg(current_width)
    39484543                            .arg(dvd_video_codec_changed));
     4544
    39494545                    av_free_packet(pkt);
    39504546                    if (current_width > 0) {
    39514547                        CloseCodecs();
     
    39534549                        allowedquit = true;
    39544550                        dvd_video_codec_changed = false;
    39554551                    }
    3956                     continue;
    3957                 }
    3958             }
    3959         }
    3960 
    3961         if (storevideoframes &&
    3962             curstream->codec->codec_type == CODEC_TYPE_VIDEO)
    3963         {
    3964             av_dup_packet(pkt);
    3965             storedPackets.append(pkt);
    3966             pkt = NULL;
    3967             continue;
    3968         }
    3969 
    3970         if (len > 0 && curstream->codec->codec_type == CODEC_TYPE_VIDEO &&
    3971             pkt->stream_index == selectedVideoIndex)
    3972         {
    3973             AVCodecContext *context = curstream->codec;
    3974             bool on_frame = true;
    3975 
    3976             if (CODEC_IS_FFMPEG_MPEG(context->codec_id))
    3977             {
    3978                 if (!ringBuffer->isDVD())
    3979                     MpegPreProcessPkt(curstream, pkt);
    3980             }
    3981             else if (CODEC_IS_H264(context->codec_id))
    3982             {
    3983                 on_frame = H264PreProcessPkt(curstream, pkt);
    3984             }
    3985             else
    3986             {
    3987                 if (pkt->flags & PKT_FLAG_KEY)
    3988                 {
    3989                     HandleGopStart(pkt, false);
    3990                     seen_gop = true;
    3991                 }
    3992                 else
    3993                 {
    3994                     seq_count++;
    3995                     if (!seen_gop && seq_count > 1)
    3996                     {
    3997                         HandleGopStart(pkt, false);
    3998                     }
    3999                 }
    4000             }
    4001 
    4002             if (framesRead == 0 && !justAfterChange &&
    4003                 !(pkt->flags & PKT_FLAG_KEY))
    4004             {
    4005                 av_free_packet(pkt);
    4006                 continue;
    4007             }
    4008 
    4009             if (on_frame)
    4010                 framesRead++;
    4011             justAfterChange = false;
    4012 
    4013             if (exitafterdecoded)
    4014                 gotvideo = 1;
    4015 
    4016             // If the resolution changed in XXXPreProcessPkt, we may
    4017             // have a fatal error, so check for this before continuing.
    4018             if (GetNVP()->IsErrored())
    4019             {
    4020                 av_free_packet(pkt);
    4021                 delete pkt;
    40224552                return false;
    40234553            }
    40244554        }
    40254555
    4026         if (len > 0 &&
    4027             curstream->codec->codec_type == CODEC_TYPE_DATA &&
    4028             curstream->codec->codec_id   == CODEC_ID_MPEG2VBI)
    4029         {
    4030             ProcessVBIDataPacket(curstream, pkt);
    4031 
    4032             av_free_packet(pkt);
    4033             continue;
    4034         }
    4035 
    4036         if (len > 0 &&
    4037             ((curstream->codec->codec_type == CODEC_TYPE_DATA &&
    4038               curstream->codec->codec_id   == CODEC_ID_DVB_VBI) ||
    4039              (curstream->codec->codec_type == CODEC_TYPE_SUBTITLE &&
    4040               curstream->codec->codec_id   == CODEC_ID_DVB_TELETEXT)))
    4041         {
    4042             ProcessDVBDataPacket(curstream, pkt);
    4043 
    4044             av_free_packet(pkt);
    4045             continue;
    4046         }
    4047 
    4048 #ifdef USING_MHEG
    4049         if (len > 0 &&
    4050             curstream->codec->codec_type == CODEC_TYPE_DATA &&
    4051             curstream->codec->codec_id   == CODEC_ID_DSMCC_B)
    4052         {
    4053             ProcessDSMCCPacket(curstream, pkt);
    4054 
    4055             av_free_packet(pkt);
    4056 
    4057             // Have to return regularly to ensure that the OSD is updated.
    4058             // This applies both to MHEG and also channel browsing.
    4059             if (!(decodetype & kDecodeVideo))
    4060             {
    4061                 allowedquit |= (itv && itv->ImageHasChanged());
    4062                 OSD *osd = NULL;
    4063                 if (!allowedquit && GetNVP() && (osd = GetNVP()->GetOSD()))
    4064                     allowedquit |=  osd->HasChanged();
    4065             }
    4066 
    4067             continue;
    4068         }
    4069 #endif // USING_MHEG
    4070 
    4071         // we don't care about other data streams
    4072         if (curstream->codec->codec_type == CODEC_TYPE_DATA)
    4073         {
    4074             av_free_packet(pkt);
    4075             continue;
    4076         }
    4077 
    4078         if (!curstream->codec->codec)
    4079         {
    4080             VERBOSE(VB_PLAYBACK, LOC +
    4081                     QString("No codec for stream index %1, type(%2) id(%3:%4)")
    4082                     .arg(pkt->stream_index)
    4083                     .arg(codec_type_string(curstream->codec->codec_type))
    4084                     .arg(codec_id_string(curstream->codec->codec_id))
    4085                     .arg(curstream->codec->codec_id));
    4086             av_free_packet(pkt);
    4087             continue;
    4088         }
    4089 
    4090         firstloop = true;
    4091         have_err = false;
    4092 
    4093         avcodeclock->lock();
    4094         int ctype  = curstream->codec->codec_type;
    4095         int audIdx = selectedTrack[kTrackTypeAudio].av_stream_index;
    4096         int audSubIdx = selectedTrack[kTrackTypeAudio].av_substream_index;
    4097         int subIdx = selectedTrack[kTrackTypeSubtitle].av_stream_index;
    4098         avcodeclock->unlock();
    4099 
    4100         while (!have_err && len > 0)
    4101         {
    4102             int ret = 0;
    4103             bool dts = false;
    4104             switch (ctype)
    4105             {
    4106                 case CODEC_TYPE_AUDIO:
    4107                 {
    4108                     bool reselectAudioTrack = false;
    4109                     char *s;
    4110 
    4111                     /// HACK HACK HACK -- begin See #3731
    4112                     if (!GetNVP()->HasAudioIn())
    4113                     {
    4114                         VERBOSE(VB_AUDIO, LOC + "Audio is disabled - trying to restart it");
    4115                         reselectAudioTrack = true;
    4116                     }
    4117                     /// HACK HACK HACK -- end
    4118 
    4119                     // detect switches between stereo and dual languages
    4120                     bool wasDual = audSubIdx != -1;
    4121                     bool isDual = curstream->codec->avcodec_dual_language;
    4122                     if ((wasDual && !isDual) || (!wasDual &&  isDual))
    4123                     {
    4124                         SetupAudioStreamSubIndexes(audIdx);
    4125                         reselectAudioTrack = true;
    4126                     }
    4127 
    4128                     // detect channels on streams that need
    4129                     // to be decoded before we can know this
    4130                     bool already_decoded = false;
    4131                     if (!curstream->codec->channels)
    4132                     {
    4133                         QMutexLocker locker(avcodeclock);
    4134                         VERBOSE(VB_IMPORTANT, LOC +
    4135                                 QString("Setting channels to %1")
    4136                                 .arg(audioOut.channels));
    4137 
    4138                         if (DoPassThrough(curstream->codec))
    4139                         {
    4140                             // for passthru let it select the max number
    4141                             // of channels
    4142                             curstream->codec->channels = 0;
    4143                             curstream->codec->request_channels = 0;
    4144                         }
    4145                         else
    4146                         {
    4147                             curstream->codec->channels = audioOut.channels;
    4148                             curstream->codec->request_channels =
    4149                                 audioOut.channels;
    4150                         }
    4151                         data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
    4152                         ret = avcodec_decode_audio2(curstream->codec,
    4153                                                     audioSamples, &data_size,
    4154                                                     ptr, len);
    4155                         already_decoded = true;
    4156 
    4157                         reselectAudioTrack |= curstream->codec->channels;
    4158                     }
    4159 
    4160                     if (curstream->codec->codec_id == CODEC_ID_AC3)
    4161                     {
    4162                         GetBitContext gbc;
    4163                         init_get_bits(&gbc, ptr, len * 8);
    4164                         if (!ff_ac3_parse_header(&gbc, &hdr))
    4165                         {
    4166                             if (hdr.channels != last_ac3_channels)
    4167                             {
    4168                                 VERBOSE(VB_AUDIO, LOC + QString("AC3 changed from %1 to %2 channels (frame %3)")
    4169                                         .arg(last_ac3_channels).arg(hdr.channels).arg(framesRead));
    4170                                 if ((framesRead - last_framesRead) > AUDIOMAXFRAMES ||
    4171                                     hdr.channels < last_ac3_channels)
    4172                                     curstream->codec->channels = hdr.channels;
    4173                                 last_ac3_channels = hdr.channels;
    4174                                 last_framesRead = framesRead;
    4175                                 SetupAudioStream();
    4176                             }
    4177                         }
    4178                     }
    4179 
    4180                     if (reselectAudioTrack)
    4181                     {
    4182                         QMutexLocker locker(avcodeclock);
    4183                         currentTrack[kTrackTypeAudio] = -1;
    4184                         selectedTrack[kTrackTypeAudio]
    4185                             .av_stream_index = -1;
    4186                         audIdx = -1;
    4187                         audSubIdx = -1;
    4188                         AutoSelectAudioTrack();
    4189                         audIdx = selectedTrack[kTrackTypeAudio]
    4190                             .av_stream_index;
    4191                         audSubIdx = selectedTrack[kTrackTypeAudio]
    4192                             .av_substream_index;
    4193                     }
    4194 
    4195                     if (!(decodetype & kDecodeAudio) ||
    4196                         (pkt->stream_index != audIdx))
    4197                     {
    4198                         ptr += len;
    4199                         len = 0;
    4200                         continue;
    4201                     }
    4202 
    4203                     if (firstloop && pkt->pts != (int64_t)AV_NOPTS_VALUE)
    4204                         lastapts = (long long)(av_q2d(curstream->time_base) *
    4205                                                pkt->pts * 1000);
    4206 
    4207                     if (skipaudio)
    4208                     {
    4209                         if ((lastapts < lastvpts - (10.0 / fps)) ||
    4210                             lastvpts == 0)
    4211                         {
    4212                             ptr += len;
    4213                             len = 0;
    4214                             continue;
    4215                         }
    4216                         else
    4217                             skipaudio = false;
    4218                     }
    4219 
    4220                     avcodeclock->lock();
    4221                     data_size = 0;
    4222 
    4223                     if (audioOut.do_passthru)
    4224                     {
    4225                         data_size = pkt->size;
    4226                         dts = CODEC_ID_DTS == curstream->codec->codec_id;
    4227                         ret = encode_frame(dts, ptr, len,
    4228                                            audioSamples, data_size);
    4229                         s = (char *)audioSamples;
    4230                     }
    4231                     else
    4232                     {
    4233                         AVCodecContext *ctx = curstream->codec;
    4234 
    4235                         if ((ctx->channels == 0) ||
    4236                             (ctx->channels > audioOut.channels))
    4237                         {
    4238                             ctx->channels = audioOut.channels;
    4239                         }
    4240 
    4241                         if (!already_decoded)
    4242                         {
    4243                             curstream->codec->request_channels =
    4244                                 audioOut.channels;
    4245                             data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
    4246                             ret = avcodec_decode_audio2(ctx, audioSamples,
    4247                                                         &data_size, ptr, len);
    4248                         }
    4249 
    4250                             // Convert sample format if required (Myth only handles 8 and 16 bits audio)
    4251                         if (ctx->sample_fmt != SAMPLE_FMT_S16 && ctx->sample_fmt != SAMPLE_FMT_U8)
    4252                         {
    4253                             if (audio_src_fmt != ctx->sample_fmt)
    4254                             {
    4255                                 if (reformat_ctx)
    4256                                     av_audio_convert_free(reformat_ctx);
    4257                                 reformat_ctx = av_audio_convert_alloc(SAMPLE_FMT_S16, 1,
    4258                                                                       ctx->sample_fmt, 1,
    4259                                                                       NULL, 0);
    4260                                 if (!reformat_ctx ||
    4261                                     (!audioSamplesResampled &&
    4262                                     !(audioSamplesResampled = (short int *)av_mallocz(AVCODEC_MAX_AUDIO_FRAME_SIZE *
    4263                                                                                       sizeof(*audioSamplesResampled)))))
    4264                                 {
    4265                                     VERBOSE(VB_PLAYBACK, QString("Cannot convert %1 sample format to %2 sample format")
    4266                                             .arg(avcodec_get_sample_fmt_name(ctx->sample_fmt))
    4267                                             .arg(avcodec_get_sample_fmt_name(SAMPLE_FMT_S16)));
    4268 
    4269                                     avcodeclock->unlock();
    4270                                     have_err = true;
    4271                                     continue;
    4272                                 }
    4273                                 audio_src_fmt = ctx->sample_fmt;
    4274                             }
    4275                         }
    4276 
    4277                         if (reformat_ctx)
    4278                         {
    4279                             const void *ibuf[6] = {audioSamples};
    4280                             void *obuf[6] = {audioSamplesResampled};
    4281                             int istride[6] = {av_get_bits_per_sample_format(ctx->sample_fmt)/8};
    4282                             int ostride[6] = {2};
    4283                             int len = data_size/istride[0];
    4284                             if (av_audio_convert(reformat_ctx, obuf, ostride,
    4285                                                  ibuf, istride, len) < 0)
    4286                             {
    4287                                 VERBOSE(VB_PLAYBACK, "av_audio_convert() failed");
    4288 
    4289                                 avcodeclock->unlock();
    4290                                 have_err = true;
    4291                                 continue;
    4292                             }
    4293 
    4294                             data_size = len * 2;
    4295                             s = (char *)audioSamplesResampled;
    4296                         }
    4297                         else
    4298                             s = (char *)audioSamples;
    4299 
    4300                         // When decoding some audio streams the number of
    4301                         // channels, etc isn't known until we try decoding it.
    4302                         if ((ctx->sample_rate != audioOut.sample_rate) ||
    4303                             (ctx->channels    != audioOut.channels))
    4304                         {
    4305                             VERBOSE(VB_IMPORTANT, "audio stream changed");
    4306                             currentTrack[kTrackTypeAudio] = -1;
    4307                             selectedTrack[kTrackTypeAudio]
    4308                                 .av_stream_index = -1;
    4309                             audIdx = -1;
    4310                             AutoSelectAudioTrack();
    4311                             data_size = 0;
    4312                         }
    4313                     }
    4314                     avcodeclock->unlock();
    4315 
    4316                     if (ret < 0)
    4317                     {
    4318                         if (!dts)
    4319                         {
    4320                             VERBOSE(VB_IMPORTANT, LOC_ERR +
    4321                                     "Unknown audio decoding error");
    4322                         }
    4323                         have_err = true;
    4324                         continue;
    4325                     }
    4326 
    4327                     if (data_size <= 0)
    4328                     {
    4329                         ptr += ret;
    4330                         len -= ret;
    4331                         continue;
    4332                     }
    4333 
    4334                     long long temppts = lastapts;
    4335 
    4336                     // calc for next frame
    4337                     lastapts += (long long)((double)(data_size * 1000) /
    4338                                 (curstream->codec->channels * 2) /
    4339                                 curstream->codec->sample_rate);
    4340 
    4341                     VERBOSE(VB_PLAYBACK+VB_TIMESTAMP,
    4342                             LOC + QString("audio timecode %1 %2 %3 %4")
    4343                             .arg(pkt->pts).arg(pkt->dts)
    4344                             .arg(temppts).arg(lastapts));
    4345 
    4346                     if (audSubIdx != -1)
    4347                     {
    4348                         extract_mono_channel(audSubIdx, &audioOut,
    4349                                              s, data_size);
    4350                     }
    4351 
    4352                     GetNVP()->AddAudioData(s, data_size, temppts);
    4353 
    4354                     total_decoded_audio += data_size;
    4355 
    4356                     allowedquit |= ringBuffer->InDVDMenuOrStillFrame();
    4357                     allowedquit |= !(decodetype & kDecodeVideo) &&
    4358                         (ofill + total_decoded_audio > othresh);
    4359 
    4360                     // top off audio buffers initially in audio only mode
    4361                     if (!allowedquit && !(decodetype & kDecodeVideo))
    4362                     {
    4363                         uint fill, total;
    4364                         if (GetNVP()->GetAudioBufferStatus(fill, total))
    4365                         {
    4366                             total /= 6; // HACK needed for some audio files
    4367                             allowedquit =
    4368                                 (fill == 0) || (fill > (total>>1)) ||
    4369                                 ((total - fill) < (uint) data_size) ||
    4370                                 (ofill + total_decoded_audio > (total>>2)) ||
    4371                                 ((total - fill) < (uint) data_size * 2);
    4372                         }
    4373                         else
    4374                         {
    4375                             VERBOSE(VB_IMPORTANT, LOC_ERR +
    4376                                     "GetFrame() : Failed to top off "
    4377                                     "buffers in audio only mode");
    4378                         }
    4379                     }
    4380 
    4381                     break;
    4382                 }
    4383                 case CODEC_TYPE_VIDEO:
    4384                 {
    4385                     if (pkt->stream_index != selectedVideoIndex)
    4386                     {
    4387                         ptr += pkt->size;
    4388                         len -= pkt->size;
    4389                         continue;
    4390                     }
    4391 
    4392                     if (firstloop && pts != (int64_t) AV_NOPTS_VALUE)
    4393                     {
    4394                         lastccptsu = (long long)
    4395                             (av_q2d(curstream->time_base)*pkt->pts*1000000);
    4396                     }
    4397 
    4398                     if (!(decodetype & kDecodeVideo))
    4399                     {
    4400                         framesPlayed++;
    4401                         gotvideo = 1;
    4402                         ptr += pkt->size;
    4403                         len -= pkt->size;
    4404                         continue;
    4405                     }
    4406 
    4407                     AVCodecContext *context = curstream->codec;
    4408                     AVFrame mpa_pic;
    4409                     bzero(&mpa_pic, sizeof(AVFrame));
    4410 
    4411                     int gotpicture = 0;
    4412 
    4413                     avcodeclock->lock();
    4414                     if (d->HasDecoder())
    4415                     {
    4416                         if (decodeStillFrame)
    4417                         {
    4418                             int count = 0;
    4419                             // HACK
    4420                             while (!gotpicture && count < 5)
    4421                             {
    4422                                 ret = d->DecodeMPEG2Video(context, &mpa_pic,
    4423                                                   &gotpicture, ptr, len);
    4424                                 count++;
    4425                             }
    4426                         }
    4427                         else
    4428                         {
    4429                             ret = d->DecodeMPEG2Video(context, &mpa_pic,
    4430                                                 &gotpicture, ptr, len);
    4431                         }
    4432                     }
    4433                     else
    4434                     {
    4435                         ret = avcodec_decode_video(context, &mpa_pic,
    4436                                                    &gotpicture, ptr, len);
    4437                         // Reparse it to not drop the DVD still frame
    4438                         if (decodeStillFrame)
    4439                             ret = avcodec_decode_video(context, &mpa_pic,
    4440                                                         &gotpicture, ptr, len);
    4441                     }
    4442                     avcodeclock->unlock();
    4443 
    4444                     if (ret < 0)
    4445                     {
    4446                         VERBOSE(VB_IMPORTANT, LOC_ERR +
    4447                                 "Unknown decoding error");
    4448                         have_err = true;
    4449                         continue;
    4450                     }
    4451 
    4452                     if (!gotpicture)
    4453                     {
    4454                         ptr += ret;
    4455                         len -= ret;
    4456                         continue;
    4457                     }
    4458 
    4459                     // Decode CEA-608 and CEA-708 captions
    4460                     for (uint i = 0; i < (uint)mpa_pic.atsc_cc_len;
    4461                          i += ((mpa_pic.atsc_cc_buf[i] & 0x1f) * 3) + 2)
    4462                     {
    4463                         DecodeDTVCC(mpa_pic.atsc_cc_buf + i,
    4464                                     mpa_pic.atsc_cc_len - i);
    4465                     }
    4466 
    4467                     VideoFrame *picframe = (VideoFrame *)(mpa_pic.opaque);
    4468 
    4469                     if (!directrendering)
    4470                     {
    4471                         AVPicture tmppicture;
    4472 
    4473                         VideoFrame *xf = picframe;
    4474                         picframe = GetNVP()->GetNextVideoFrame(false);
    4475 
    4476                         unsigned char *buf = picframe->buf;
    4477                         tmppicture.data[0] = buf + picframe->offsets[0];
    4478                         tmppicture.data[1] = buf + picframe->offsets[1];
    4479                         tmppicture.data[2] = buf + picframe->offsets[2];
    4480                         tmppicture.linesize[0] = picframe->pitches[0];
    4481                         tmppicture.linesize[1] = picframe->pitches[1];
    4482                         tmppicture.linesize[2] = picframe->pitches[2];
    4483 
    4484                         myth_sws_img_convert(
    4485                             &tmppicture, PIX_FMT_YUV420P,
    4486                                     (AVPicture *)&mpa_pic,
    4487                                     context->pix_fmt,
    4488                                     context->width,
    4489                                     context->height);
    4490 
    4491                         if (xf)
    4492                         {
    4493                             // Set the frame flags, but then discard it
    4494                             // since we are not using it for display.
    4495                             xf->interlaced_frame = mpa_pic.interlaced_frame;
    4496                             xf->top_field_first = mpa_pic.top_field_first;
    4497                             xf->frameNumber = framesPlayed;
    4498                             GetNVP()->DiscardVideoFrame(xf);
    4499                         }
    4500                     }
    4501 
    4502                     long long temppts = pts;
    4503 
    4504                     // Validate the video pts against the last pts. If it's
    4505                     // a little bit smaller, equal or not available, compute
    4506                     // it from the last. Otherwise assume a wraparound.
    4507                     if (!ringBuffer->isDVD() &&
    4508                         temppts <= lastvpts &&
    4509                         (temppts + 10000 > lastvpts || temppts <= 0))
    4510                     {
    4511                         temppts = lastvpts;
    4512                         temppts += (long long)(1000 / fps);
    4513                         // MPEG2/H264 frames can be repeated, update pts accordingly
    4514                         temppts += (long long)(mpa_pic.repeat_pict * 500 / fps);
    4515                     }
    4516 
    4517                     VERBOSE(VB_PLAYBACK+VB_TIMESTAMP, LOC +
    4518                             QString("video timecode %1 %2 %3 %4")
    4519                             .arg(pkt->pts).arg(pkt->dts).arg(temppts)
    4520                             .arg(lastvpts));
    4521 
    4522 /* XXX: Broken.
    4523                     if (mpa_pic.qscale_table != NULL && mpa_pic.qstride > 0 &&
    4524                         context->height == picframe->height)
    4525                     {
    4526                         int tblsize = mpa_pic.qstride *
    4527                                       ((picframe->height + 15) / 16);
    4528 
    4529                         if (picframe->qstride != mpa_pic.qstride ||
    4530                             picframe->qscale_table == NULL)
    4531                         {
    4532                             picframe->qstride = mpa_pic.qstride;
    4533                             if (picframe->qscale_table)
    4534                                 delete [] picframe->qscale_table;
    4535                             picframe->qscale_table = new unsigned char[tblsize];
    4536                         }
    4537 
    4538                         memcpy(picframe->qscale_table, mpa_pic.qscale_table,
    4539                                tblsize);
    4540                     }
    4541 */
    4542 
    4543                     picframe->interlaced_frame = mpa_pic.interlaced_frame;
    4544                     picframe->top_field_first = mpa_pic.top_field_first;
    4545                     picframe->repeat_pict = mpa_pic.repeat_pict;
    4546 
    4547                     picframe->frameNumber = framesPlayed;
    4548                     GetNVP()->ReleaseNextVideoFrame(picframe, temppts);
    4549                     if (d->HasMPEG2Dec() && mpa_pic.data[3])
    4550                         context->release_buffer(context, &mpa_pic);
    4551 
    4552                     decoded_video_frame = picframe;
    4553                     gotvideo = 1;
    4554                     framesPlayed++;
    4555 
    4556                     lastvpts = temppts;
    4557                     break;
    4558                 }
    4559                 case CODEC_TYPE_SUBTITLE:
    4560                 {
    4561                     int gotSubtitles = 0;
    4562                     AVSubtitle subtitle;
    4563                     memset(&subtitle, 0, sizeof(AVSubtitle));
    4564 
    4565                     if (ringBuffer->isDVD())
    4566                     {
    4567                         if (ringBuffer->DVD()->NumMenuButtons() > 0)
    4568                         {
    4569                             ringBuffer->DVD()->GetMenuSPUPkt(ptr, len,
    4570                                                              curstream->id);
    4571                         }
    4572                         else
    4573                         {
    4574                             if (pkt->stream_index == subIdx)
    4575                             {
    4576                                 QMutexLocker locker(avcodeclock);
    4577                                 ringBuffer->DVD()->DecodeSubtitles(&subtitle,
    4578                                                                    &gotSubtitles,
    4579                                                                    ptr, len);
    4580                             }
    4581                         }
    4582                     }
    4583                     else if (pkt->stream_index == subIdx)
    4584                     {
    4585                         QMutexLocker locker(avcodeclock);
    4586                         avcodec_decode_subtitle(curstream->codec,
    4587                                                 &subtitle, &gotSubtitles,
    4588                                                 ptr, len);
    4589                     }
    4590 
    4591                     // the subtitle decoder always consumes the whole packet
    4592                     ptr += len;
    4593                     len = 0;
    4594 
    4595                     if (gotSubtitles)
    4596                     {
    4597                         subtitle.start_display_time += pts;
    4598                         subtitle.end_display_time += pts;
    4599                         GetNVP()->AddAVSubtitle(subtitle);
    4600 
    4601                         VERBOSE(VB_PLAYBACK|VB_TIMESTAMP, LOC +
    4602                                 QString("subtl timecode %1 %2 %3 %4")
    4603                                 .arg(pkt->pts).arg(pkt->dts)
    4604                                 .arg(subtitle.start_display_time)
    4605                                 .arg(subtitle.end_display_time));
    4606                     }
    4607 
    4608                     break;
    4609                 }
    4610                 default:
    4611                 {
    4612                     AVCodecContext *enc = curstream->codec;
    4613                     VERBOSE(VB_IMPORTANT, LOC_ERR +
    4614                             QString("Decoding - id(%1) type(%2)")
    4615                             .arg(codec_id_string(enc->codec_id))
    4616                             .arg(codec_type_string(enc->codec_type)));
    4617                     have_err = true;
    4618                     break;
    4619                 }
    4620             }
    4621 
    4622             if (!have_err)
    4623             {
    4624                 ptr += ret;
    4625                 len -= ret;
    4626                 frame_decoded = 1;
    4627                 firstloop = false;
    4628             }
    4629         }
    4630 
    4631         av_free_packet(pkt);
    4632     }
    4633 
    4634     if (pkt)
    4635         delete pkt;
    4636 
    46374556    return true;
    46384557}
    46394558
     
    48934812    return true;
    48944813}
    48954814
     4815char* AvFormatDecoder::ConvertSampleFormat(const AVCodecContext *ctx,
     4816                                           int &decoded)
     4817{
     4818    if (audio_src_fmt != ctx->sample_fmt)
     4819    {
     4820        if (reformat_ctx)
     4821            av_audio_convert_free(reformat_ctx);
     4822        reformat_ctx = av_audio_convert_alloc(SAMPLE_FMT_S16, 1,
     4823                                              ctx->sample_fmt, 1, NULL, 0);
     4824
     4825        if (!reformat_ctx ||
     4826            (!audioSamplesResampled &&
     4827             !(audioSamplesResampled =
     4828                (short int *)av_mallocz(AVCODEC_MAX_AUDIO_FRAME_SIZE *
     4829                                        sizeof(*audioSamplesResampled)))))
     4830        {
     4831            VERBOSE(VB_PLAYBACK,
     4832                QString("Cannot convert %1 sample format to %2 sample format")
     4833                    .arg(avcodec_get_sample_fmt_name(ctx->sample_fmt))
     4834                    .arg(avcodec_get_sample_fmt_name(SAMPLE_FMT_S16)));
     4835            return NULL;
     4836        }
     4837
     4838        audio_src_fmt = ctx->sample_fmt;
     4839    }
     4840
     4841    if (reformat_ctx)
     4842    {
     4843        const void *ibuf[6] = {audioSamples};
     4844        void *obuf[6]       = {audioSamplesResampled};
     4845        int is[6]         = {av_get_bits_per_sample_format(ctx->sample_fmt)>>3};
     4846        int os[6]           = {2};
     4847        int samples         = decoded / is[0];
     4848
     4849        if (av_audio_convert(reformat_ctx, obuf, os, ibuf, is, samples) < 0)
     4850        {
     4851            VERBOSE(VB_PLAYBACK, "av_audio_convert() failed");
     4852            return NULL;
     4853        }
     4854
     4855        decoded = samples << 1;
     4856        return (char *)audioSamplesResampled;
     4857    }
     4858
     4859    return NULL;
     4860}
     4861
    48964862static int encode_frame(bool dts, unsigned char *data, int len,
    48974863                        short *samples, int &samples_size)
    48984864{