Ticket #5900: audioencoding-trunk-7.patch

File audioencoding-trunk-7.patch, 105.2 KB (added by foobum@…, 15 years ago)

against r20844

  • mythplugins/mythmusic/mythmusic/aacdecoder.cpp

    diff --git a/mythplugins/mythmusic/mythmusic/aacdecoder.cpp b/mythplugins/mythmusic/mythmusic/aacdecoder.cpp
    index 0e5b1ed..968c211 100644
    a b  
    2929// MythTV headers
    3030#include <mythtv/audiooutput.h>
    3131#include <mythtv/mythcontext.h>
     32#include <mythtv/ffmpeg/avcodec.h>
    3233
    3334// MythMusic headers
    3435#include "aacdecoder.h"
    bool aacDecoder::initializeMP4() 
    401402    if (output())
    402403    {
    403404        const AudioSettings settings(
    404             16 /*bits*/, channels, sample_rate,
     405            16 /*bits*/, channels, CODEC_ID_AAC, sample_rate,
    405406            false /* AC3/DTS pass through */);
    406407        output()->Reconfigure(settings);
    407408        output()->SetSourceBitrate(bitrate);
  • mythplugins/mythmusic/mythmusic/avfdecoder.cpp

    diff --git a/mythplugins/mythmusic/mythmusic/avfdecoder.cpp b/mythplugins/mythmusic/mythmusic/avfdecoder.cpp
    index 260612f..c7e2ace 100644
    a b bool avfDecoder::initialize() 
    253253    if (output())
    254254    {
    255255        const AudioSettings settings(
    256             16 /*bits*/, m_audioDec->channels, m_audioDec->sample_rate,
    257             false /* AC3/DTS pass through */);
     256            16 /*bits*/, m_audioDec->channels, m_audioDec->codec_id,
     257            m_audioDec->sample_rate, false /* AC3/DTS pass through */);
    258258        output()->Reconfigure(settings);
    259259        output()->SetSourceBitrate(m_audioDec->bit_rate);
    260260    }
  • mythplugins/mythmusic/mythmusic/cddecoder.cpp

    diff --git a/mythplugins/mythmusic/mythmusic/cddecoder.cpp b/mythplugins/mythmusic/mythmusic/cddecoder.cpp
    index 9eb0d74..9caaf24 100644
    a b using namespace std; 
    1414
    1515#include <mythtv/mythcontext.h>
    1616#include <mythtv/mythmediamonitor.h>
     17#include <mythtv/ffmpeg/avcodec.h>
    1718
    1819CdDecoder::CdDecoder(const QString &file, DecoderFactory *d, QIODevice *i,
    1920                     AudioOutput *o) :
    bool CdDecoder::initialize() 
    149150    if (output())
    150151    {
    151152        const AudioSettings settings(
    152             16 /*bits*/, chan, freq, false /* AC3/DTS passthru */);
     153            16 /*bits*/, chan, CODEC_ID_PCM_S16LE, freq,
     154            false /* AC3/DTS passthru */);
    153155        output()->Reconfigure(settings);
    154156        output()->SetSourceBitrate(44100 * 2 * 16);
    155157    }
  • mythplugins/mythmusic/mythmusic/main.cpp

    diff --git a/mythplugins/mythmusic/mythmusic/main.cpp b/mythplugins/mythmusic/mythmusic/main.cpp
    index cde9575..c520219 100644
    a b void setupKeys(void) 
    367367    REG_KEY("Music", "VOLUMEDOWN", "Volume down",       "[,{,F10,Volume Down");
    368368    REG_KEY("Music", "VOLUMEUP",   "Volume up",         "],},F11,Volume Up");
    369369    REG_KEY("Music", "MUTE",       "Mute",              "|,\\,F9,Volume Mute");
     370    REG_KEY("Music", "TOGGLEUPMIX","Toggle upmixer",             "Ctrl+U");
    370371    REG_KEY("Music", "CYCLEVIS",   "Cycle visualizer mode",      "6");
    371372    REG_KEY("Music", "BLANKSCR",   "Blank screen",               "5");
    372373    REG_KEY("Music", "THMBUP",     "Increase rating",            "9");
  • mythplugins/mythmusic/mythmusic/musicplayer.cpp

    diff --git a/mythplugins/mythmusic/mythmusic/musicplayer.cpp b/mythplugins/mythmusic/mythmusic/musicplayer.cpp
    index fad20ee..088f88b 100644
    a b void MusicPlayer::stopDecoder(void) 
    348348
    349349void MusicPlayer::openOutputDevice(void)
    350350{
    351     QString adevice;
     351    QString adevice, pdevice;
    352352
    353353    if (gContext->GetSetting("MusicAudioDevice") == "default")
    354354        adevice = gContext->GetSetting("AudioOutputDevice");
    355355    else
    356356        adevice = gContext->GetSetting("MusicAudioDevice");
    357357
     358    pdevice = gContext->GetSetting("PassThruOutputDevice");
     359
    358360    // TODO: Error checking that device is opened correctly!
    359     m_output = AudioOutput::OpenAudio(adevice, "default", 16, 2, 44100,
    360                                     AUDIOOUTPUT_MUSIC, true, false);
     361    m_output = AudioOutput::OpenAudio(adevice, pdevice, 16, 2, 0, 44100,
     362                                      AUDIOOUTPUT_MUSIC, true, false);
    361363    m_output->setBufferSize(256 * 1024);
    362364    m_output->SetBlocking(false);
    363365
  • mythplugins/mythmusic/mythmusic/playbackbox.cpp

    diff --git a/mythplugins/mythmusic/mythmusic/playbackbox.cpp b/mythplugins/mythmusic/mythmusic/playbackbox.cpp
    index f8a2bc7..0a6a061 100644
    a b void PlaybackBoxMusic::keyPressEvent(QKeyEvent *e) 
    367367            changeSpeed(true);
    368368        else if (action == "MUTE")
    369369            toggleMute();
     370        else if (action == "TOGGLEUPMIX")
     371            toggleUpmix();
    370372        else if (action == "MENU" && visualizer_status != 2)
    371373        {
    372374            menufilters = false;
    void PlaybackBoxMusic::toggleMute() 
    12021204    }
    12031205}
    12041206
     1207void PlaybackBoxMusic::toggleUpmix()
     1208{
     1209    if (gPlayer->getOutput())
     1210        gPlayer->getOutput()->ToggleUpmix();
     1211}
     1212   
     1213
    12051214void PlaybackBoxMusic::showProgressBar()
    12061215{
    12071216    if (progress_bar && visualizer_status != 2)
  • mythplugins/mythmusic/mythmusic/playbackbox.h

    diff --git a/mythplugins/mythmusic/mythmusic/playbackbox.h b/mythplugins/mythmusic/mythmusic/playbackbox.h
    index ecc0207..b22c6ce 100644
    a b class PlaybackBoxMusic : public MythThemedDialog 
    6969    void changeVolume(bool up_or_down);
    7070    void changeSpeed(bool up_or_down);
    7171    void toggleMute();
     72    void toggleUpmix();
    7273    void resetTimer();
    7374    void hideVolume(){showVolume(false);}
    7475    void showVolume(bool on_or_off);
  • mythtv/libs/libavcodec/ac3dec.c

    diff --git a/mythtv/libs/libavcodec/ac3dec.c b/mythtv/libs/libavcodec/ac3dec.c
    index 99cd4e4..99c99be 100644
    a b static const uint8_t ac3_default_coeffs[8][5][2] = { 
    115115    { { 2, 7 }, { 5, 5 }, { 7, 2 }, { 6, 7 }, { 7, 6 }, },
    116116};
    117117
     118static const int channel_map[6] = { 0, 2, 3, 4, 1, 5 };
     119
    118120/**
    119121 * Symmetrical Dequantization
    120122 * reference: Section 7.3.3 Expansion of Mantissas for Symmetrical Quantization
    static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, 
    12251227    int blk, ch, err;
    12261228    const uint8_t *channel_map;
    12271229    const float *output[AC3_MAX_CHANNELS];
     1230    int16_t tmp;
    12281231
    12291232    /* initialize the GetBitContext with the start of valid AC-3 Frame */
    12301233    if (s->input_buffer) {
    static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, 
    13271330        out_samples += 256 * s->out_channels;
    13281331    }
    13291332    *data_size = s->num_blocks * 256 * avctx->channels * sizeof (int16_t);
     1333    if (avctx->channels == 6) {
     1334        for (int i = 0; i < *data_size / sizeof(int16_t); i += avctx->channels) {
     1335            tmp = out_samples[i+1];
     1336            out_samples[i+1] = out_samples[i+2];
     1337            out_samples[i+2] = out_samples[i+3];
     1338            out_samples[i+3] = out_samples[i+4];
     1339            out_samples[i+4] = tmp;
     1340        }
     1341    }
    13301342    return s->frame_size;
    13311343}
    13321344
  • mythtv/libs/libavcodec/dca.c

    diff --git a/mythtv/libs/libavcodec/dca.c b/mythtv/libs/libavcodec/dca.c
    index b42d3df..2f571d2 100644
    a b static int dca_decode_frame(AVCodecContext * avctx, 
    12411241    int16_t *samples = data;
    12421242    DCAContext *s = avctx->priv_data;
    12431243    int channels;
     1244    int16_t tmp;
    12441245
    12451246
    12461247    s->dca_buffer_size = dca_convert_bitstream(buf, buf_size, s->dca_buffer, DCA_MAX_FRAME_SIZE);
    static int dca_decode_frame(AVCodecContext * avctx, 
    12971298        s->dsp.float_to_int16_interleave(samples, s->samples_chanptr, 256, channels);
    12981299        samples += 256 * channels;
    12991300    }
    1300 
     1301     
     1302    if (channels == 6) {
     1303        for (i = 0; i < *data_size / sizeof(int16_t); i += channels) {
     1304            tmp = samples[i];
     1305            samples[i] = samples[i+1];
     1306            samples[i+1] = samples[i+2];
     1307            samples[i+2] = samples[i+3];
     1308            samples[i+3] = samples[i+4];
     1309            samples[i+4] = tmp;
     1310        }
     1311    }
     1312       
    13011313    return buf_size;
    13021314}
    13031315
  • mythtv/libs/libmyth/audiooutput.cpp

    diff --git a/mythtv/libs/libmyth/audiooutput.cpp b/mythtv/libs/libmyth/audiooutput.cpp
    index 17f7c64..f97fe44 100644
    a b using namespace std; 
    3333AudioOutput *AudioOutput::OpenAudio(
    3434    const QString &main_device,
    3535    const QString &passthru_device,
    36     int audio_bits, int audio_channels, int audio_samplerate,
     36    int audio_bits, int audio_channels,
     37    int audio_codec, int audio_samplerate,
    3738    AudioOutputSource source,
    3839    bool set_initial_vol, bool audio_passthru)
    3940{
    4041    AudioSettings settings(
    4142        main_device, passthru_device, audio_bits,
    42         audio_channels, audio_samplerate, source,
     43        audio_channels, audio_codec, audio_samplerate, source,
    4344        set_initial_vol, audio_passthru);
    4445
    4546    settings.FixPassThrough();
  • mythtv/libs/libmyth/audiooutput.h

    diff --git a/mythtv/libs/libmyth/audiooutput.h b/mythtv/libs/libmyth/audiooutput.h
    index 943bd77..7c55ac0 100644
    a b class MPUBLIC AudioOutput : public VolumeBase, public OutputListeners 
    1515    static AudioOutput *OpenAudio(
    1616        const QString &audiodevice,
    1717        const QString &passthrudevice,
    18         int audio_bits, int audio_channels, int audio_samplerate,
     18        int audio_bits, int audio_channels,
     19        int audio_codec, int audio_samplerate,
    1920        AudioOutputSource source,
    2021        bool set_initial_vol, bool audio_passthru);
    2122
    class MPUBLIC AudioOutput : public VolumeBase, public OutputListeners 
    6869   
    6970    virtual void bufferOutputData(bool y) = 0;
    7071    virtual int readOutputData(unsigned char *read_buffer, int max_length) = 0;
     72    virtual bool ToggleUpmix(void) = 0;
    7173
    7274  protected:
    7375    void Error(const QString &msg);
  • mythtv/libs/libmyth/audiooutputalsa.cpp

    diff --git a/mythtv/libs/libmyth/audiooutputalsa.cpp b/mythtv/libs/libmyth/audiooutputalsa.cpp
    index 5bd6445..788ae18 100644
    a b AudioOutputALSA::AudioOutputALSA(const AudioSettings &settings) : 
    3232AudioOutputALSA::~AudioOutputALSA()
    3333{
    3434    KillAudio();
     35    SetIECStatus(true);
     36}
     37
     38void AudioOutputALSA::SetIECStatus(bool audio) {
     39   
     40    snd_ctl_t *ctl;
     41    const char *spdif_str = SND_CTL_NAME_IEC958("", PLAYBACK, DEFAULT);
     42    int spdif_index = -1;
     43    snd_ctl_elem_list_t *clist;
     44    snd_ctl_elem_id_t *cid;
     45    snd_ctl_elem_value_t *cval;
     46    snd_aes_iec958_t iec958;
     47    int cidx, controls;
     48
     49    VERBOSE(VB_AUDIO, QString("Setting IEC958 status: %1")
     50                      .arg(audio ? "audio" : "non-audio"));
     51   
     52    snd_ctl_open(&ctl, "default", 0);
     53    snd_ctl_elem_list_alloca(&clist);
     54    snd_ctl_elem_list(ctl, clist);
     55    snd_ctl_elem_list_alloc_space(clist, snd_ctl_elem_list_get_count(clist));
     56    snd_ctl_elem_list(ctl, clist);
     57    controls = snd_ctl_elem_list_get_used(clist);
     58    for (cidx = 0; cidx < controls; cidx++) {
     59        if (!strcmp(snd_ctl_elem_list_get_name(clist, cidx), spdif_str))
     60            if (spdif_index < 0 ||
     61                snd_ctl_elem_list_get_index(clist, cidx) == (uint)spdif_index)
     62                    break;
     63    }
     64
     65    if (cidx >= controls)
     66        return;
     67
     68    snd_ctl_elem_id_alloca(&cid);
     69    snd_ctl_elem_list_get_id(clist, cidx, cid);
     70    snd_ctl_elem_value_alloca(&cval);
     71    snd_ctl_elem_value_set_id(cval, cid);
     72    snd_ctl_elem_read(ctl,cval);
     73    snd_ctl_elem_value_get_iec958(cval, &iec958);
     74   
     75    if (!audio)
     76        iec958.status[0] |= IEC958_AES0_NONAUDIO;
     77    else
     78        iec958.status[0] &= ~IEC958_AES0_NONAUDIO;
     79
     80    snd_ctl_elem_value_set_iec958(cval, &iec958);
     81    snd_ctl_elem_write(ctl, cval);
     82
     83}
     84
     85vector<int> AudioOutputALSA::GetSupportedRates()
     86{
     87    snd_pcm_hw_params_t *params;
     88    int err;
     89    const int srates[] = { 8000, 11025, 16000, 22050, 32000, 44100, 48000 };
     90    vector<int> rates(srates, srates + sizeof(srates) / sizeof(int) );
     91    QString real_device;
     92   
     93    if (audio_passthru || audio_enc)
     94        real_device = audio_passthru_device;
     95    else
     96        real_device = audio_main_device;
     97
     98    if((err = snd_pcm_open(&pcm_handle, real_device.toAscii(),
     99                           SND_PCM_STREAM_PLAYBACK,
     100                           SND_PCM_NONBLOCK|SND_PCM_NO_AUTO_RESAMPLE)) < 0)
     101    {
     102        Error(QString("snd_pcm_open(%1): %2")
     103              .arg(real_device).arg(snd_strerror(err)));
     104
     105        if (pcm_handle)
     106        {
     107            snd_pcm_close(pcm_handle);
     108            pcm_handle = NULL;
     109        }
     110        rates.clear();
     111        return rates;
     112    }
     113   
     114    snd_pcm_hw_params_alloca(&params);
     115
     116    if ((err = snd_pcm_hw_params_any(pcm_handle, params)) < 0)
     117    {
     118        Error(QString("Broken configuration for playback; no configurations"
     119              " available: %1").arg(snd_strerror(err)));
     120        snd_pcm_close(pcm_handle);
     121        pcm_handle = NULL;
     122        rates.clear();
     123        return rates;
     124    }
     125   
     126    vector<int>::iterator it;
     127
     128    for (it = rates.begin(); it < rates.end(); it++)
     129        if(snd_pcm_hw_params_test_rate(pcm_handle, params, *it, 0) < 0)
     130            rates.erase(it--);
     131   
     132    snd_pcm_close(pcm_handle);
     133    pcm_handle = NULL;
     134
     135    return rates;
    35136}
    36137
    37138bool AudioOutputALSA::OpenDevice()
    bool AudioOutputALSA::OpenDevice() 
    39140    snd_pcm_format_t format;
    40141    unsigned int buffer_time, period_time;
    41142    int err;
     143    QString real_device;
    42144
    43145    if (pcm_handle != NULL)
    44146        CloseDevice();
    45147
    46148    pcm_handle = NULL;
    47149    numbadioctls = 0;
    48 
    49     QString real_device = (audio_passthru) ?
    50         audio_passthru_device : audio_main_device;
     150   
     151    if (audio_passthru || audio_enc)
     152    {
     153        real_device = audio_passthru_device;
     154        SetIECStatus(false);
     155    }
     156    else
     157    {
     158        real_device = audio_main_device;
     159        SetIECStatus(true);
     160    }
    51161
    52162    VERBOSE(VB_GENERAL, QString("Opening ALSA audio device '%1'.")
    53163            .arg(real_device));
  • mythtv/libs/libmyth/audiooutputalsa.h

    diff --git a/mythtv/libs/libmyth/audiooutputalsa.h b/mythtv/libs/libmyth/audiooutputalsa.h
    index a156edd..c260982 100644
    a b class AudioOutputALSA : public AudioOutputBase 
    6565    virtual void WriteAudio(unsigned char *aubuf, int size);
    6666    virtual int  GetSpaceOnSoundcard(void) const;
    6767    virtual int  GetBufferedOnSoundcard(void) const;
     68    virtual vector<int> GetSupportedRates(void);
    6869
    6970  private:
     71    void SetIECStatus(bool audio);
    7072    inline int SetParameters(snd_pcm_t *handle,
    7173                             snd_pcm_format_t format, unsigned int channels,
    7274                             unsigned int rate, unsigned int buffer_time,
  • mythtv/libs/libmyth/audiooutputarts.h

    diff --git a/mythtv/libs/libmyth/audiooutputarts.h b/mythtv/libs/libmyth/audiooutputarts.h
    index f985ef8..35ec39f 100644
    a b class AudioOutputARTS : public AudioOutputBase 
    2727    virtual void WriteAudio(unsigned char *aubuf, int size);
    2828    virtual int  GetSpaceOnSoundcard(void) const;
    2929    virtual int  GetBufferedOnSoundcard(void) const;
    30 
    31      
     30    virtual vector<int> GetSupportedRates(void)
     31        { vector<int> rates; return rates; }
    3232
    3333  private:
    3434    arts_stream_t pcm_handle;
  • mythtv/libs/libmyth/audiooutputbase.cpp

    diff --git a/mythtv/libs/libmyth/audiooutputbase.cpp b/mythtv/libs/libmyth/audiooutputbase.cpp
    index ef2f3d5..63f90a4 100644
    a b  
    2121AudioOutputBase::AudioOutputBase(const AudioSettings &settings) :
    2222    // protected
    2323    effdsp(0),                  effdspstretched(0),
    24     audio_channels(-1),         audio_bytes_per_sample(0),
    25     audio_bits(-1),             audio_samplerate(-1),
    26     audio_buffer_unused(0),
     24    audio_channels(-1),         audio_codec(CODEC_ID_NONE),
     25    audio_bytes_per_sample(0),  audio_bits(-1),
     26    audio_samplerate(-1),       audio_buffer_unused(0),
    2727    fragment_size(0),           soundcard_buffer_size(0),
    2828
    2929    audio_main_device(settings.GetMainDevice()),
    3030    audio_passthru_device(settings.GetPassthruDevice()),
    31     audio_passthru(false),      audio_stretchfactor(1.0f),
     31    audio_passthru(false),      audio_enc(false),
     32    audio_reenc(false),         audio_stretchfactor(1.0f),
    3233
    33     audio_codec(NULL),
    3434    source(settings.source),    killaudio(false),
    3535
    3636    pauseaudio(false),          audio_actually_paused(false),
    AudioOutputBase::AudioOutputBase(const AudioSettings &settings) : 
    4848    encoder(NULL),
    4949    upmixer(NULL),
    5050    source_audio_channels(-1),
     51    source_audio_samplerate(0),
    5152    source_audio_bytes_per_sample(0),
    5253    needs_upmix(false),
    5354    surround_mode(FreeSurround::SurroundModePassive),
     55    old_audio_stretchfactor(1.0),
    5456
    5557    blocking(false),
    5658
    AudioOutputBase::AudioOutputBase(const AudioSettings &settings) : 
    7981    memset(&audiotime_updated, 0, sizeof(audiotime_updated));
    8082    memset(audiobuffer,        0, sizeof(char)  * kAudioRingBufferSize);
    8183    configured_audio_channels = gContext->GetNumSetting("MaxChannels", 2);
     84    orig_config_channels = configured_audio_channels;
     85    allow_ac3_passthru = gContext->GetNumSetting("AC3PassThru", false);
     86    src_quality = gContext->GetNumSetting("SRCQuality", 3);
    8287
    8388    // You need to call Reconfigure from your concrete class.
    8489    // Reconfigure(laudio_bits,       laudio_channels,
    void AudioOutputBase::SetStretchFactorLocked(float laudio_stretchfactor) 
    124129            VERBOSE(VB_GENERAL, LOC + QString("Using time stretch %1")
    125130                                        .arg(audio_stretchfactor));
    126131            pSoundStretch = new soundtouch::SoundTouch();
    127             if (audio_codec)
    128             {
    129                 if (!encoder)
    130                 {
    131                     VERBOSE(VB_AUDIO, LOC +
    132                             QString("Creating Encoder for codec %1 origfs %2")
    133                             .arg(audio_codec->codec_id)
    134                             .arg(audio_codec->frame_size));
    135 
    136                     encoder = new AudioOutputDigitalEncoder();
    137                     if (!encoder->Init(audio_codec->codec_id,
    138                                 audio_codec->bit_rate,
    139                                 audio_codec->sample_rate,
    140                                 audio_codec->channels
    141                                 ))
    142                     {
    143                         // eeks
    144                         delete encoder;
    145                         encoder = NULL;
    146                         VERBOSE(VB_AUDIO, LOC +
    147                                 QString("Failed to Create Encoder"));
    148                     }
    149                 }
    150             }
    151             if (audio_codec && encoder)
    152             {
    153                 pSoundStretch->setSampleRate(audio_codec->sample_rate);
    154                 pSoundStretch->setChannels(audio_codec->channels);
    155             }
    156             else
    157             {
    158                 pSoundStretch->setSampleRate(audio_samplerate);
    159                 pSoundStretch->setChannels(audio_channels);
    160             }
     132            pSoundStretch->setSampleRate(audio_samplerate);
     133            pSoundStretch->setChannels(upmixer ?
     134                configured_audio_channels : source_audio_channels);
    161135
    162136            pSoundStretch->setTempo(audio_stretchfactor);
    163137            pSoundStretch->setSetting(SETTING_SEQUENCE_MS, 35);
    void AudioOutputBase::SetStretchFactorLocked(float laudio_stretchfactor) 
    165139            // dont need these with only tempo change
    166140            //pSoundStretch->setPitch(1.0);
    167141            //pSoundStretch->setRate(1.0);
    168 
    169142            //pSoundStretch->setSetting(SETTING_USE_QUICKSEEK, true);
    170143            //pSoundStretch->setSetting(SETTING_USE_AA_FILTER, false);
    171144        }
    float AudioOutputBase::GetStretchFactor(void) const 
    183156    return audio_stretchfactor;
    184157}
    185158
     159bool AudioOutputBase::ToggleUpmix(void)
     160{
     161    if (orig_config_channels == 2 || source_audio_channels > 2 ||
     162        audio_passthru)
     163        return false;
     164    if (configured_audio_channels == 6)
     165        configured_audio_channels = 2;
     166    else
     167        configured_audio_channels = 6;
     168
     169    const AudioSettings settings(audio_bits, source_audio_channels,
     170                                 audio_codec, source_audio_samplerate,
     171                                 audio_passthru);
     172    Reconfigure(settings);
     173    return (configured_audio_channels == 6);
     174}
     175
     176
    186177void AudioOutputBase::Reconfigure(const AudioSettings &orig_settings)
    187178{
    188179    AudioSettings settings = orig_settings;
    189180
    190     int codec_id = CODEC_ID_NONE;
    191     int lcodec_id = CODEC_ID_NONE;
    192     int lcchannels = 0;
    193     int cchannels = 0;
    194181    int lsource_audio_channels = settings.channels;
    195182    bool lneeds_upmix = false;
     183    bool laudio_reenc = false;
    196184
    197     if (settings.codec)
     185    // Are we reencoding a (previously) timestretched bitstream?
     186    if ((settings.codec == CODEC_ID_AC3 || settings.codec == CODEC_ID_DTS) &&
     187        !settings.use_passthru && allow_ac3_passthru)
    198188    {
    199         lcodec_id = ((AVCodecContext*)settings.codec)->codec_id;
    200         settings.bits = 16;
    201         settings.channels = 2;
    202         lsource_audio_channels = settings.channels;
    203         settings.samplerate = 48000;
    204         lcchannels = ((AVCodecContext*)settings.codec)->channels;
     189        laudio_reenc = true;
     190        VERBOSE(VB_AUDIO, LOC + "Reencoding decoded AC3/DTS to AC3");
    205191    }
    206192
    207     if (audio_codec)
    208     {
    209         codec_id = audio_codec->codec_id;
    210         cchannels = ((AVCodecContext*)audio_codec)->channels;
    211     }
    212 
    213     if ((configured_audio_channels == 6) &&
    214         !(settings.codec || audio_codec))
     193    // Enough channels? Upmix if not
     194    if (settings.channels < configured_audio_channels &&
     195        !settings.use_passthru)
    215196    {
    216197        settings.channels = configured_audio_channels;
    217198        lneeds_upmix = true;
    void AudioOutputBase::Reconfigure(const AudioSettings &orig_settings) 
    224205        settings.samplerate == audio_samplerate && !need_resampler &&
    225206        settings.use_passthru == audio_passthru &&
    226207        lneeds_upmix == needs_upmix &&
    227         lcodec_id == codec_id && lcchannels == cchannels);
     208        laudio_reenc == audio_reenc);
    228209    bool upmix_deps =
    229210        (lsource_audio_channels == source_audio_channels);
    230211    if (general_deps && upmix_deps)
    void AudioOutputBase::Reconfigure(const AudioSettings &orig_settings) 
    251232    waud = raud = 0;
    252233    audio_actually_paused = false;
    253234
    254     bool redo_stretch = (pSoundStretch && audio_channels != settings.channels);
    255235    audio_channels = settings.channels;
    256236    source_audio_channels = lsource_audio_channels;
    257237    audio_bits = settings.bits;
    258     audio_samplerate = settings.samplerate;
    259     audio_codec = (AVCodecContext*)settings.codec;
     238    source_audio_samplerate = audio_samplerate = settings.samplerate;
     239    audio_reenc = laudio_reenc;
    260240    audio_passthru = settings.use_passthru;
    261241    needs_upmix = lneeds_upmix;
    262242
    void AudioOutputBase::Reconfigure(const AudioSettings &orig_settings) 
    265245        Error("AudioOutput only supports 8 or 16bit audio.");
    266246        return;
    267247    }
    268     audio_bytes_per_sample = audio_channels * audio_bits / 8;
    269     source_audio_bytes_per_sample = source_audio_channels * audio_bits / 8;
     248   
     249    VERBOSE(VB_AUDIO, LOC + QString("Original audio codec was %1")
     250                            .arg(codec_id_string((CodecID)audio_codec)));
    270251
    271252    need_resampler = false;
    272253    killaudio = false;
    void AudioOutputBase::Reconfigure(const AudioSettings &orig_settings) 
    275256    internal_vol = gContext->GetNumSetting("MythControlsVolume", 0);
    276257
    277258    numlowbuffer = 0;
     259   
     260    // Find out what sample rates we can output (if output layer supports it)
     261    vector<int> rates = GetSupportedRates();
     262    vector<int>::iterator it;
     263    bool resample = true;
     264
     265    for (it = rates.begin(); it < rates.end(); it++)
     266    {
     267        VERBOSE(VB_AUDIO, LOC + QString("Sample rate %1 is supported")
     268                                .arg(*it));
     269        if (*it == audio_samplerate)
     270            resample = false;
     271    }
     272
     273    // Assume 48k if we can't get supported rates
     274    if (rates.empty())
     275        rates.push_back(48000);
     276
     277    if (resample)
     278    {
     279        int error;
     280        audio_samplerate = *(rates.end());
     281        VERBOSE(VB_GENERAL, LOC + QString("Using resampler. From: %1 to %2")
     282            .arg(settings.samplerate).arg(audio_samplerate));
     283        src_ctx = src_new(3-src_quality, source_audio_channels, &error);
     284        if (error)
     285        {
     286            Error(QString("Error creating resampler, the error was: %1")
     287                  .arg(src_strerror(error)) );
     288            src_ctx = NULL;
     289            return;
     290        }
     291        src_data.src_ratio = (double) audio_samplerate / settings.samplerate;
     292        src_data.data_in = src_in;
     293        src_data.data_out = src_out;
     294        src_data.output_frames = 16384*6;
     295        need_resampler = true;
     296    }
     297   
     298    // Encode to AC-3 if not passing thru , there's > 2 channels
     299    // and a passthru device is defined
     300    if (
     301        !audio_passthru && allow_ac3_passthru &&
     302        (audio_channels > 2 || audio_reenc)
     303       )
     304    {
     305        VERBOSE(VB_AUDIO, LOC + "Creating AC-3 Encoder");
     306        encoder = new AudioOutputDigitalEncoder();
     307        if (!encoder->Init(CODEC_ID_AC3, 448000, audio_samplerate,
     308                           audio_channels))
     309        {
     310            VERBOSE(VB_AUDIO, LOC + "Can't create AC-3 encoder");
     311            delete encoder;
     312            encoder = NULL;
     313        }
     314       
     315        audio_enc = true;
     316    }       
     317   
     318    if(audio_passthru || audio_enc)
     319        // AC-3 output - soundcard expects a 2ch 48k stream
     320        audio_channels = 2;
     321   
     322    audio_bytes_per_sample = audio_channels * audio_bits / 8;
     323    source_audio_bytes_per_sample = source_audio_channels * audio_bits / 8;
    278324
     325   
    279326    VERBOSE(VB_GENERAL, QString("Opening audio device '%1'. ch %2(%3) sr %4")
    280327            .arg(audio_main_device).arg(audio_channels)
    281328            .arg(source_audio_channels).arg(audio_samplerate));
    void AudioOutputBase::Reconfigure(const AudioSettings &orig_settings) 
    309356    current_seconds = -1;
    310357    source_bitrate = -1;
    311358
    312     // NOTE: this won't do anything as above samplerate vars are set equal
    313     // Check if we need the resampler
    314     if (audio_samplerate != settings.samplerate)
    315     {
    316         int error;
    317         VERBOSE(VB_GENERAL, LOC + QString("Using resampler. From: %1 to %2")
    318                                .arg(settings.samplerate).arg(audio_samplerate));
    319         src_ctx = src_new (SRC_SINC_BEST_QUALITY, audio_channels, &error);
    320         if (error)
    321         {
    322             Error(QString("Error creating resampler, the error was: %1")
    323                   .arg(src_strerror(error)) );
    324             return;
    325         }
    326         src_data.src_ratio = (double) audio_samplerate / settings.samplerate;
    327         src_data.data_in = src_in;
    328         src_data.data_out = src_out;
    329         src_data.output_frames = 16384*6;
    330         need_resampler = true;
    331     }
    332 
    333359    if (needs_upmix)
    334360    {
    335361        VERBOSE(VB_AUDIO, LOC + QString("create upmixer"));
    void AudioOutputBase::Reconfigure(const AudioSettings &orig_settings) 
    344370            (FreeSurround::SurroundMode)surround_mode);
    345371
    346372        VERBOSE(VB_AUDIO, LOC +
    347                 QString("create upmixer done with surround mode %1")
     373                QString("Create upmixer done with surround mode %1")
    348374                .arg(surround_mode));
    349375    }
    350376
    351377    VERBOSE(VB_AUDIO, LOC + QString("Audio Stretch Factor: %1")
    352378            .arg(audio_stretchfactor));
    353     VERBOSE(VB_AUDIO, QString("Audio Codec Used: %1")
    354             .arg((audio_codec) ?
    355                  codec_id_string(audio_codec->codec_id) : "not set"));
    356 
    357     if (redo_stretch)
    358     {
    359         delete pSoundStretch;
    360         pSoundStretch = NULL;
    361         SetStretchFactorLocked(audio_stretchfactor);
    362     }
    363     else
    364     {
    365         SetStretchFactorLocked(audio_stretchfactor);
    366         if (pSoundStretch)
    367         {
    368             // if its passthru then we need to reencode
    369             if (audio_codec)
    370             {
    371                 if (!encoder)
    372                 {
    373                     VERBOSE(VB_AUDIO, LOC +
    374                             QString("Creating Encoder for codec %1")
    375                             .arg(audio_codec->codec_id));
    376 
    377                     encoder = new AudioOutputDigitalEncoder();
    378                     if (!encoder->Init(audio_codec->codec_id,
    379                                 audio_codec->bit_rate,
    380                                 audio_codec->sample_rate,
    381                                 audio_codec->channels
    382                                 ))
    383                     {
    384                         // eeks
    385                         delete encoder;
    386                         encoder = NULL;
    387                         VERBOSE(VB_AUDIO, LOC + "Failed to Create Encoder");
    388                     }
    389                 }
    390             }
    391             if (audio_codec && encoder)
    392             {
    393                 pSoundStretch->setSampleRate(audio_codec->sample_rate);
    394                 pSoundStretch->setChannels(audio_codec->channels);
    395             }
    396             else
    397             {
    398                 pSoundStretch->setSampleRate(audio_samplerate);
    399                 pSoundStretch->setChannels(audio_channels);
    400             }
    401         }
    402     }
    403379
     380    SetStretchFactorLocked(old_audio_stretchfactor);
     381   
    404382    // Setup visualisations, zero the visualisations buffers
    405383    prepareVisuals();
    406384
    void AudioOutputBase::KillAudio() 
    436414    VERBOSE(VB_AUDIO, LOC + "Killing AudioOutputDSP");
    437415    killaudio = true;
    438416    StopOutputThread();
     417    QMutexLocker lock1(&audio_buflock);
    439418
    440419    // Close resampler?
    441420    if (src_ctx)
     421    {
    442422        src_delete(src_ctx);
     423        src_ctx = NULL;
     424    }
     425               
    443426    need_resampler = false;
    444427
    445428    // close sound stretcher
    void AudioOutputBase::KillAudio() 
    447430    {
    448431        delete pSoundStretch;
    449432        pSoundStretch = NULL;
     433        old_audio_stretchfactor = audio_stretchfactor;
     434        audio_stretchfactor = 1.0;
    450435    }
    451436
    452437    if (encoder)
    void AudioOutputBase::KillAudio() 
    461446        upmixer = NULL;
    462447    }
    463448    needs_upmix = false;
     449    audio_enc = false;
    464450
    465451    CloseDevice();
    466452
    int AudioOutputBase::GetAudiotime(void) 
    562548    ret += (now.tv_usec - audiotime_updated.tv_usec) / 1000;
    563549    ret = (long long)(ret * audio_stretchfactor);
    564550
    565 #if 1
    566551    VERBOSE(VB_AUDIO+VB_TIMESTAMP,
    567552            QString("GetAudiotime now=%1.%2, set=%3.%4, ret=%5, audt=%6 sf=%7")
    568553            .arg(now.tv_sec).arg(now.tv_usec)
    int AudioOutputBase::GetAudiotime(void) 
    571556            .arg(audiotime)
    572557            .arg(audio_stretchfactor)
    573558           );
    574 #endif
    575559
    576560    ret += audiotime;
    577561
    void AudioOutputBase::SetAudiotime(void) 
    611595
    612596    // include algorithmic latencies
    613597    if (pSoundStretch)
    614     {
    615         // add the effect of any unused but processed samples,
    616         // AC3 reencode does this
    617         totalbuffer += (int)(pSoundStretch->numSamples() *
    618                              audio_bytes_per_sample);
    619         // add the effect of unprocessed samples in time stretch algo
    620598        totalbuffer += (int)((pSoundStretch->numUnprocessedSamples() *
    621599                              audio_bytes_per_sample) / audio_stretchfactor);
    622     }
    623600
    624601    if (upmixer && needs_upmix)
    625     {
    626602        totalbuffer += upmixer->sampleLatency() * audio_bytes_per_sample;
    627     }
     603
     604    if (encoder)
     605         totalbuffer += encoder->Buffered();
    628606
    629607    audiotime = audbuf_timecode - (int)(totalbuffer * 100000.0 /
    630608                                   (audio_bytes_per_sample * effdspstretched));
    631609
    632610    gettimeofday(&audiotime_updated, NULL);
    633 #if 1
     611   
    634612    VERBOSE(VB_AUDIO+VB_TIMESTAMP,
    635613            QString("SetAudiotime set=%1.%2, audt=%3 atc=%4 "
    636614                    "tb=%5 sb=%6 eds=%7 abps=%8 sf=%9")
    void AudioOutputBase::SetAudiotime(void) 
    642620            .arg(effdspstretched)
    643621            .arg(audio_bytes_per_sample)
    644622            .arg(audio_stretchfactor));
    645 #endif
    646623}
    647624
    648625int AudioOutputBase::GetAudioBufferedTime(void)
    bool AudioOutputBase::AddSamples(char *buffers[], int samples, 
    681658        return false; // would overflow
    682659    }
    683660
     661    QMutexLocker lock1(&audio_buflock);
     662
    684663    // resample input if necessary
    685664    if (need_resampler && src_ctx)
    686665    {
    bool AudioOutputBase::AddSamples(char *buffer, int samples, long long timecode) 
    725704    int abps = (encoder) ?
    726705        encoder->audio_bytes_per_sample : audio_bytes_per_sample;
    727706    int len = samples * abps;
     707   
     708    // Give original samples to mythmusic visualisation
     709    dispatchVisual((unsigned char *)buffer, len, timecode,
     710                   source_audio_channels, audio_bits);
    728711
    729712    // Check we have enough space to write the data
    730713    if (need_resampler && src_ctx)
    bool AudioOutputBase::AddSamples(char *buffer, int samples, long long timecode) 
    749732        return false; // would overflow
    750733    }
    751734
     735    QMutexLocker lock1(&audio_buflock);
     736
    752737    // resample input if necessary
    753738    if (need_resampler && src_ctx)
    754739    {
    int AudioOutputBase::WaitForFreeSpace(int samples) 
    808793            if (src_ctx)
    809794            {
    810795                int error = src_reset(src_ctx);
    811                 if (error)
     796                if (error)
     797                {
    812798                    VERBOSE(VB_IMPORTANT, LOC_ERR + QString(
    813799                            "Error occured while resetting resampler: %1")
    814800                            .arg(src_strerror(error)));
     801                    src_ctx = NULL;
     802                }
    815803            }
    816804        }
    817805    }
    int AudioOutputBase::WaitForFreeSpace(int samples) 
    821809void AudioOutputBase::_AddSamples(void *buffer, bool interleaved, int samples,
    822810                                  long long timecode)
    823811{
    824     audio_buflock.lock();
    825 
    826812    int len; // = samples * audio_bytes_per_sample;
    827813    int audio_bytes = audio_bits / 8;
    828814    int org_waud = waud;
    void AudioOutputBase::_AddSamples(void *buffer, bool interleaved, int samples, 
    839825            .arg(samples * abps)
    840826            .arg(kAudioRingBufferSize-afree).arg(afree).arg(timecode)
    841827            .arg(needs_upmix));
    842 
     828   
     829    len = WaitForFreeSpace(samples);
     830       
    843831    if (upmixer && needs_upmix)
    844832    {
    845833        int out_samples = 0;
     834        org_waud = waud;
    846835        int step = (interleaved)?source_audio_channels:1;
    847         len = WaitForFreeSpace(samples);    // test
     836       
    848837        for (int itemp = 0; itemp < samples; )
    849838        {
    850             // just in case it does a processing cycle, release the lock
    851             // to allow the output loop to do output
    852             audio_buflock.unlock();
    853839            if (audio_bytes == 2)
    854840            {
    855841                itemp += upmixer->putSamples(
    void AudioOutputBase::_AddSamples(void *buffer, bool interleaved, int samples, 
    866852                    source_audio_channels,
    867853                    (interleaved) ? 0 : samples);
    868854            }
    869             audio_buflock.lock();
    870855
    871856            int copy_samples = upmixer->numSamples();
    872857            if (copy_samples)
    void AudioOutputBase::_AddSamples(void *buffer, bool interleaved, int samples, 
    900885    }
    901886    else
    902887    {
    903         len = WaitForFreeSpace(samples);
    904 
    905888        if (interleaved)
    906889        {
    907890            char *mybuf = (char*)buffer;
    void AudioOutputBase::_AddSamples(void *buffer, bool interleaved, int samples, 
    936919        }
    937920    }
    938921
    939     if (samples > 0)
     922    if (samples <= 0)
     923        return;
     924       
     925    if (pSoundStretch)
    940926    {
    941         if (pSoundStretch)
     927        // does not change the timecode, only the number of samples
     928        // back to orig pos
     929        org_waud = waud;
     930        int bdiff = kAudioRingBufferSize - org_waud;
     931        int nSamplesToEnd = bdiff/abps;
     932        if (bdiff < len)
    942933        {
     934            pSoundStretch->putSamples((soundtouch::SAMPLETYPE*)
     935                                      (audiobuffer +
     936                                       org_waud), nSamplesToEnd);
     937            pSoundStretch->putSamples((soundtouch::SAMPLETYPE*)audiobuffer,
     938                                      (len - bdiff) / abps);
     939        }
     940        else
     941        {
     942            pSoundStretch->putSamples((soundtouch::SAMPLETYPE*)
     943                                      (audiobuffer + org_waud),
     944                                      len / abps);
     945        }
    943946
    944             // does not change the timecode, only the number of samples
    945             // back to orig pos
    946             org_waud = waud;
    947             int bdiff = kAudioRingBufferSize - org_waud;
    948             int nSamplesToEnd = bdiff/abps;
    949             if (bdiff < len)
    950             {
    951                 pSoundStretch->putSamples((soundtouch::SAMPLETYPE*)
    952                                           (audiobuffer +
    953                                            org_waud), nSamplesToEnd);
    954                 pSoundStretch->putSamples((soundtouch::SAMPLETYPE*)audiobuffer,
    955                                           (len - bdiff) / abps);
     947        int nSamples = pSoundStretch->numSamples();
     948        len = WaitForFreeSpace(nSamples);
     949       
     950        while ((nSamples = pSoundStretch->numSamples()))
     951        {
     952            if (nSamples > nSamplesToEnd)
     953                nSamples = nSamplesToEnd;
     954           
     955            nSamples = pSoundStretch->receiveSamples(
     956                (soundtouch::SAMPLETYPE*)
     957                (audiobuffer + org_waud), nSamples
     958            );
     959           
     960            if (nSamples == nSamplesToEnd) {
     961                org_waud = 0;
     962                nSamplesToEnd = kAudioRingBufferSize/abps;
    956963            }
    957             else
    958             {
    959                 pSoundStretch->putSamples((soundtouch::SAMPLETYPE*)
    960                                           (audiobuffer + org_waud),
    961                                           len / abps);
     964            else {
     965                org_waud += nSamples * abps;
     966                nSamplesToEnd -= nSamples;
    962967            }
     968           
     969        }
     970       
     971    }
    963972
    964             if (encoder)
    965             {
    966                 // pull out a packet's worth and reencode it until we
    967                 // don't have enough for any more packets
    968                 soundtouch::SAMPLETYPE *temp_buff =
    969                     (soundtouch::SAMPLETYPE*)encoder->GetFrameBuffer();
    970                 size_t frameSize = encoder->FrameSize()/abps;
     973    // Encode to AC-3?
     974    if (encoder)
     975    {
     976       
     977        org_waud = waud;
     978        int bdiff = kAudioRingBufferSize - org_waud;
     979        int to_get = 0;
    971980
    972                 VERBOSE(VB_AUDIO+VB_TIMESTAMP,
    973                         QString("_AddSamples Enc sfs=%1 bfs=%2 sss=%3")
    974                         .arg(frameSize)
    975                         .arg(encoder->FrameSize())
    976                         .arg(pSoundStretch->numSamples()));
    977 
    978                 // process the same number of samples as it creates
    979                 // a full encoded buffer just like before
    980                 while (pSoundStretch->numSamples() >= frameSize)
    981                 {
    982                     int got = pSoundStretch->receiveSamples(
    983                         temp_buff, frameSize);
    984                     int amount = encoder->Encode(temp_buff);
    985 
    986                     VERBOSE(VB_AUDIO+VB_TIMESTAMP,
    987                             QString("_AddSamples Enc bytes=%1 got=%2 left=%3")
    988                             .arg(amount)
    989                             .arg(got)
    990                             .arg(pSoundStretch->numSamples()));
    991 
    992                     if (!amount)
    993                         continue;
    994 
    995                     //len = WaitForFreeSpace(amount);
    996                     char *ob = encoder->GetOutBuff();
    997                     if (amount >= bdiff)
    998                     {
    999                         memcpy(audiobuffer + org_waud, ob, bdiff);
    1000                         ob += bdiff;
    1001                         amount -= bdiff;
    1002                         org_waud = 0;
    1003                     }
    1004                     if (amount > 0)
    1005                         memcpy(audiobuffer + org_waud, ob, amount);
    1006 
    1007                     bdiff = kAudioRingBufferSize - amount;
    1008                     org_waud = (org_waud + amount) % kAudioRingBufferSize;
    1009                 }
    1010             }
    1011             else
     981        if (bdiff < len)
     982        {
     983            encoder->Encode(audiobuffer + org_waud, bdiff);
     984            to_get = encoder->Encode(audiobuffer, len - bdiff);
     985        }
     986        else
     987            to_get = encoder->Encode(audiobuffer + org_waud, len);
     988       
     989        if (to_get > 0)
     990        {
     991           
     992            if (to_get >= bdiff)
    1012993            {
    1013                 int newLen = 0;
    1014                 int nSamples;
    1015                 len = WaitForFreeSpace(pSoundStretch->numSamples() *
    1016                                        audio_bytes_per_sample);
    1017                 do
    1018                 {
    1019                     int samplesToGet = len/audio_bytes_per_sample;
    1020                     if (samplesToGet > nSamplesToEnd)
    1021                     {
    1022                         samplesToGet = nSamplesToEnd;
    1023                     }
    1024 
    1025                     nSamples = pSoundStretch->receiveSamples(
    1026                         (soundtouch::SAMPLETYPE*)
    1027                         (audiobuffer + org_waud), samplesToGet);
    1028                     if (nSamples == nSamplesToEnd)
    1029                     {
    1030                         org_waud = 0;
    1031                         nSamplesToEnd = kAudioRingBufferSize/audio_bytes_per_sample;
    1032                     }
    1033                     else
    1034                     {
    1035                         int bufsz = nSamples * audio_bytes_per_sample;
    1036                         org_waud = (org_waud + bufsz) % kAudioRingBufferSize;
    1037                         nSamplesToEnd -= nSamples;
    1038                     }
    1039 
    1040                     newLen += nSamples * audio_bytes_per_sample;
    1041                     len -= nSamples * audio_bytes_per_sample;
    1042                 } while (nSamples > 0);
     994                encoder->GetFrames(audiobuffer + org_waud, bdiff);
     995                to_get -= bdiff;
     996                org_waud = 0;
    1043997            }
    1044         }
     998            if (to_get > 0)
     999                encoder->GetFrames(audiobuffer + org_waud, to_get);
    10451000
    1046         waud = org_waud;
    1047         lastaudiolen = audiolen(false);
     1001            org_waud += to_get;
    10481002
    1049         if (timecode < 0)
    1050         {
    1051             // mythmusic doesn't give timestamps..
    1052             timecode = (int)((samples_buffered * 100000.0) / effdsp);
    10531003        }
    1054  
    1055         samples_buffered += samples;
    1056  
    1057         /* we want the time at the end -- but the file format stores
    1058            time at the start of the chunk. */
    1059         // even with timestretch, timecode is still calculated from original
    1060         // sample count
    1061         audbuf_timecode = timecode + (int)((samples * 100000.0) / effdsp);
    10621004
    1063         if (interleaved)
    1064         {
    1065             dispatchVisual((unsigned char *)buffer, len, timecode,
    1066                            source_audio_channels, audio_bits);
    1067         }
    10681005    }
    10691006
    1070     audio_buflock.unlock();
     1007    waud = org_waud;
     1008    lastaudiolen = audiolen(false);
     1009
     1010    if (timecode < 0)
     1011        // mythmusic doesn't give timestamps..
     1012        timecode = (int)((samples_buffered * 100000.0) / effdsp);
     1013
     1014    samples_buffered += samples;
     1015
     1016    /* we want the time at the end -- but the file format stores
     1017       time at the start of the chunk. */
     1018    // even with timestretch, timecode is still calculated from original
     1019    // sample count
     1020    audbuf_timecode = timecode + (int)((samples * 100000.0) / effdsp);
     1021
    10711022}
    10721023
    10731024void AudioOutputBase::Status()
  • mythtv/libs/libmyth/audiooutputbase.h

    diff --git a/mythtv/libs/libmyth/audiooutputbase.h b/mythtv/libs/libmyth/audiooutputbase.h
    index 1f636e2..4bcaaa4 100644
    a b class AudioOutputBase : public AudioOutput, public QThread 
    4343
    4444    virtual void SetStretchFactor(float factor);
    4545    virtual float GetStretchFactor(void) const;
     46    virtual bool ToggleUpmix(void);
    4647
    4748    virtual void Reset(void);
    4849
    class AudioOutputBase : public AudioOutput, public QThread 
    8586    virtual void WriteAudio(unsigned char *aubuf, int size) = 0;
    8687    virtual int  GetSpaceOnSoundcard(void) const = 0;
    8788    virtual int  GetBufferedOnSoundcard(void) const = 0;
     89    virtual vector<int> GetSupportedRates(void) = 0;
     90
    8891    /// You need to call this from any implementation in the dtor.
    8992    void KillAudio(void);
    9093
    class AudioOutputBase : public AudioOutput, public QThread 
    122125
    123126    // Basic details about the audio stream
    124127    int audio_channels;
     128    int audio_codec;
    125129    int audio_bytes_per_sample;
    126130    int audio_bits;
    127131    int audio_samplerate;
    class AudioOutputBase : public AudioOutput, public QThread 
    132136    QString audio_passthru_device;
    133137
    134138    bool audio_passthru;
     139    bool audio_enc;
     140    bool audio_reenc;
    135141
    136142    float audio_stretchfactor;
    137     AVCodecContext *audio_codec;
    138143    AudioOutputSource source;
    139144
    140145    bool killaudio;
    class AudioOutputBase : public AudioOutput, public QThread 
    144149    bool buffer_output_data_for_use; //  used by AudioOutputNULL
    145150
    146151    int configured_audio_channels;
     152    int orig_config_channels;
     153    int src_quality;
    147154
    148155 private:
    149156    // resampler
    class AudioOutputBase : public AudioOutput, public QThread 
    156163    FreeSurround              *upmixer;
    157164
    158165    int source_audio_channels;
     166    int source_audio_samplerate;
    159167    int source_audio_bytes_per_sample;
    160168    bool needs_upmix;
    161169    int surround_mode;
     170    bool allow_ac3_passthru;
     171    float old_audio_stretchfactor;
    162172
    163173    bool blocking; // do AddSamples calls block?
    164174
  • mythtv/libs/libmyth/audiooutputca.h

    diff --git a/mythtv/libs/libmyth/audiooutputca.h b/mythtv/libs/libmyth/audiooutputca.h
    index 5afe3e0..14192bb 100644
    a b protected: 
    4949   
    5050    virtual bool StartOutputThread(void) { return true; }
    5151    virtual void StopOutputThread(void) {}
     52    virtual vector<int> GetSupportedRates(void)
     53        { vector<int> rates; return rates; }
    5254
    5355private:
    5456
  • mythtv/libs/libmyth/audiooutputdigitalencoder.cpp

    diff --git a/mythtv/libs/libmyth/audiooutputdigitalencoder.cpp b/mythtv/libs/libmyth/audiooutputdigitalencoder.cpp
    index a9688c9..f3bce4c 100644
    a b extern "C" { 
    3232AudioOutputDigitalEncoder::AudioOutputDigitalEncoder(void) :
    3333    audio_bytes_per_sample(0),
    3434    av_context(NULL),
    35     outbuf(NULL),
    36     outbuf_size(0),
    37     frame_buffer(NULL),
     35    outbuflen(0),
     36    inbuflen(0),
    3837    one_frame_bytes(0)
    3938{
    4039}
    void AudioOutputDigitalEncoder::Dispose() 
    5251        av_free(av_context);
    5352        av_context = NULL;
    5453    }
    55 
    56     if (outbuf)
    57     {
    58         delete [] outbuf;
    59         outbuf = NULL;
    60         outbuf_size = 0;
    61     }
    62 
    63     if (frame_buffer)
    64     {
    65         delete [] frame_buffer;
    66         frame_buffer = NULL;
    67         one_frame_bytes = 0;
    68     }
    6954}
    7055
    7156//CODEC_ID_AC3
    bool AudioOutputDigitalEncoder::Init( 
    8065            .arg(bitrate)
    8166            .arg(samplerate)
    8267            .arg(channels));
    83 
    84     //codec = avcodec_find_encoder(codec_id);
     68   
     69    // We need to do this when called from mythmusic
     70    avcodec_init();
     71    avcodec_register_all();
    8572    // always AC3 as there is no DTS encoder at the moment 2005/1/9
    8673    codec = avcodec_find_encoder(CODEC_ID_AC3);
    8774    if (!codec)
    bool AudioOutputDigitalEncoder::Init( 
    11097    audio_bytes_per_sample = bytes_per_frame;
    11198    one_frame_bytes = bytes_per_frame * av_context->frame_size;
    11299
    113     outbuf_size = 16384;    // ok for AC3 but DTS?
    114     outbuf = new char [outbuf_size];
    115100    VERBOSE(VB_AUDIO, QString("DigitalEncoder::Init fs=%1, bpf=%2 ofb=%3")
    116101            .arg(av_context->frame_size)
    117102            .arg(bytes_per_frame)
    typedef struct { 
    256241
    257242} AESHeader;
    258243
     244void reorder_6ch_ac3(void *buf, unsigned int len) {
     245    unsigned short *src = (unsigned short *)buf;
     246    unsigned short tmp;
     247    unsigned int samples = len >> 1;
     248
     249    for (uint i = 0; i < samples; i += 6) {
     250        tmp = src[i+4];
     251        src[i+4] = src[i+3];
     252        src[i+3] = src[i+2];
     253        src[i+2] = src[i+1];
     254        src[i+1] = tmp;
     255    }
     256}
     257
    259258static int encode_frame(
    260259        bool dts,
    261260        unsigned char *data,
    262         size_t &len)
     261        size_t enc_len)
    263262{
    264263    unsigned char *payload = data + 8;  // skip header, currently 52 or 54bits
    265     size_t         enc_len;
    266264    int            flags, sample_rate, bit_rate;
    267265
    268266    // we don't do any length/crc validation of the AC3 frame here; presumably
    static int encode_frame( 
    273271    // ignore, and if so, may as well just assume that it will ignore
    274272    // anything with a bad CRC...
    275273
    276     uint nr_samples = 0, block_len;
     274    uint nr_samples = 0, block_len = 0;
     275   
    277276    if (dts)
    278277    {
    279278        enc_len = dts_syncinfo(payload, &flags, &sample_rate, &bit_rate);
    static int encode_frame( 
    302301        }
    303302    }
    304303
    305     if (enc_len == 0 || enc_len > len)
    306     {
    307         int l = len;
    308         len = 0;
    309         return l;
    310     }
    311 
    312304    enc_len = std::min((uint)enc_len, block_len - 8);
    313305
    314306    //uint32_t x = *(uint32_t*)payload;
    static int encode_frame( 
    361353    data[6] = (enc_len << 3) & 0xFF;
    362354    data[7] = (enc_len >> 5) & 0xFF;
    363355    memset(payload + enc_len, 0, block_len - 8 - enc_len);
    364     len = block_len;
    365356
    366357    return enc_len;
    367358}
    368359
    369360// must have exactly 1 frames worth of data
    370 size_t AudioOutputDigitalEncoder::Encode(short *buff)
     361size_t AudioOutputDigitalEncoder::Encode(void *buf, int len)
    371362{
    372     int encsize = 0;
    373363    size_t outsize = 0;
    374364 
    375     // put data in the correct spot for encode frame
    376     outsize = avcodec_encode_audio(
    377         av_context, ((uchar*)outbuf) + 8, outbuf_size - 8, buff);
    378 
    379     size_t tmpsize = outsize;
    380 
    381     outsize = MAX_AC3_FRAME_SIZE;
    382     encsize = encode_frame(
    383         /*av_context->codec_id==CODEC_ID_DTS*/ false,
    384         (unsigned char*)outbuf, outsize);
     365    int fs = FrameSize();
     366    memcpy(inbuf+inbuflen, buf, len);
     367    inbuflen += len;
     368    int frames = inbuflen / fs;
    385369
    386     VERBOSE(VB_AUDIO+VB_TIMESTAMP,
    387             QString("DigitalEncoder::Encode len1=%1 len2=%2 finallen=%3")
    388                 .arg(tmpsize).arg(encsize).arg(outsize));
     370    while (frames--)
     371    {
     372        reorder_6ch_ac3(inbuf, fs);
     373       
     374        // put data in the correct spot for encode frame
     375        outsize = avcodec_encode_audio(
     376            av_context, ((uchar*)outbuf) + outbuflen + 8, OUTBUFSIZE - 8, (short int *)inbuf);
     377       
     378        encode_frame(
     379            /*av_context->codec_id==CODEC_ID_DTS*/ false,
     380            (unsigned char*)outbuf + outbuflen, outsize
     381        );
     382
     383        outbuflen += MAX_AC3_FRAME_SIZE;
     384        inbuflen -= fs;
     385        memmove(inbuf, inbuf+fs, inbuflen);
     386    }
     387 
     388    return outbuflen;
     389}
    389390
    390     return outsize;
     391void AudioOutputDigitalEncoder::GetFrames(void *ptr, int maxlen)
     392{
     393    int len = (maxlen < outbuflen ? maxlen : outbuflen);
     394    memcpy(ptr, outbuf, len);
     395    outbuflen -= len;
     396    memmove(outbuf, outbuf+len, outbuflen);
    391397}
  • mythtv/libs/libmyth/audiooutputdigitalencoder.h

    diff --git a/mythtv/libs/libmyth/audiooutputdigitalencoder.h b/mythtv/libs/libmyth/audiooutputdigitalencoder.h
    index 8a4689a..8d81298 100644
    a b extern "C" { 
    55#include "libavcodec/avcodec.h"
    66};
    77
     8#define INBUFSIZE 131072
     9#define OUTBUFSIZE 98304
     10
    811class AudioOutputDigitalEncoder
    912{
    1013  public:
    class AudioOutputDigitalEncoder 
    1316
    1417    bool   Init(CodecID codec_id, int bitrate, int samplerate, int channels);
    1518    void   Dispose(void);
    16     size_t Encode(short * buff);
    17 
    18     inline char *GetFrameBuffer(void);
     19    size_t Encode(void *buf, int len);
     20    void   GetFrames(void *ptr, int maxlen);
    1921    size_t FrameSize(void)  const { return one_frame_bytes; }
    20     char  *GetOutBuff(void) const { return outbuf;          }
     22    int    Buffered(void) const { return inbuflen; }
    2123
    2224  public:
    2325    size_t audio_bytes_per_sample;
    2426
    2527  private:
    2628    AVCodecContext *av_context;
    27     char           *outbuf;
    28     int             outbuf_size;
    29     char           *frame_buffer;
     29    char            outbuf[OUTBUFSIZE];
     30    char            inbuf[INBUFSIZE];
     31    int             outbuflen;
     32    int             inbuflen;
    3033    size_t          one_frame_bytes;
    3134};
    3235
    33 inline char *AudioOutputDigitalEncoder::GetFrameBuffer(void)
    34 {
    35     if (!frame_buffer && av_context)
    36         frame_buffer = new char [one_frame_bytes];
    37 
    38     return frame_buffer;
    39 }
    40 
    4136#endif
  • mythtv/libs/libmyth/audiooutputdx.h

    diff --git a/mythtv/libs/libmyth/audiooutputdx.h b/mythtv/libs/libmyth/audiooutputdx.h
    index e0d3e24..485adb1 100644
    a b public: 
    4545    // Volume control
    4646    virtual int GetVolumeChannel(int channel) const; // Returns 0-100
    4747    virtual void SetVolumeChannel(int channel, int volume); // range 0-100 for vol
     48    virtual vector<int> GetSupportedRates(void)
     49        { vector<int> rates; return rates; }
    4850
    4951 private:
    5052    HINSTANCE dsound_dll;      /* handle of the opened dsound dll */
  • mythtv/libs/libmyth/audiooutputjack.cpp

    diff --git a/mythtv/libs/libmyth/audiooutputjack.cpp b/mythtv/libs/libmyth/audiooutputjack.cpp
    index 7e0ad0d..f9a5848 100644
    a b AudioOutputJACK::AudioOutputJACK(const AudioSettings &settings) : 
    3030    Reconfigure(settings);
    3131}
    3232
     33vector<int> AudioOutputJACK::GetSupportedRates()
     34{
     35    const int srates[] = { 8000, 11025, 16000, 22050, 32000, 44100, 48000 };
     36    vector<int> rates(srates, srates + sizeof(srates) / sizeof(int) );
     37    unsigned long jack_port_flags = 0;
     38    unsigned int jack_port_name_count = 1;
     39    const char *jack_port_name = audio_main_device.ascii();
     40    int err = -1;
     41    audioid = -1;
     42    vector<int>::iterator it;
     43
     44    for (it = rates.begin(); it < rates.end(); it++)
     45    {
     46        err = JACK_OpenEx(&audioid, 16, (unsigned long *)it,
     47                          2, 2, &jack_port_name, jack_port_name_count,
     48                          jack_port_flags);
     49       
     50        if (err == 1)
     51        {
     52            Error(QString("Error connecting to jackd: %1. Is it running?")
     53                  .arg(audio_main_device));
     54            rates.clear();
     55            return rates;
     56        }
     57        else if (err == 2)
     58            rates.erase(it--);
     59
     60        JACK_Close(audioid);
     61        audioid = -1;
     62       
     63    }
     64 
     65    return rates;
     66}
     67
     68
    3369AudioOutputJACK::~AudioOutputJACK()
    3470{
    3571    // Close down all audio stuff
  • mythtv/libs/libmyth/audiooutputjack.h

    diff --git a/mythtv/libs/libmyth/audiooutputjack.h b/mythtv/libs/libmyth/audiooutputjack.h
    index f87538e..259c202 100644
    a b class AudioOutputJACK : public AudioOutputBase 
    2323    virtual void WriteAudio(unsigned char *aubuf, int size);
    2424    virtual int  GetSpaceOnSoundcard(void) const;
    2525    virtual int  GetBufferedOnSoundcard(void) const;
     26    virtual vector<int> GetSupportedRates(void);
    2627
    2728  private:
    2829
  • mythtv/libs/libmyth/audiooutputnull.h

    diff --git a/mythtv/libs/libmyth/audiooutputnull.h b/mythtv/libs/libmyth/audiooutputnull.h
    index 7eb247d..78a0f54 100644
    a b class AudioOutputNULL : public AudioOutputBase 
    4141    virtual void WriteAudio(unsigned char *aubuf, int size);
    4242    virtual int  GetSpaceOnSoundcard(void) const;
    4343    virtual int  GetBufferedOnSoundcard(void) const;
     44    virtual vector<int> GetSupportedRates(void)
     45        { vector<int> rates; return rates; }
    4446
    4547  private:
    4648    QMutex        pcm_output_buffer_mutex;
  • mythtv/libs/libmyth/audiooutputoss.cpp

    diff --git a/mythtv/libs/libmyth/audiooutputoss.cpp b/mythtv/libs/libmyth/audiooutputoss.cpp
    index 127bf6e..8d3b135 100644
    a b AudioOutputOSS::~AudioOutputOSS() 
    4242    KillAudio();
    4343}
    4444
     45vector<int> AudioOutputOSS::GetSupportedRates()
     46{
     47    const int srates[] = { 8000, 11025, 16000, 22050, 32000, 44100, 48000 };
     48    vector<int> rates(srates, srates + sizeof(srates) / sizeof(int) );
     49    audiofd = open(audio_main_device.toAscii(), O_WRONLY | O_NONBLOCK);
     50   
     51    if (audiofd < 0)
     52    {
     53        VERBOSE(VB_IMPORTANT, QString("Error opening audio device (%1), the"
     54                " error was: %2").arg(audio_main_device).arg(strerror(errno)));
     55        rates.clear();
     56        return rates;
     57    }
     58   
     59    vector<int>::iterator it;
     60
     61    for (it = rates.begin(); it < rates.end(); it++)
     62        if(ioctl(audiofd, SNDCTL_DSP_SPEED, &audio_samplerate) < 0)
     63            rates.erase(it--);
     64   
     65    close(audiofd);
     66    audiofd = -1;
     67   
     68    return rates;
     69}
     70
    4571bool AudioOutputOSS::OpenDevice()
    4672{
    4773    numbadioctls = 0;
  • mythtv/libs/libmyth/audiooutputoss.h

    diff --git a/mythtv/libs/libmyth/audiooutputoss.h b/mythtv/libs/libmyth/audiooutputoss.h
    index d5105a2..e218e31 100644
    a b class AudioOutputOSS : public AudioOutputBase 
    2323    virtual void WriteAudio(unsigned char *aubuf, int size);
    2424    virtual int  GetSpaceOnSoundcard(void) const;
    2525    virtual int  GetBufferedOnSoundcard(void) const;
     26    virtual vector<int> GetSupportedRates(void);
    2627
    2728  private:
    2829    void VolumeInit(void);
  • mythtv/libs/libmyth/audiooutputwin.h

    diff --git a/mythtv/libs/libmyth/audiooutputwin.h b/mythtv/libs/libmyth/audiooutputwin.h
    index 8ba37e4..5fd5945 100644
    a b class AudioOutputWin : public AudioOutputBase 
    2323    virtual void WriteAudio(unsigned char *aubuf, int size);
    2424    virtual int  GetSpaceOnSoundcard(void) const;
    2525    virtual int  GetBufferedOnSoundcard(void) const;
     26    virtual vector<int> GetSupportedRates(void)
     27        { vector<int> rates; return rates; }
    2628
    2729  protected:
    2830    AudioOutputWinPrivate *m_priv;
  • mythtv/libs/libmyth/audiosettings.cpp

    diff --git a/mythtv/libs/libmyth/audiosettings.cpp b/mythtv/libs/libmyth/audiosettings.cpp
    index 68e515b..1f4ef18 100644
    a b AudioSettings::AudioSettings() : 
    1212    passthru_device(QString::null),
    1313    bits(-1),
    1414    channels(-1),
     15    codec(0),
    1516    samplerate(-1),
    1617    set_initial_vol(false),
    1718    use_passthru(false),
    18     codec(NULL),
    1919    source(AUDIOOUTPUT_UNKNOWN)
    2020{
    2121}
    AudioSettings::AudioSettings(const AudioSettings &other) : 
    2525    passthru_device(other.passthru_device),
    2626    bits(other.bits),
    2727    channels(other.channels),
     28    codec(other.codec),
    2829    samplerate(other.samplerate),
    2930    set_initial_vol(other.set_initial_vol),
    3031    use_passthru(other.use_passthru),
    31     codec(other.codec),
    3232    source(other.source)
    3333{
    3434}
    AudioSettings::AudioSettings( 
    3838    const QString &audio_passthru_device,
    3939    int audio_bits,
    4040    int audio_channels,
     41    int audio_codec,
    4142    int audio_samplerate,
    4243    AudioOutputSource audio_source,
    4344    bool audio_set_initial_vol,
    44     bool audio_use_passthru,
    45     void *audio_codec) :
     45    bool audio_use_passthru) :
    4646    main_device(audio_main_device),
    4747    passthru_device(audio_passthru_device),
    4848    bits(audio_bits),
    4949    channels(audio_channels),
     50    codec(audio_codec),
    5051    samplerate(audio_samplerate),
    5152    set_initial_vol(audio_set_initial_vol),
    5253    use_passthru(audio_use_passthru),
    53     codec(audio_codec),
    5454    source(audio_source)
    5555{
    5656}
    AudioSettings::AudioSettings( 
    5858AudioSettings::AudioSettings(
    5959    int   audio_bits,
    6060    int   audio_channels,
     61    int   audio_codec,
    6162    int   audio_samplerate,
    62     bool  audio_use_passthru,
    63     void *audio_codec) :
     63    bool  audio_use_passthru) :
    6464    main_device(QString::null),
    6565    passthru_device(QString::null),
    6666    bits(audio_bits),
    6767    channels(audio_channels),
     68    codec(audio_codec),
    6869    samplerate(audio_samplerate),
    6970    set_initial_vol(false),
    7071    use_passthru(audio_use_passthru),
    71     codec(audio_codec),
    7272    source(AUDIOOUTPUT_UNKNOWN)
    7373{
    7474}
  • mythtv/libs/libmyth/audiosettings.h

    diff --git a/mythtv/libs/libmyth/audiosettings.h b/mythtv/libs/libmyth/audiosettings.h
    index f9349f4..ba38f51 100644
    a b class MPUBLIC AudioSettings 
    2929        const QString    &audio_passthru_device,
    3030        int               audio_bits,
    3131        int               audio_channels,
     32        int               audio_codec,
    3233        int               audio_samplerate,
    3334        AudioOutputSource audio_source,
    3435        bool              audio_set_initial_vol,
    35         bool              audio_use_passthru,
    36         void             *audio_codec = NULL);
     36        bool              audio_use_passthru);
    3737
    3838    AudioSettings(int   audio_bits,
    3939                  int   audio_channels,
     40                  int   audio_codec,
    4041                  int   audio_samplerate,
    41                   bool  audio_use_passthru,
    42                   void *audio_codec = NULL);
     42                  bool  audio_use_passthru);
    4343
    4444    void FixPassThrough(void);
    4545    void TrimDeviceType(void);
    class MPUBLIC AudioSettings 
    5454  public:
    5555    int     bits;
    5656    int     channels;
     57    int     codec;
    5758    int     samplerate;
    5859    bool    set_initial_vol;
    5960    bool    use_passthru;
    60     void   *codec;
    6161    AudioOutputSource source;
    6262};
    6363
  • mythtv/libs/libmythfreesurround/el_processor.cpp

    diff --git a/mythtv/libs/libmythfreesurround/el_processor.cpp b/mythtv/libs/libmythfreesurround/el_processor.cpp
    index 8f24737..1cf0dc8 100644
    a b typedef std::complex<float> cfloat; 
    4040
    4141const float PI = 3.141592654;
    4242const float epsilon = 0.000001;
    43 //const float center_level = 0.5*sqrt(0.5);   // gain of the center channel
    44 //const float center_level = sqrt(0.5);   // gain of the center channel
    45 const float center_level = 1.0;   // gain of the center channel
    46 //const float center_level = 0.5;   // gain of the center channel
    47 
    48 // should be .6-.7
    49 // but with centerlevel 2x what its supposed to be, we halve 0.68
    50 // to keep center from clipping
    51 //const float window_gain = 0.34;     
    52 //const float window_gain = 0.68;     
    53 const float window_gain = 0.95;     // to prive a bit of margin
     43const float center_level = 0.5*sqrt(0.5);
    5444
    5545// private implementation of the surround decoder
    5646class decoder_impl {
    public: 
    9888            outbuf[c].resize(N);
    9989            filter[c].resize(N);
    10090        }
    101         // DC component of filters is always 0
    102         for (unsigned c=0;c<5;c++)
    103         {
    104             filter[c][0] = 0.0;
    105             filter[c][1] = 0.0;
    106             filter[c][halfN] = 0.0;
    107         }
    10891        sample_rate(48000);
    10992        // generate the window function (square root of hann, b/c it is applied before and after the transform)
    11093        wnd.resize(N);
    111         // dft normalization included in the window for zero cost scaling
    112         // also add a gain factor of *2 due to processing gain in algo (see center_level)
    113         surround_gain(1.0);
     94        for (unsigned k=0;k<N;k++)
     95            wnd[k] = sqrt(0.5*(1-cos(2*PI*k/N))/N);
    11496        current_buf = 0;
    11597        // set the default coefficients
    11698        surround_coefficients(0.8165,0.5774);
    public: 
    192174    // set lfe filter params
    193175    void sample_rate(unsigned int srate) {
    194176        // lfe filter is just straight through band limited
    195         unsigned int cutoff = (250*N)/srate;
     177        unsigned int cutoff = (30*N)/srate;
    196178        for (unsigned f=0;f<=halfN;f++) {           
    197             if ((f>=2) && (f<cutoff))
    198                 filter[5][f] = 1.0;
     179            if (f<cutoff)
     180                filter[5][f] = 0.5*sqrt(0.5);
    199181            else
    200182                filter[5][f] = 0.0;
    201183        }
    public: 
    214196        E = (o+v)*n; F = (o+u)*n; G = (o-v)*n;  H = (o-u)*n;
    215197    }
    216198
    217     void surround_gain(float gain) {
    218         master_gain = gain * window_gain * 0.5 * 0.25;
    219         for (unsigned k=0;k<N;k++)
    220             wnd[k] = sqrt(master_gain*(1-cos(2*PI*k/N))/N);
    221     }
    222 
    223199    // set the phase shifting mode
    224200    void phase_mode(unsigned mode) {
    225201        const float modes[4][2] = {{0,0},{0,PI},{PI,0},{-PI/2,PI/2}};
    private: 
    290266
    291267        // 2. compare amplitude and phase of each DFT bin and produce the X/Y coordinates in the sound field
    292268        //    but dont do DC or N/2 component
    293         for (unsigned f=2;f<halfN;f++) {           
     269        for (unsigned f=0;f<halfN;f++) {           
    294270            // get left/right amplitudes/phases
    295271            float ampL = amplitude(dftL[f]), ampR = amplitude(dftR[f]);
    296272            float phaseL = phase(dftL[f]), phaseR = phase(dftR[f]);
    private: 
    305281            phaseDiff = abs(phaseDiff);
    306282
    307283            if (linear_steering) {
    308 /*              cfloat w = polar(sqrt(ampL*ampL+ampR*ampR), (phaseL+phaseR)/2);
    309                 cfloat lt = cfloat(dftL[f][0],dftL[f][1])/w, rt = cfloat(dftR[f][0],dftR[f][1])/w;              */
    310 //              xfs[f] = -(C*(rt-H) - B*E + F*A + G*(D-lt)) / (G*A - C*E).real();
    311 //              yfs[f] = (rt - (xfs[f]*E+H))/(F+xfs[f]*G);
    312 
    313                 /*
    314                 Problem:
    315                 This assumes that the values are interpolated linearly between the cardinal points.
    316                 But this way we have no chance of knowing the average volume...
    317                 - Can we solve that computing everything under the assumption of normalized volume?
    318                   No. Seemingly not.
    319                 - Maybe we should add w explitcitly into the equation and see if we can solve it...
    320                 */
    321 
    322 
    323                 //cfloat lt(0.5,0),rt(0.5,0);
    324                 //cfloat x(0,0), y(1,0);
    325                 /*cfloat p = (C*(rt-H) - B*E + F*A + G*(D-lt)) / (G*A - C*E);
    326                 cfloat q = B*(rt+H) + F*(D-lt) / (G*A - C*E);
    327                 cfloat s = sqrt(p*p/4.0f - q);
    328                 cfloat x = -p;
    329                 cfloat x1 = -p/2.0f + s;
    330                 cfloat x2 = -p/2.0f - s;
    331                 float x = 0;
    332                 if (x1.real() >= -1 && x1.real() <= 1)
    333                     x = x1.real();
    334                 else if (x2.real() >= -1 && x2.real() <= 1)
    335                     x = x2.real();*/
    336 
    337                 //cfloat yp = (rt - (x*E+H))/(F+x*G);
    338                 //cfloat xp = (lt - (y*B+D))/(A+y*C);
    339 
    340                 /*xfs[f] = x;
    341                 yfs[f] = y.real();*/
    342 
    343284                // --- this is the fancy new linear mode ---
    344285
    345286                // get sound field x/y position
    private: 
    597538    float surround_high,surround_low;  // high and low surround mixing coefficient (e.g. 0.8165/0.5774)
    598539    float surround_balance;            // the xfs balance that follows from the coeffs
    599540    float surround_level;              // gain for the surround channels (follows from the coeffs
    600     float master_gain;                 // gain for all channels
    601541    float phase_offsetL, phase_offsetR;// phase shifts to be applied to the rear channels
    602542    float front_separation;            // front stereo separation
    603543    float rear_separation;             // rear stereo separation
    void fsurround_decoder::flush() { impl->flush(); } 
    625565
    626566void fsurround_decoder::surround_coefficients(float a, float b) { impl->surround_coefficients(a,b); }
    627567
    628 void fsurround_decoder::gain(float gain) { impl->surround_gain(gain); }
    629 
    630568void fsurround_decoder::phase_mode(unsigned mode) { impl->phase_mode(mode); }
    631569
    632570void fsurround_decoder::steering_mode(bool mode) { impl->steering_mode(mode); }
  • mythtv/libs/libmythfreesurround/el_processor.h

    diff --git a/mythtv/libs/libmythfreesurround/el_processor.h b/mythtv/libs/libmythfreesurround/el_processor.h
    index 021786a..26452f6 100644
    a b public: 
    4747        //  a is the coefficient of left rear in left total, b is the coefficient of left rear in right total; the same is true for right.
    4848        void surround_coefficients(float a, float b);
    4949
    50         // override for master surround gain
    51         void gain(float gain);
    52 
    5350        // set the phase shifting mode for decoding
    5451        // 0 = (+0°,+0°)   - music mode
    5552        // 1 = (+0°,+180°) - PowerDVD compatibility
  • mythtv/libs/libmythfreesurround/freesurround.cpp

    diff --git a/mythtv/libs/libmythfreesurround/freesurround.cpp b/mythtv/libs/libmythfreesurround/freesurround.cpp
    index fc7ed8f..bf93d28 100644
    a b using namespace std; 
    6363const unsigned default_block_size = 8192;
    6464// there will be a slider for this in the future
    6565//const float master_gain = 1.0;
    66 //#define MASTER_GAIN * master_gain
     66//#define MASTER_GAIN * master_gain 
    6767#define MASTER_GAIN
    68 //const float master_gain = 1.0/(1<<15);
    69 //const float inv_master_gain = (1<<15);
     68//const float inv_master_gain = 1.0;
    7069//#define INV_MASTER_GAIN * inv_master_gain
    7170#define INV_MASTER_GAIN
    7271
    FreeSurround::FreeSurround(uint srate, bool moviemode, SurroundMode smode) : 
    192191    if (moviemode)
    193192    {
    194193        params.phasemode = 1;
    195         params.center_width = 0;
    196         params.gain = 1.0;
     194        params.center_width = 25;
     195        params.dimension = 0.5;
    197196    }
    198197    else
    199198    {
    200         params.center_width = 70;
    201         // for 50, gain should be about 1.9, c/lr about 2.7
    202         // for 70, gain should be about 3.1, c/lr about 1.5
    203         params.gain = 3.1;
     199        params.center_width = 65;
     200        params.dimension = 0.3;
    204201    }
    205202    switch (surround_mode)
    206203    {
    void FreeSurround::SetParams() 
    236233        decoder->phase_mode(params.phasemode);
    237234        decoder->surround_coefficients(params.coeff_a, params.coeff_b);                         
    238235        decoder->separation(params.front_sep/100.0,params.rear_sep/100.0);
    239         decoder->gain(params.gain);
    240236    }
    241237}
    242238
    FreeSurround::fsurround_params::fsurround_params( 
    250246    phasemode(0),
    251247    steering(1),
    252248    front_sep(100),
    253     rear_sep(100),
    254     gain(1.0)
     249    rear_sep(100)
    255250{
    256251}
    257252
    void FreeSurround::process_block() 
    655650    {
    656651        if (decoder)
    657652        {
    658             // actually these params need only be set when they change... but it doesn't hurt
    659 #if 0
    660             decoder->steering_mode(params.steering);
    661             decoder->phase_mode(params.phasemode);
    662             decoder->surround_coefficients(params.coeff_a, params.coeff_b);                             
    663             decoder->separation(params.front_sep/100.0,params.rear_sep/100.0);
    664 #endif
    665             // decode the bufs->block
    666             //decoder->decode(input,output,params.center_width/100.0,params.dimension/100.0);
    667             //decoder->decode(output,params.center_width/100.0,params.dimension/100.0);
    668653            decoder->decode(params.center_width/100.0,params.dimension/100.0);
    669654        }
    670655    }
  • mythtv/libs/libmythsamplerate/samplerate.c

    diff --git a/mythtv/libs/libmythsamplerate/samplerate.c b/mythtv/libs/libmythsamplerate/samplerate.c
    index adaccf0..a53a942 100644
    a b src_float_to_short_array (const float *in, short *out, int len) 
    452452        {       len -- ;
    453453
    454454                scaled_value = in [len] * (8.0 * 0x10000000) ;
    455                 if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFFFFFF))
     455                if (scaled_value >= (1.0 * 0x7FFFFFFF))
    456456                {       out [len] = 32767 ;
    457457                        continue ;
    458458                        } ;
    459                 if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x10000000))
     459                if (scaled_value <= (-8.0 * 0x10000000))
    460460                {       out [len] = -32768 ;
    461461                        continue ;
    462462                        } ;
  • mythtv/libs/libmythtv/NuppelVideoPlayer.cpp

    diff --git a/mythtv/libs/libmythtv/NuppelVideoPlayer.cpp b/mythtv/libs/libmythtv/NuppelVideoPlayer.cpp
    index 7ebedfe..d45c010 100644
    a b NuppelVideoPlayer::NuppelVideoPlayer() 
    218218      audioOutput(NULL),
    219219      audio_main_device(QString::null),
    220220      audio_passthru_device(QString::null),
    221       audio_channels(2),            audio_bits(-1),
    222       audio_samplerate(44100),      audio_stretchfactor(1.0f),
    223       audio_codec(NULL),
     221      audio_channels(2),            audio_codec(0),
     222      audio_bits(-1),               audio_samplerate(44100),
     223      audio_stretchfactor(1.0f),
    224224      // Picture-in-Picture stuff
    225225      pip_active(false),            pip_visible(true),
    226226      // Preview window support
    QString NuppelVideoPlayer::ReinitAudio(void) 
    899899        bool setVolume = gContext->GetNumSetting("MythControlsVolume", 1);
    900900        audioOutput = AudioOutput::OpenAudio(audio_main_device,
    901901                                             audio_passthru_device,
    902                                              audio_bits, audio_channels,
    903                                              audio_samplerate,
     902                                             audio_bits, audio_channels, 
     903                                             audio_codec, audio_samplerate,
    904904                                             AUDIOOUTPUT_VIDEO,
    905905                                             setVolume, audio_passthru);
    906906        if (!audioOutput)
    QString NuppelVideoPlayer::ReinitAudio(void) 
    928928
    929929    if (audioOutput)
    930930    {
    931         const AudioSettings settings(
    932             audio_bits, audio_channels, audio_samplerate,
    933             audio_passthru, audio_codec);
     931        const AudioSettings settings(audio_bits, audio_channels, audio_codec,
     932                                     audio_samplerate, audio_passthru);
    934933        audioOutput->Reconfigure(settings);
     934        if (audio_passthru)
     935            audio_channels = 2;
    935936        errMsg = audioOutput->GetError();
    936937        if (!errMsg.isEmpty())
    937938            audioOutput->SetStretchFactor(audio_stretchfactor);
    bool NuppelVideoPlayer::StartPlaying(bool openfile) 
    38623863    return !IsErrored();
    38633864}
    38643865
    3865 void NuppelVideoPlayer::SetAudioParams(int bps, int channels,
     3866void NuppelVideoPlayer::SetAudioParams(int bps, int channels, int codec,
    38663867                                       int samplerate, bool passthru)
    38673868{
    38683869    audio_bits = bps;
    38693870    audio_channels = channels;
     3871    audio_codec = codec;
    38703872    audio_samplerate = samplerate;
    38713873    audio_passthru = passthru;
    38723874}
    38733875
    3874 void NuppelVideoPlayer::SetAudioCodec(void *ac)
    3875 {
    3876     audio_codec = ac;
    3877 }
    3878 
    38793876void NuppelVideoPlayer::SetEffDsp(int dsprate)
    38803877{
    38813878    if (audioOutput)
    void NuppelVideoPlayer::ToggleAdjustFill(AdjustFillMode adjustfillMode) 
    52945291    }
    52955292}
    52965293
     5294bool NuppelVideoPlayer::ToggleUpmix()
     5295{
     5296    if (audioOutput)
     5297        return audioOutput->ToggleUpmix();
     5298    return false;
     5299}
     5300
    52975301void NuppelVideoPlayer::Zoom(ZoomDirection direction)
    52985302{
    52995303    if (videoOutput)
  • mythtv/libs/libmythtv/NuppelVideoPlayer.h

    diff --git a/mythtv/libs/libmythtv/NuppelVideoPlayer.h b/mythtv/libs/libmythtv/NuppelVideoPlayer.h
    index 2ceb683..06743d4 100644
    a b class MPUBLIC NuppelVideoPlayer : public CC608Reader, public CC708Reader 
    125125    void SetAudioStretchFactor(float factor)  { audio_stretchfactor = factor; }
    126126    void SetAudioOutput(AudioOutput *ao)      { audioOutput = ao; }
    127127    void SetAudioInfo(const QString &main, const QString &passthru, uint rate);
    128     void SetAudioParams(int bits, int channels, int samplerate, bool passthru);
     128    void SetAudioParams(int bits, int channels, int codec, int samplerate,
     129                        bool passthru);
    129130    void SetEffDsp(int dsprate);
    130131    uint AdjustVolume(int change);
    131132    bool SetMuted(bool mute);
    class MPUBLIC NuppelVideoPlayer : public CC608Reader, public CC708Reader 
    179180    // Toggle Sets
    180181    void ToggleAspectOverride(AspectOverrideMode aspectMode = kAspect_Toggle);
    181182    void ToggleAdjustFill(AdjustFillMode adjustfillMode = kAdjustFill_Toggle);
     183    bool ToggleUpmix(void);
    182184
    183185    // Gets
    184186    QSize   GetVideoBufferSize(void) const    { return video_dim; }
    class MPUBLIC NuppelVideoPlayer : public CC608Reader, public CC708Reader 
    711713    QString  audio_main_device;
    712714    QString  audio_passthru_device;
    713715    int      audio_channels;
     716    int      audio_codec;
    714717    int      audio_bits;
    715718    int      audio_samplerate;
    716719    float    audio_stretchfactor;
    717     void    *audio_codec;
    718720    bool     audio_passthru;
    719721
    720722    // Picture-in-Picture
  • mythtv/libs/libmythtv/avformatdecoder.cpp

    diff --git a/mythtv/libs/libmythtv/avformatdecoder.cpp b/mythtv/libs/libmythtv/avformatdecoder.cpp
    index bbc68e3..4530bc4 100644
    a b AvFormatDecoder::AvFormatDecoder(NuppelVideoPlayer *parent, 
    444444      audioSamples(NULL),
    445445      allow_ac3_passthru(false),    allow_dts_passthru(false),
    446446      disable_passthru(false),      max_channels(2),
    447       dummy_frame(NULL),
     447      last_ac3_channels(0),         dummy_frame(NULL),
    448448      // DVD
    449449      lastdvdtitle(-1),
    450450      decodeStillFrame(false),
    int AvFormatDecoder::ScanStreams(bool novideo) 
    20192019    // waiting on audio.
    20202020    if (GetNVP()->HasAudioIn() && tracks[kTrackTypeAudio].empty())
    20212021    {
    2022         GetNVP()->SetAudioParams(-1, -1, -1, false /* AC3/DTS pass-through */);
     2022        GetNVP()->SetAudioParams(-1, -1, CODEC_ID_NONE, -1, false /* AC3/DTS pass-through */);
    20232023        GetNVP()->ReinitAudio();
    20242024        if (ringBuffer && ringBuffer->isDVD())
    20252025            audioIn = AudioInfo();
    int AvFormatDecoder::AutoSelectAudioTrack(void) 
    30543054    {
    30553055        int idx = atracks[i].av_stream_index;
    30563056        AVCodecContext *codec_ctx = ic->streams[idx]->codec;
    3057         bool do_ac3_passthru = (allow_ac3_passthru && !transcoding &&
    3058                                 !disable_passthru &&
    3059                                 (codec_ctx->codec_id == CODEC_ID_AC3));
    3060         bool do_dts_passthru = (allow_dts_passthru && !transcoding &&
    3061                                 !disable_passthru &&
    3062                                 (codec_ctx->codec_id == CODEC_ID_DTS));
    30633057        AudioInfo item(codec_ctx->codec_id,
    30643058                       codec_ctx->sample_rate, codec_ctx->channels,
    3065                        do_ac3_passthru || do_dts_passthru);
     3059                       DoPassThrough(codec_ctx));
    30663060        VERBOSE(VB_AUDIO, LOC + " * " + item.toString());
    30673061    }
    30683062#endif
    static void extract_mono_channel(uint channel, AudioInfo *audioInfo, 
    31963190bool AvFormatDecoder::GetFrame(int onlyvideo)
    31973191{
    31983192    AVPacket *pkt = NULL;
     3193    AC3HeaderInfo hdr;
    31993194    int len;
    32003195    unsigned char *ptr;
    32013196    int data_size = 0;
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    33923387        pts = 0;
    33933388
    33943389        AVStream *curstream = ic->streams[pkt->stream_index];
     3390        AVCodecContext *ctx = curstream->codec;
    33953391
    33963392        if (pkt->dts != (int64_t)AV_NOPTS_VALUE)
    33973393            pts = (long long)(av_q2d(curstream->time_base) * pkt->dts * 1000);
    33983394
    3399         if (ringBuffer->isDVD() &&
    3400             curstream->codec->codec_type == CODEC_TYPE_VIDEO)
     3395        if (ringBuffer->isDVD() && 
     3396            ctx->codec_type == CODEC_TYPE_VIDEO)
    34013397        {
    34023398            MpegPreProcessPkt(curstream, pkt);
    34033399
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    34193415
    34203416            if (!d->HasMPEG2Dec())
    34213417            {
    3422                 int current_width = curstream->codec->width;
     3418                int current_width = ctx->width;
    34233419                int video_width = GetNVP()->GetVideoSize().width();
    34243420                if (dvd_xvmc_enabled && GetNVP() && GetNVP()->getVideoOutput())
    34253421                {
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    34603456        }
    34613457
    34623458        if (storevideoframes &&
    3463             curstream->codec->codec_type == CODEC_TYPE_VIDEO)
     3459            ctx->codec_type == CODEC_TYPE_VIDEO)
    34643460        {
    34653461            av_dup_packet(pkt);
    34663462            storedPackets.append(pkt);
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    34683464            continue;
    34693465        }
    34703466
    3471         if (len > 0 && curstream->codec->codec_type == CODEC_TYPE_VIDEO &&
     3467        if (len > 0 && ctx->codec_type == CODEC_TYPE_VIDEO &&
    34723468            pkt->stream_index == selectedVideoIndex)
    34733469        {
    3474             AVCodecContext *context = curstream->codec;
    34753470
    3476             if (context->codec_id == CODEC_ID_MPEG1VIDEO ||
    3477                 context->codec_id == CODEC_ID_MPEG2VIDEO ||
    3478                 context->codec_id == CODEC_ID_MPEG2VIDEO_XVMC ||
    3479                 context->codec_id == CODEC_ID_MPEG2VIDEO_XVMC_VLD)
     3471            if (ctx->codec_id == CODEC_ID_MPEG1VIDEO ||
     3472                ctx->codec_id == CODEC_ID_MPEG2VIDEO ||
     3473                ctx->codec_id == CODEC_ID_MPEG2VIDEO_XVMC ||
     3474                ctx->codec_id == CODEC_ID_MPEG2VIDEO_XVMC_VLD)
    34803475            {
    34813476                if (!ringBuffer->isDVD())
    34823477                    MpegPreProcessPkt(curstream, pkt);
    34833478            }
    3484             else if (context->codec_id == CODEC_ID_H264)
     3479            else if (ctx->codec_id == CODEC_ID_H264)
    34853480            {
    34863481                H264PreProcessPkt(curstream, pkt);
    34873482            }
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    35263521        }
    35273522
    35283523        if (len > 0 &&
    3529             curstream->codec->codec_type == CODEC_TYPE_DATA &&
    3530             curstream->codec->codec_id   == CODEC_ID_MPEG2VBI)
     3524            ctx->codec_type == CODEC_TYPE_DATA &&
     3525            ctx->codec_id   == CODEC_ID_MPEG2VBI)
    35313526        {
    35323527            ProcessVBIDataPacket(curstream, pkt);
    35333528
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    35363531        }
    35373532
    35383533        if (len > 0 &&
    3539             curstream->codec->codec_type == CODEC_TYPE_DATA &&
    3540             curstream->codec->codec_id   == CODEC_ID_DVB_VBI)
     3534            ctx->codec_type == CODEC_TYPE_DATA &&
     3535            ctx->codec_id   == CODEC_ID_DVB_VBI)
    35413536        {
    35423537            ProcessDVBDataPacket(curstream, pkt);
    35433538
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    35473542
    35483543#ifdef USING_MHEG
    35493544        if (len > 0 &&
    3550             curstream->codec->codec_type == CODEC_TYPE_DATA &&
    3551             curstream->codec->codec_id   == CODEC_ID_DSMCC_B)
     3545            ctx->codec_type == CODEC_TYPE_DATA &&
     3546            ctx->codec_id   == CODEC_ID_DSMCC_B)
    35523547        {
    35533548            ProcessDSMCCPacket(curstream, pkt);
    35543549
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    35693564#endif // USING_MHEG
    35703565
    35713566        // we don't care about other data streams
    3572         if (curstream->codec->codec_type == CODEC_TYPE_DATA)
     3567        if (ctx->codec_type == CODEC_TYPE_DATA)
    35733568        {
    35743569            av_free_packet(pkt);
    35753570            continue;
    35763571        }
    35773572
    3578         if (!curstream->codec->codec)
     3573        if (!ctx->codec)
    35793574        {
    35803575            VERBOSE(VB_PLAYBACK, LOC +
    35813576                    QString("No codec for stream index %1, type(%2) id(%3:%4)")
    35823577                    .arg(pkt->stream_index)
    3583                     .arg(codec_type_string(curstream->codec->codec_type))
    3584                     .arg(codec_id_string(curstream->codec->codec_id))
    3585                     .arg(curstream->codec->codec_id));
     3578                    .arg(codec_type_string(ctx->codec_type))
     3579                    .arg(codec_id_string(ctx->codec_id))
     3580                    .arg(ctx->codec_id));
    35863581            av_free_packet(pkt);
    35873582            continue;
    35883583        }
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    35913586        have_err = false;
    35923587
    35933588        avcodeclock.lock();
    3594         int ctype  = curstream->codec->codec_type;
     3589        int ctype  = ctx->codec_type;
    35953590        int audIdx = selectedTrack[kTrackTypeAudio].av_stream_index;
    35963591        int audSubIdx = selectedTrack[kTrackTypeAudio].av_substream_index;
    35973592        int subIdx = selectedTrack[kTrackTypeSubtitle].av_stream_index;
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    36163611
    36173612                    // detect switches between stereo and dual languages
    36183613                    bool wasDual = audSubIdx != -1;
    3619                     bool isDual = curstream->codec->avcodec_dual_language;
     3614                    bool isDual = ctx->avcodec_dual_language;
    36203615                    if ((wasDual && !isDual) || (!wasDual &&  isDual))
    36213616                    {
    36223617                        SetupAudioStreamSubIndexes(audIdx);
    36233618                        reselectAudioTrack = true;
    36243619                    }
    36253620
    3626                     bool do_ac3_passthru =
    3627                         (allow_ac3_passthru && !transcoding &&
    3628                          (curstream->codec->codec_id == CODEC_ID_AC3));
    3629                     bool do_dts_passthru =
    3630                         (allow_dts_passthru && !transcoding &&
    3631                          (curstream->codec->codec_id == CODEC_ID_DTS));
    3632                     bool using_passthru = do_ac3_passthru || do_dts_passthru;
    3633 
    36343621                    // detect channels on streams that need
    36353622                    // to be decoded before we can know this
    36363623                    bool already_decoded = false;
    3637                     if (!curstream->codec->channels)
     3624                    if (!ctx->channels)
    36383625                    {
    36393626                        QMutexLocker locker(&avcodeclock);
    36403627                        VERBOSE(VB_IMPORTANT, LOC +
    36413628                                QString("Setting channels to %1")
    36423629                                .arg(audioOut.channels));
    36433630
    3644                         if (using_passthru)
     3631                        if (DoPassThrough(ctx))
    36453632                        {
    36463633                            // for passthru let it select the max number
    36473634                            // of channels
    3648                             curstream->codec->channels = 0;
    3649                             curstream->codec->request_channels = 0;
     3635                            ctx->channels = 0;
     3636                            ctx->request_channels = 0;
    36503637                        }
    36513638                        else
    36523639                        {
    3653                             curstream->codec->channels = audioOut.channels;
    3654                             curstream->codec->request_channels =
     3640                            ctx->channels = audioOut.channels;
     3641                            ctx->request_channels =
    36553642                                audioOut.channels;
    36563643                        }
     3644                       
    36573645                        data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
    3658                         ret = avcodec_decode_audio2(curstream->codec,
    3659                                                     audioSamples, &data_size,
    3660                                                     ptr, len);
     3646                        ret = avcodec_decode_audio2(ctx, audioSamples,
     3647                                                   &data_size, ptr, len);
    36613648                        already_decoded = true;
    36623649
    3663                         reselectAudioTrack |= curstream->codec->channels;
     3650                        reselectAudioTrack |= ctx->channels;
     3651                    }
     3652
     3653                    if (ctx->codec_id == CODEC_ID_AC3)
     3654                    {
     3655                        GetBitContext gbc;
     3656                        init_get_bits(&gbc, ptr, len * 8);
     3657                        if (!ff_ac3_parse_header(&gbc, &hdr))
     3658                        {
     3659                            if (hdr.channels != last_ac3_channels)
     3660                            {
     3661                                last_ac3_channels = ctx->channels = hdr.channels;
     3662                                SetupAudioStream();
     3663                            }
     3664                        }
    36643665                    }
    36653666
    36663667                    if (reselectAudioTrack)
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    36763677                            .av_stream_index;
    36773678                        audSubIdx = selectedTrack[kTrackTypeAudio]
    36783679                            .av_substream_index;
     3680                        ctx = curstream->codec;
    36793681                    }
    36803682
    36813683                    if ((onlyvideo > 0) || (pkt->stream_index != audIdx))
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    37073709                    if (audioOut.do_passthru)
    37083710                    {
    37093711                        data_size = pkt->size;
    3710                         bool dts = CODEC_ID_DTS == curstream->codec->codec_id;
     3712                        bool dts = CODEC_ID_DTS == ctx->codec_id;
    37113713                        ret = encode_frame(dts, ptr, len,
    37123714                                           audioSamples, data_size);
    37133715                    }
    37143716                    else
    37153717                    {
    3716                         AVCodecContext *ctx = curstream->codec;
    3717 
    37183718                        if ((ctx->channels == 0) ||
    37193719                            (ctx->channels > audioOut.channels))
    37203720                        {
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    37233723
    37243724                        if (!already_decoded)
    37253725                        {
    3726                             curstream->codec->request_channels =
    3727                                 audioOut.channels;
    37283726                            data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
    3729                             ret = avcodec_decode_audio2(ctx, audioSamples,
     3727                            ctx->request_channels = audioOut.channels;
     3728                            ret = avcodec_decode_audio2(ctx, audioSamples,
    37303729                                                        &data_size, ptr, len);
    37313730                        }
    37323731
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    37423741                            audIdx = -1;
    37433742                            AutoSelectAudioTrack();
    37443743                            data_size = 0;
     3744                            ctx = curstream->codec;
    37453745                        }
    37463746                    }
    37473747                    avcodeclock.unlock();
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    37593759
    37603760                    // calc for next frame
    37613761                    lastapts += (long long)((double)(data_size * 1000) /
    3762                                 (curstream->codec->channels * 2) /
    3763                                 curstream->codec->sample_rate);
     3762                                (ctx->channels * 2) / ctx->sample_rate);
    37643763
    37653764                    VERBOSE(VB_PLAYBACK+VB_TIMESTAMP,
    37663765                            LOC + QString("audio timecode %1 %2 %3 %4")
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    38283827                        continue;
    38293828                    }
    38303829
    3831                     AVCodecContext *context = curstream->codec;
    38323830                    AVFrame mpa_pic;
    38333831                    bzero(&mpa_pic, sizeof(AVFrame));
    38343832
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    38433841                            // HACK
    38443842                            while (!gotpicture && count < 5)
    38453843                            {
    3846                                 ret = d->DecodeMPEG2Video(context, &mpa_pic,
     3844                                ret = d->DecodeMPEG2Video(ctx, &mpa_pic,
    38473845                                                  &gotpicture, ptr, len);
    38483846                                count++;
    38493847                            }
    38503848                        }
    38513849                        else
    38523850                        {
    3853                             ret = d->DecodeMPEG2Video(context, &mpa_pic,
     3851                            ret = d->DecodeMPEG2Video(ctx, &mpa_pic,
    38543852                                                &gotpicture, ptr, len);
    38553853                        }
    38563854                    }
    38573855                    else
    38583856                    {
    3859                         ret = avcodec_decode_video(context, &mpa_pic,
     3857                        ret = avcodec_decode_video(ctx, &mpa_pic,
    38603858                                                   &gotpicture, ptr, len);
    38613859                        // Reparse it to not drop the DVD still frame
    38623860                        if (decodeStillFrame)
    3863                             ret = avcodec_decode_video(context, &mpa_pic,
     3861                            ret = avcodec_decode_video(ctx, &mpa_pic,
    38643862                                                        &gotpicture, ptr, len);
    38653863                    }
    38663864                    avcodeclock.unlock();
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    39283926                        myth_sws_img_convert(
    39293927                            &tmppicture, PIX_FMT_YUV420P,
    39303928                                    (AVPicture *)&mpa_pic,
    3931                                     context->pix_fmt,
    3932                                     context->width,
    3933                                     context->height);
     3929                                    ctx->pix_fmt,
     3930                                    ctx->width,
     3931                                    ctx->height);
    39343932
    39353933                        if (xf)
    39363934                        {
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    39533951                        (temppts + 10000 > lastvpts || temppts < 0))
    39543952                    {
    39553953                        temppts = lastvpts;
    3956                         temppts += (long long)(1000 * av_q2d(context->time_base));
     3954                        temppts += (long long)(1000 * av_q2d(ctx->time_base));
    39573955                        // MPEG2 frames can be repeated, update pts accordingly
    39583956                        temppts += (long long)(mpa_pic.repeat_pict * 500
    3959                                       * av_q2d(curstream->codec->time_base));
     3957                                      * av_q2d(ctx->time_base));
    39603958                    }
    39613959
    39623960                    VERBOSE(VB_PLAYBACK+VB_TIMESTAMP, LOC +
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    39923990                    picframe->frameNumber = framesPlayed;
    39933991                    GetNVP()->ReleaseNextVideoFrame(picframe, temppts);
    39943992                    if (d->HasMPEG2Dec() && mpa_pic.data[3])
    3995                         context->release_buffer(context, &mpa_pic);
     3993                        ctx->release_buffer(ctx, &mpa_pic);
    39963994
    39973995                    decoded_video_frame = picframe;
    39983996                    gotvideo = 1;
    bool AvFormatDecoder::GetFrame(int onlyvideo) 
    40484046                }
    40494047                default:
    40504048                {
    4051                     AVCodecContext *enc = curstream->codec;
    40524049                    VERBOSE(VB_IMPORTANT, LOC_ERR +
    40534050                            QString("Decoding - id(%1) type(%2)")
    4054                             .arg(codec_id_string(enc->codec_id))
    4055                             .arg(codec_type_string(enc->codec_type)));
     4051                            .arg(codec_id_string(ctx->codec_id))
     4052                            .arg(codec_type_string(ctx->codec_type)));
    40564053                    have_err = true;
    40574054                    break;
    40584055                }
    void AvFormatDecoder::SetDisablePassThrough(bool disable) 
    42014198    }
    42024199}
    42034200
     4201bool AvFormatDecoder::DoPassThrough(const AVCodecContext *ctx)
     4202{
     4203    bool passthru = false;
     4204
     4205    if (ctx->codec_id == CODEC_ID_AC3)
     4206        passthru = allow_ac3_passthru &&
     4207                   ctx->channels >= (int)max_channels;
     4208    else if (ctx->codec_id == CODEC_ID_DTS)
     4209        passthru = allow_dts_passthru;
     4210   
     4211    passthru &= !transcoding && !disable_passthru;
     4212    // Don't know any cards that support spdif clocked at < 44100
     4213    // Some US cable transmissions have 2ch 32k AC-3 streams
     4214    passthru &= ctx->sample_rate >= 44100;
     4215
     4216    return passthru;
     4217}
     4218
    42044219/** \fn AvFormatDecoder::SetupAudioStream(void)
    42054220 *  \brief Reinitializes audio if it needs to be reinitialized.
    42064221 *
    bool AvFormatDecoder::SetupAudioStream(void) 
    42144229    AVStream *curstream = NULL;
    42154230    AVCodecContext *codec_ctx = NULL;
    42164231    AudioInfo old_in  = audioIn;
    4217     AudioInfo old_out = audioOut;
    42184232    bool using_passthru = false;
    42194233
    42204234    if ((currentTrack[kTrackTypeAudio] >= 0) &&
    bool AvFormatDecoder::SetupAudioStream(void) 
    42284242        codec_ctx = curstream->codec;
    42294243        if (codec_ctx)
    42304244        {
    4231             bool do_ac3_passthru = (allow_ac3_passthru && !transcoding &&
    4232                                     (codec_ctx->codec_id == CODEC_ID_AC3));
    4233             bool do_dts_passthru = (allow_dts_passthru && !transcoding &&
    4234                                     (codec_ctx->codec_id == CODEC_ID_DTS));
    4235             using_passthru = do_ac3_passthru || do_dts_passthru;
    4236             info = AudioInfo(codec_ctx->codec_id,
    4237                              codec_ctx->sample_rate, codec_ctx->channels,
    4238                              using_passthru && !disable_passthru);
     4245            using_passthru = DoPassThrough(codec_ctx);
     4246            info = AudioInfo(codec_ctx->codec_id, codec_ctx->sample_rate,
     4247                            codec_ctx->channels, using_passthru);
    42394248        }
    42404249    }
    42414250
    bool AvFormatDecoder::SetupAudioStream(void) 
    42524261            QString("audio track #%1").arg(currentTrack[kTrackTypeAudio]+1));
    42534262
    42544263    audioOut = audioIn = info;
    4255     AudioInfo tmpAudioOut = audioOut;
    42564264
    4257     // A passthru stream looks like a 48KHz 2ch (@ 16bit) to the sound card
    4258     if (using_passthru && !disable_passthru)
     4265    if (!using_passthru && audioOut.channels > (int)max_channels)
    42594266    {
    4260         tmpAudioOut.channels    = 2;
    4261         tmpAudioOut.sample_rate = 48000;
    4262         tmpAudioOut.sample_size = 4;
    4263     }
    4264 
    4265     if (audioOut.channels > (int) max_channels)
    4266     {
    4267         audioOut.channels    = (int) max_channels;
     4267        audioOut.channels = (int)max_channels;
    42684268        audioOut.sample_size = audioOut.channels * 2;
    4269         codec_ctx->channels  = audioOut.channels;
     4269        codec_ctx->channels = audioOut.channels;
    42704270    }
    42714271
    4272     if (!using_passthru)
    4273         tmpAudioOut = audioOut;
    4274 
    42754272    VERBOSE(VB_AUDIO, LOC + "Audio format changed " +
    4276             QString("%1%2\n\t\t\tfrom %3 ; %4\n\t\t\tto   %5 ; %6")
    4277             .arg((using_passthru) ? "digital passthrough " : "")
    4278             .arg((using_passthru) ? tmpAudioOut.toString() : QString(""))
    4279             .arg(old_in.toString()).arg(old_out.toString())
    4280             .arg(audioIn.toString()).arg(audioOut.toString()));
     4273            QString("\n\t\t\tfrom %1 to %2")
     4274            .arg(old_in.toString()).arg(audioOut.toString()));
    42814275
    4282     if (tmpAudioOut.sample_rate > 0)
    4283         GetNVP()->SetEffDsp(tmpAudioOut.sample_rate * 100);
     4276    if (audioOut.sample_rate > 0)
     4277        GetNVP()->SetEffDsp(audioOut.sample_rate * 100);
    42844278
    4285     GetNVP()->SetAudioParams(tmpAudioOut.bps(), tmpAudioOut.channels,
    4286                              tmpAudioOut.sample_rate, audioIn.do_passthru);
     4279    GetNVP()->SetAudioParams(audioOut.bps(), audioOut.channels,
     4280                             audioOut.codec_id, audioOut.sample_rate,
     4281                             audioOut.do_passthru);
    42874282
    4288     // allow the audio stuff to reencode
    4289     GetNVP()->SetAudioCodec((using_passthru) ? codec_ctx : NULL);
    42904283    GetNVP()->ReinitAudio();
    42914284
    42924285    return true;
  • mythtv/libs/libmythtv/avformatdecoder.h

    diff --git a/mythtv/libs/libmythtv/avformatdecoder.h b/mythtv/libs/libmythtv/avformatdecoder.h
    index 9ead273..ea1fb23 100644
    a b class AvFormatDecoder : public DecoderBase 
    198198
    199199    void SeekReset(long long, uint skipFrames, bool doFlush, bool discardFrames);
    200200
     201    bool DoPassThrough(const AVCodecContext *ctx);
    201202    bool SetupAudioStream(void);
    202203    void SetupAudioStreamSubIndexes(int streamIndex);
    203204    void RemoveAudioStreams();
    class AvFormatDecoder : public DecoderBase 
    270271    bool              allow_dts_passthru;
    271272    bool              disable_passthru;
    272273    uint              max_channels;
     274    uint              last_ac3_channels;
    273275
    274276    VideoFrame       *dummy_frame;
    275277
  • mythtv/libs/libmythtv/nuppeldecoder.cpp

    diff --git a/mythtv/libs/libmythtv/nuppeldecoder.cpp b/mythtv/libs/libmythtv/nuppeldecoder.cpp
    index 88d2fbb..010a458 100644
    a b int NuppelDecoder::OpenFile(RingBuffer *rbuffer, bool novideo, 
    495495#endif
    496496        GetNVP()->SetAudioParams(extradata.audio_bits_per_sample,
    497497                                 extradata.audio_channels,
     498                                 CODEC_ID_NONE,
    498499                                 extradata.audio_sample_rate,
    499500                                 false /* AC3/DTS pass through */);
    500501        GetNVP()->ReinitAudio();
  • mythtv/libs/libmythtv/tv_play.cpp

    diff --git a/mythtv/libs/libmythtv/tv_play.cpp b/mythtv/libs/libmythtv/tv_play.cpp
    index babe363..99e62a0 100644
    a b void TV::InitKeys(void) 
    491491    REG_KEY("TV Playback", "VOLUMEDOWN", "Volume down", "[,{,F10,Volume Down");
    492492    REG_KEY("TV Playback", "VOLUMEUP",   "Volume up",   "],},F11,Volume Up");
    493493    REG_KEY("TV Playback", "MUTE",       "Mute",        "|,\\,F9,Volume Mute");
     494    REG_KEY("TV Playback", "TOGGLEUPMIX", "Toggle upmixer", "Ctrl+U");
    494495    REG_KEY("TV Playback", "TOGGLEPIPMODE", "Toggle Picture-in-Picture view",
    495496            "V");
    496497    REG_KEY("TV Playback", "TOGGLEPBPMODE", "Toggle Picture-by-Picture view",
    void TV::InitKeys(void) 
    630631  Teletext     F2,F3,F4,F5,F6,F7,F8
    631632  ITV          F2,F3,F4,F5,F6,F7,F12
    632633
    633   Playback: Ctrl-B,Ctrl-G,Ctrl-Y
     634  Playback: Ctrl-B,Ctrl-G,Ctrl-Y,Ctrl-U
    634635*/
    635636}
    636637
    bool TV::ToggleHandleAction(PlayerContext *ctx, 
    43454346        DoTogglePictureAttribute(ctx, kAdjustingPicture_Playback);
    43464347    else if (has_action("TOGGLESTRETCH", actions))
    43474348        ToggleTimeStretch(ctx);
     4349    else if (has_action("TOGGLEUPMIX", actions))
     4350        ToggleUpmix(ctx);
    43484351    else if (has_action("TOGGLESLEEP", actions))
    43494352        ToggleSleepTimer(ctx);
    43504353    else if (has_action("TOGGLERECORD", actions) && islivetv)
    void TV::ChangeTimeStretch(PlayerContext *ctx, int dir, bool allowEdit) 
    80108013    SetSpeedChangeTimer(0, __LINE__);
    80118014}
    80128015
     8016void TV::ToggleUpmix(PlayerContext *ctx)
     8017{
     8018    if (!ctx->nvp || !ctx->nvp->HasAudioOut())
     8019        return;
     8020    QString text;
     8021    if (ctx->nvp->ToggleUpmix())
     8022        text = tr("Upmixer On");
     8023    else
     8024        text = tr("Upmixer Off");
     8025   
     8026    if (ctx->nvp->GetOSD() && !browsemode)
     8027        ctx->nvp->GetOSD()->SetSettingsText(text, 5);
     8028}
     8029   
    80138030// dir in 10ms jumps
    80148031void TV::ChangeAudioSync(PlayerContext *ctx, int dir, bool allowEdit)
    80158032{
    void TV::TreeMenuSelected(OSDListTreeItemSelectedEvent *e) 
    96429659        SetManualZoom(actx, true, tr("Zoom Mode ON"));
    96439660    else if (action == "TOGGLESTRETCH")
    96449661        ToggleTimeStretch(actx);
     9662    else if (action == "TOGGLEUPMIX")
     9663        ToggleUpmix(actx);
    96459664    else if (action.left(13) == "ADJUSTSTRETCH")
    96469665    {
    96479666        bool floatRead;
    void TV::FillOSDTreeMenu( 
    999510014
    999610015    if (category == "AUDIOSYNC")
    999710016        new OSDGenericTree(treeMenu, tr("Adjust Audio Sync"), "TOGGLEAUDIOSYNC");
     10017    else if (category == "TOGGLEUPMIX")
     10018        new OSDGenericTree(treeMenu, tr("Toggle Upmixer"), "TOGGLEUPMIX");
    999810019    else if (category == "TIMESTRETCH")
    999910020        FillMenuTimeStretch(ctx, treeMenu);
    1000010021    else if (category == "VIDEOSCAN")
  • mythtv/libs/libmythtv/tv_play.h

    diff --git a/mythtv/libs/libmythtv/tv_play.h b/mythtv/libs/libmythtv/tv_play.h
    index b361a7e..f9b93bf 100644
    a b class MPUBLIC TV : public QThread 
    419419        ARBSEEK_FORWARD,
    420420        ARBSEEK_END
    421421    };
     422   
    422423    void DoArbSeek(PlayerContext*, ArbSeekWhence whence);
    423424    void NormalSpeed(PlayerContext*);
    424425    void ChangeSpeed(PlayerContext*, int direction);
    class MPUBLIC TV : public QThread 
    427428    bool TimeStretchHandleAction(PlayerContext*,
    428429                                 const QStringList &actions);
    429430
     431    void ToggleUpmix(PlayerContext*);
    430432    void ChangeAudioSync(PlayerContext*, int dir, bool allowEdit = true);
    431433    bool AudioSyncHandleAction(PlayerContext*, const QStringList &actions);
    432434
  • mythtv/libs/libmythtv/tvosdmenuentry.cpp

    diff --git a/mythtv/libs/libmythtv/tvosdmenuentry.cpp b/mythtv/libs/libmythtv/tvosdmenuentry.cpp
    index 994dcb2..ef714ea 100644
    a b void TVOSDMenuEntryList::InitDefaultEntries(void) 
    232232    curMenuEntries.append(
    233233        new TVOSDMenuEntry("AUDIOSYNC",           1, 1, 1, 1 , "Audio Sync"));
    234234    curMenuEntries.append(
     235        new TVOSDMenuEntry("TOGGLEUPMIX",        1, 1, 1, 1, "Toggle Upmixer"));
     236    curMenuEntries.append(
    235237        new TVOSDMenuEntry("TIMESTRETCH",        1, 1, 1, 1, "Time Stretch"));
    236238    curMenuEntries.append(
    237239        new TVOSDMenuEntry("VIDEOSCAN",            1, 1, 1, 1, "Video Scan"));
  • mythtv/programs/mythfrontend/globalsettings.cpp

    diff --git a/mythtv/programs/mythfrontend/globalsettings.cpp b/mythtv/programs/mythfrontend/globalsettings.cpp
    index d61cf26..c5d0406 100644
    a b static HostComboBox *AudioUpmixType() 
    119119    return gc;
    120120}
    121121
     122static HostComboBox *SRCQuality()
     123{
     124    HostComboBox *gc = new HostComboBox("SRCQuality", false);
     125    gc->setLabel(QObject::tr("Sample Rate Conversion"));
     126    gc->addSelection(QObject::tr("Best"), "3", true); // default
     127    gc->addSelection(QObject::tr("Medium"), "2");
     128    gc->addSelection(QObject::tr("Fastest"), "1");
     129    gc->setHelpText(
     130            QObject::tr(
     131                "Set the quality of audio sample rate conversion. "
     132                "This only affects non 48000Hz PCM audio. "
     133                "All three options offer a worst-case SNR of 97dB. "
     134                "'Best' at a bandwidth of 97%. "
     135                "'Medium' at a bandwidth of 90%. "
     136                "'Fastest' at a bandwidth of 80%. "
     137            )
     138    );
     139    return gc;
     140}
     141
     142
    122143static HostComboBox *PassThroughOutputDevice()
    123144{
    124145    HostComboBox *gc = new HostComboBox("PassThruOutputDevice", true);
    class AudioSystemSettingsGroup : public VerticalConfigurationGroup 
    34463467
    34473468        addChild(MaxAudioChannels());
    34483469        addChild(AudioUpmixType());
     3470        addChild(SRCQuality());
    34493471
    34503472        // General boolean settings
    34513473        addChild(AC3PassThrough());
  • mythtv/programs/mythtranscode/transcode.cpp

    diff --git a/mythtv/programs/mythtranscode/transcode.cpp b/mythtv/programs/mythtranscode/transcode.cpp
    index a69ceb1..9958473 100644
    a b class AudioReencodeBuffer : public AudioOutput 
    4949    AudioReencodeBuffer(int audio_bits, int audio_channels)
    5050    {
    5151        Reset();
    52         const AudioSettings settings(audio_bits, audio_channels, 0, false);
     52        const AudioSettings settings(audio_bits, audio_channels, 0, 0, false);
    5353        Reconfigure(settings);
    5454        bufsize = 512000;
    5555        audiobuffer = new unsigned char[bufsize];
    class AudioReencodeBuffer : public AudioOutput 
    222222        // Do nothing
    223223        return kMuteOff;
    224224    }
     225    virtual bool ToggleUpmix(void)
     226    {
     227        // Do nothing
     228        return false;
     229    }
    225230
    226231    //  These are pure virtual in AudioOutput, but we don't need them here
    227232    virtual void bufferOutputData(bool){ return; }