
#include "TestSound.h"
#include "CSound.h"

#ifdef EVA_COMPOSITE
extern       char VERSION_STRING[];
#else
static const char VERSION_STRING[]= UJI_APPVER;
#endif
static const char VERSION_DATE[]  =	__DATE__ " " __TIME__ ;

#define  TESTSOUND_DEBUGGER 0 // デバッグ時には 1 に

using namespace uji::sys;

namespace
{
    static uji::eva::sound::TestSound *s_pTs;
    static uji::eva::csnd::CSound     *s_pCsnd;
    
    static bool s_IsInitializeHWCHK = false;    // nn::codec::HardwareCheck クラスのイニシャライズ判定用
    static bool s_IsInitializeSound = false;    // uji::eva::sound::TestSound クラスのイニシャライズ判定用
    static bool s_ThreadSoundFlag = false;      // サウンドスレッド 判定用
    static nn::os::Thread s_ThreadSound;
    
    nn::Handle s_Session;
    
    
    static const u16 nFiles = WAV_FILENUM;  // 使用できる voice の最大値は 24
    static u8*                 s_apMemory[nFiles];
    static nn::snd::Voice*     s_apVoice[nFiles];
    static nn::snd::WaveBuffer s_aBuffer[nFiles];
    
    static u8*                 s_pMemory = NULL;
    static nn::snd::Voice*     s_pVoice  = NULL;
    static nn::snd::WaveBuffer s_Buffer;
}

namespace uji {
namespace eva {
namespace sound {

/*---------------------------------------------------------------------------
  Desc: ログカウント付きPrintf
---------------------------------------------------------------------------*/
void TestSound::LogPrintfAndUpdateDisplay(InputTextWindow *win, sys::ATTR_TEXT_COLOR color, const char* format, ...)
{
    sys::ATTR_TEXT_COLOR prev_color = win->GetTextColor();
    win->SetTextColor(color);
    va_list vlist;
    va_start(vlist, format);
    win->VPrintf(format, vlist);    
    va_end(vlist); 
    
    win->SetTextColor(prev_color);
    
#if TESTSOUND_DEBUGGER==1
    // デバッグモードの時のみ画面出力
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    
    gfx->m_DrawFramework->SetRenderTarget(NN_GX_DISPLAY0);  
    gfx->m_DrawFramework->Clear();
    uji::sys::Menu::m_WindowManager.DrawDisplay0();
    gfx->m_DrawFramework->SwapBuffers();
    
    gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);
#endif
}

//===========================================================================
//===========================================================================
//                            スレッド関係
//===========================================================================
//===========================================================================
/*---------------------------------------------------------------------------
  Desc: (Wrapper) ThreadSound のラッパー
---------------------------------------------------------------------------*/
void TestSound::WrappingThreadSound(void* param)
{
    TestSound* pTs = reinterpret_cast< TestSound* >( param );
    pTs->ThreadSound();
}

/*---------------------------------------------------------------------------
  Desc: (Thread) サウンドスレッド
---------------------------------------------------------------------------*/
void TestSound::ThreadSound()
{
    NN_LOG("Create ThreadSound!\n");
    
    s_ThreadSoundFlag = true;
    while (s_ThreadSoundFlag)
    {
        nn::snd::WaitForDspSync();      // DSP からのデータ受信を待つ。
        nn::snd::SendParameterToDsp();  // パラメータを DSP に送信。
    }
    
    NN_LOG("Exit ThreadSound!\n");
}

/*---------------------------------------------------------------------------
  Desc: サウンドスレッドを起動
---------------------------------------------------------------------------*/
void TestSound::StartThreadSound()
{
    const int SOUND_THREAD_STACK_SIZE = 4096;
    const int SOUND_THREAD_PRIORITY = 2;
    
    // サウンドスレッドを起動（DSP 割り込みイベント待ち）
    s_ThreadSound.StartUsingAutoStack(
        WrappingThreadSound,
        this,
        SOUND_THREAD_STACK_SIZE,
        SOUND_THREAD_PRIORITY
    );
}

/*---------------------------------------------------------------------------
  Desc: サウンドスレッド停止
---------------------------------------------------------------------------*/
void TestSound::StopThreadSound()
{
    s_ThreadSoundFlag = false;
    s_ThreadSound.Join();             // スレッド終了待ち
    s_ThreadSound.Finalize();         // スレッド破棄
}


//===========================================================================
//===========================================================================
//                      配列でＷＡＶファイルを指定
//===========================================================================
//===========================================================================
/*---------------------------------------------------------------------------
  Desc: サウンド初期化
---------------------------------------------------------------------------*/
void TestSound::InitializeSound(f32 volume, u8 outputChannel, bool loopFlag)
{
    sys::InputTextWindow *win = new uji::sys::InputTextWindow(56,33,14,uji::sys::Menu::m_WindowManager);
    win->SetTitle( "DebugWindow" );
    Menu::m_WindowManager.CreateWindow( win, NN_GX_DISPLAY0, 0, 0 );
    
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "InitializeSound() start\n");
    
    nn::Result result;

    // dsp, snd の初期化
    uji::eva::SoundInitializer().InitSDK();
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "InitializeSDK() done\n");

    // サウンドスレッド開始
    StartThreadSound();
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "StartThreadSound() start\n");
    
    if( uji::sys::PLATFORM_FTR == uji::sys::GetPlatformType())
    {
#if defined(EVA_BOARD) || defined(EVA_INTERFACE)
        // FTRの場合でも基板検査・I/F検査時はサウンド出力をサラウンドに（ヘッドホン検査用）
        nn::snd::SetSoundOutputMode( nn::snd::OUTPUT_MODE_STEREO );
        LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "SetSoundOutputMode: OUTPUT_MODE_STEREO\n");
#else
        // FTRの場合はサウンド出力をモノラルに
        nn::snd::SetSoundOutputMode(nn::snd::OUTPUT_MODE_MONO);
        LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "SetSoundOutputMode: OUTPUT_MODE_MONO\n");
#endif
    }else
    {
        // サウンド出力をステレオに
        nn::snd::SetSoundOutputMode(nn::snd::OUTPUT_MODE_STEREO);
        LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "SetSoundOutputMode: OUTPUT_MODE_STEREO\n");
    }
    
    NN_LOG("Loading wav files...\n");
    
    for (int i = 0; i < nFiles; i++)
    {
        s_apMemory[i] = NULL;
        s_apVoice[i]  = NULL;
        
        if(apFileNames[i] == NULL)
        {
//※NG処理追加----------------------
            LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_RED, "Sound file isn't exist.\n");
            continue;
//----------------------------------
        }
        nn::fs::FileReader fileReader;
        result = fileReader.TryInitialize( apFileNames[i] );
        NN_UTIL_PANIC_IF_FAILED(result);

        if (::std::strcmp(::std::strrchr(apFileNames[i], '.'), ".wav") == false)
        {
            // 連続メモリ領域の取得、確認
            s_apMemory[i] = reinterpret_cast<u8*>(uji::sys::AllocDeviceMemory(GetWaveLength(fileReader), 32));
            if (s_apMemory[i] == NULL)
            {
//※NG処理追加----------------------
                NN_LOG("* Warning: Failed to allocate continuous memory\n");
                continue;
//----------------------------------
            }

            WaveFmt fmt;
            WaveData data;
            
            // Wave データを読み込み、キャッシュを無効に
            data.buf = s_apMemory[i];
            LoadWave(fileReader, &fmt, &data);
            nn::snd::FlushDataCache(reinterpret_cast<uptr>(s_apMemory[i]), data.size);

            NN_LOG("%s (%1dch, %5dHz, %2d-bit wav file)\n",
                       apFileNames[i], fmt.channel, fmt.sample_rate, fmt.quantum_bits);
            LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "%s\n", apFileNames[i]);
            nn::snd::SampleFormat format = (fmt.quantum_bits == 8) ?
                                                    nn::snd::SAMPLE_FORMAT_PCM8 :
                                                    nn::snd::SAMPLE_FORMAT_PCM16;

            nn::snd::InitializeWaveBuffer(&s_aBuffer[i]);
            s_aBuffer[i].bufferAddress = s_apMemory[i];
            s_aBuffer[i].sampleLength  = nn::snd::GetSampleLength(data.size, format, fmt.channel);
            s_aBuffer[i].loopFlag      = loopFlag;

            fileReader.Finalize();

            
            /*
                Voice の準備
            */
            s_pVoice = s_apVoice[i] = nn::snd::AllocVoice(128, NULL, NULL);
            NN_TASSERT_(s_pVoice);
            
            m_MainBus = volume;
            SetChannelGain(outputChannel);                  // 各チャンネルのゲインを設定
            s_pVoice->SetVolume(0.8f);                      // ボリュームの設定
            s_pVoice->SetPitch(1.0f);                       // ピッチの設定
            s_pVoice->SetChannelCount( fmt.channel );       // チャンネル数の設定
            s_pVoice->SetSampleFormat( format );            // フォーマットを指定
            s_pVoice->SetSampleRate(fmt.sample_rate);       // サンプリングレートの設定
            
            s_pVoice->AppendWaveBuffer(&s_aBuffer[i]);      // バッファの追加
        }
    }
    
    // マスターボリュームを設定
    nn::snd::SetMasterVolume( 1.0 );
    
    Menu::m_WindowManager.DestroyWindow(win);
    delete win;
}

/*---------------------------------------------------------------------------
  Desc: サウンド終了処理
---------------------------------------------------------------------------*/
void TestSound::FinalizeSound()
{
    sys::InputTextWindow *win = new uji::sys::InputTextWindow(56,33,14,uji::sys::Menu::m_WindowManager);
    win->SetTitle( "DebugWindow" );
    Menu::m_WindowManager.CreateWindow( win, NN_GX_DISPLAY0, 0, 0 );
    
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "FinalizeSound() start\n");
    
    for(int i=0; i<nFiles; i++)
    {
        nn::snd::FreeVoice(s_apVoice[i]);
        uji::sys::Free(s_apMemory[i]);
    }
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "FreeVoice() complet\n");
    
    StopThreadSound();
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "StartThreadSound() stop\n");
    
    uji::eva::SoundInitializer().FinalizeSDK();
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "FinalizeSDK() done\n");
    
    Menu::m_WindowManager.DestroyWindow(win);
    delete win;
}

/*---------------------------------------------------------------------------
  Desc: サウンド開始

  Args: isPlaying       true:再生中、false:停止中

  Rtns: サウンドの再生状態を返します
---------------------------------------------------------------------------*/
bool TestSound::PlaySound(u16 sndId, bool* isPlaying)
{
    if( *isPlaying==false )
    {
        s_apVoice[sndId]->SetState( nn::snd::Voice::STATE_PLAY );// 再生
        *isPlaying = true;
    }
    else
    {
        s_apVoice[sndId]->SetState( nn::snd::Voice::STATE_PAUSE );// 一時停止
        *isPlaying = false;
    }
    return true;
}

/*---------------------------------------------------------------------------
  Desc: サウンド終了
---------------------------------------------------------------------------*/
bool TestSound::StopSound(u16 sndId)
{
    s_apVoice[sndId]->SetState( nn::snd::Voice::STATE_STOP );// 終了
    
    return true;
}
bool TestSound::StopSound(u16 sndId, bool* isPlaying)
{
    if(*isPlaying)
    {
        PlaySound(sndId, isPlaying);
    }
    
    s_apVoice[sndId]->SetState( nn::snd::Voice::STATE_STOP );// 終了
    
    return true;
}

/*---------------------------------------------------------------------------
  Desc: サウンドを鳴らして指定時間が経過したら止める
---------------------------------------------------------------------------*/
bool TestSound::PlaySoundOnMilliseconds(u16 sndId, s64 milliseconds)
{
    nn::os::Tick start = nn::os::Tick::GetSystemCurrent();
    nn::os::Tick current;
    
    s_apVoice[sndId]->SetState( nn::snd::Voice::STATE_PLAY );// 再生
    
    do
    {
        current = nn::os::Tick::GetSystemCurrent();
    }
    while( (current-start).ToTimeSpan().GetMilliSeconds() < milliseconds );
    
    s_apVoice[sndId]->SetState( nn::snd::Voice::STATE_STOP );// 終了
    
    return true;
}

/*---------------------------------------------------------------------------
  Desc      音量の上げ下げ

  Args      vol ボリューム

  Rtns      None.
---------------------------------------------------------------------------*/
f64 TestSound::TurnUpVolume( f64 vol )
{
    vol += 0.1;
    for( int i=0; i<nFiles; ++i)
    {
        s_apVoice[i]->SetVolume(vol);
    }
    return vol;
}
f64 TestSound::TurnDownVolume( f64 vol )
{
    vol -= 0.1;
    for( int i=0; i<nFiles; ++i)
    {
        s_apVoice[i]->SetVolume(vol);
    }
    return vol;
}


//===========================================================================
//===========================================================================
//                ファイル名でＷＡＶファイルを指定する
//===========================================================================
//===========================================================================
/*---------------------------------------------------------------------------
  Desc: サウンド初期化
---------------------------------------------------------------------------*/
void TestSound::InitializeSoundUsingFileName(char* soundFileName, f32 volume, u8 outputChannel, bool loopFlag)
{
    nn::Result result;

    // dsp, snd の初期化
    uji::eva::SoundInitializer().InitSDK();

    // サウンドスレッド開始
    StartThreadSound();

    if( uji::sys::PLATFORM_FTR == uji::sys::GetPlatformType())
    {
        // FTRの場合はサウンド出力をモノラルに
        nn::snd::SetSoundOutputMode(nn::snd::OUTPUT_MODE_MONO);
    }else
    {
        // サウンド出力をステレオに
        nn::snd::SetSoundOutputMode(nn::snd::OUTPUT_MODE_STEREO);
    }

    // マスターボリュームを設定
    nn::snd::SetMasterVolume( 1.0 );

    NN_LOG("Loading wav files...\n");
    

    if(soundFileName == NULL)
    {
//※NG処理追加----------------------
        NN_LOG("* Warning: Sound file isn't exist.\n");
//----------------------------------
    }
    nn::fs::FileReader fileReader;
    result = fileReader.TryInitialize( soundFileName );
    NN_UTIL_PANIC_IF_FAILED(result);

    if (::std::strcmp(::std::strrchr(soundFileName, '.'), ".wav") == false)
    {
        // 連続メモリ領域の取得、確認
        s_pMemory = reinterpret_cast<u8*>(uji::sys::AllocDeviceMemory(GetWaveLength(fileReader), 32));
        if (s_pMemory == NULL)
        {
//※NG処理追加----------------------
            NN_LOG("* Warning: Failed to allocate continuous memory\n");
//----------------------------------
        }

        WaveFmt fmt;
        WaveData data;
        
        // Wave データを読み込み、キャッシュを無効に
        data.buf = s_pMemory;
        LoadWave(fileReader, &fmt, &data);
        nn::snd::FlushDataCache(reinterpret_cast<uptr>(s_pMemory), data.size);

        NN_LOG("%s (%1dch, %5dHz, %2d-bit wav file)\n",
                   soundFileName, fmt.channel, fmt.sample_rate, fmt.quantum_bits);

        nn::snd::SampleFormat format = (fmt.quantum_bits == 8) ?
                                                nn::snd::SAMPLE_FORMAT_PCM8 :
                                                nn::snd::SAMPLE_FORMAT_PCM16;

        nn::snd::InitializeWaveBuffer(&s_Buffer);
        s_Buffer.bufferAddress = s_pMemory;
        s_Buffer.sampleLength  = nn::snd::GetSampleLength(data.size, format, fmt.channel);
        s_Buffer.loopFlag      = loopFlag;

        fileReader.Finalize();
        
        /*
            Voice の準備
        */
        s_pVoice = nn::snd::AllocVoice(128, NULL, NULL);
        NN_TASSERT_(s_pVoice);
        
        m_MainBus = volume;
        SetChannelGain(outputChannel);                  // 各チャンネルのゲインを設定
        s_pVoice->SetVolume(0.8f);                      // ボリュームの設定
        s_pVoice->SetPitch(1.0f);                       // ピッチの設定
        s_pVoice->SetChannelCount( fmt.channel );       // チャンネル数の設定
        s_pVoice->SetSampleFormat( format );            // フォーマットを指定
        s_pVoice->SetSampleRate(fmt.sample_rate);       // サンプリングレートの設定

        s_pVoice->AppendWaveBuffer(&s_Buffer);          // バッファの追加
    }
}

/*---------------------------------------------------------------------------
  Desc: サウンド終了処理
---------------------------------------------------------------------------*/
void TestSound::FinalizeSoundUsingFileName()
{
    nn::snd::FreeVoice(s_pVoice);
    uji::sys::Free(s_pMemory);
    
    StopThreadSound();

//#if NN_VERSION_REVISION==22048
//SDK 0.11 PEE
    uji::eva::SoundInitializer().FinalizeSDK();
//#endif
}

/*---------------------------------------------------------------------------
  Desc: サウンド開始

  Args: isPlaying       true:再生中、false:停止中

  Rtns: サウンドの再生状態を返します
---------------------------------------------------------------------------*/
bool TestSound::PlaySoundUsingFileName(bool* isPlaying)
{
    if( *isPlaying==false )
    {
        s_pVoice->SetState( nn::snd::Voice::STATE_PLAY );// 再生
        *isPlaying = true;
    }
    else
    {
        s_pVoice->SetState( nn::snd::Voice::STATE_PAUSE );// 一時停止
        *isPlaying = false;
    }
    return true;
}

/*---------------------------------------------------------------------------
  Desc: サウンド終了
---------------------------------------------------------------------------*/
bool TestSound::StopSoundUsingFileName()
{
    s_pVoice->SetState( nn::snd::Voice::STATE_STOP );// 終了
    
    return true;
}
bool TestSound::StopSoundUsingFileName(bool* isPlaying)
{
    if(*isPlaying)
    {
        PlaySoundUsingFileName(isPlaying);
    }
    
    s_pVoice->SetState( nn::snd::Voice::STATE_STOP );// 終了
    
    return true;
}

/*---------------------------------------------------------------------------
  Desc: サウンドを鳴らして指定時間が経過したら止める
---------------------------------------------------------------------------*/
bool TestSound::PlaySoundUsingFileNameOnMilliseconds(s64 milliseconds)
{
    nn::os::Tick start = nn::os::Tick::GetSystemCurrent();
    nn::os::Tick current;
    
    s_pVoice->SetState( nn::snd::Voice::STATE_PLAY );// 再生
    
    do
    {
        current = nn::os::Tick::GetSystemCurrent();
    }
    while( (current-start).ToTimeSpan().GetMilliSeconds() < milliseconds );
    
    s_pVoice->SetState( nn::snd::Voice::STATE_STOP );// 終了
    
    return true;
}


//===========================================================================
//===========================================================================
//                              共通の処理
//===========================================================================
//===========================================================================
/*---------------------------------------------------------------------------
  Desc: Voice の各チャンネルのゲインを設定
---------------------------------------------------------------------------*/
void TestSound::SetChannelGain(u8 outputChannel)
{
    nn::snd::MixParam mix;
    
    switch(outputChannel)
    {
    
    case CHANNEL_ALL:
         
        mix.mainBus[nn::snd::CHANNEL_INDEX_FRONT_LEFT ] = m_MainBus;
        mix.mainBus[nn::snd::CHANNEL_INDEX_FRONT_RIGHT] = m_MainBus;
        break;
        
    case CHANNEL_FRONT_LEFT:
    
        mix.mainBus[nn::snd::CHANNEL_INDEX_FRONT_LEFT ] = m_MainBus;
        mix.mainBus[nn::snd::CHANNEL_INDEX_FRONT_RIGHT] = 0.0f;
        break;
        
    case CHANNEL_FRONT_RIGHT:
    
        mix.mainBus[nn::snd::CHANNEL_INDEX_FRONT_LEFT ] = 0.0f;
        mix.mainBus[nn::snd::CHANNEL_INDEX_FRONT_RIGHT] = m_MainBus;
        break;
        
    }
    
    s_pVoice->SetMixParam(mix);
}

/*---------------------------------------------------------------------------
  Desc: HardwareCheck クラスのイニシャライズ
---------------------------------------------------------------------------*/
void TestSound::InitializeCodecHardwareCheck()
{
    if( s_IsInitializeHWCHK==false )
    {
        nn::codec::CTR::InitializeCheck(&s_Session);
        
        s_IsInitializeHWCHK=true;
    }
}

/*---------------------------------------------------------------------------
  Desc: HardwareCheck クラスのファイナライズ
---------------------------------------------------------------------------*/
void TestSound::FinalizeCodecHardwareCheck()
{
    if( s_IsInitializeHWCHK==true )
    {
        nn::codec::CTR::FinalizeCheck(&s_Session);
        
        s_IsInitializeHWCHK=false;
    }
}

/*---------------------------------------------------------------------------
  Desc: I2S1 バス経由で正弦波基準音を鳴らす
---------------------------------------------------------------------------*/
bool TestSound::PlaySoundI2S1()
{
    /*
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    hc.SetI2SVolume(nn::codec::CTR::I2S_LINE_1,    0);
    hc.SetI2SVolume(nn::codec::CTR::I2S_LINE_2, -128);
    */
    bool isPlaying = false;
    PlaySound(LR_SIN_16BIT_1000HZ, &isPlaying);
    
    WaitMilliSeconds(500);
    
    return true;
}

/*---------------------------------------------------------------------------
  Desc: I2S1 バス経由で正弦波基準音を鳴らす
---------------------------------------------------------------------------*/
bool TestSound::PlaySoundI2S1_NEC()
{
    /*
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    hc.SetI2SVolume(nn::codec::CTR::I2S_LINE_1,    0);
    hc.SetI2SVolume(nn::codec::CTR::I2S_LINE_2, -128);
    */
    bool isPlaying = false;
    PlaySound(LR_SIN_16BIT_1000HZ, &isPlaying);
    
//    WaitMilliSeconds(500);
    
    return true;
}

/*---------------------------------------------------------------------------
  Desc: I2S2 バス経由で正弦波基準音を鳴らす
---------------------------------------------------------------------------*/
bool TestSound::PlaySoundI2S2()
{
    /*
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    hc.SetI2SVolume(nn::codec::CTR::I2S_LINE_1, -128);
    hc.SetI2SVolume(nn::codec::CTR::I2S_LINE_2,    0);
    */
    enum BcwavFileId soundFileId = SSID_SINE;
    
    sys::InputTextWindow *win = new uji::sys::InputTextWindow(56,33,14,uji::sys::Menu::m_WindowManager);
    win->SetTitle( "DebugWindow" );
    Menu::m_WindowManager.CreateWindow( win, NN_GX_DISPLAY0, 0, 0 );
    
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "InitializeCSound() start\n");
    
    s_pCsnd = new uji::eva::csnd::CSound;
    s_pCsnd->InitializeCSound();
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "InitializeCSound() done\n");
    
    s_pCsnd->SetCSound( soundFileId, true );
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "SetCSound() done\n");
    
    s_pCsnd->PlayCSound();
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "PlayCSound() done\n");
    
    WaitMilliSeconds(500);
    
    Menu::m_WindowManager.DestroyWindow(win);
    delete win;
    
    return true;
}

/*---------------------------------------------------------------------------
  Desc: I2S2 バス経由で正弦波基準音を鳴らす
---------------------------------------------------------------------------*/
bool TestSound::PlaySoundI2S2_NEC()
{
    /*
    TestInitializeCommon();
    
    nn::codec::CTR::HardwareCheck hc(s_Session);
    hc.SetI2SVolume(nn::codec::CTR::I2S_LINE_1, -128);
    hc.SetI2SVolume(nn::codec::CTR::I2S_LINE_2,    0);
    */
    enum BcwavFileId soundFileId = SSID_SINE;
    
    sys::InputTextWindow *win = new uji::sys::InputTextWindow(56,33,14,uji::sys::Menu::m_WindowManager);
    win->SetTitle( "DebugWindow" );
    Menu::m_WindowManager.CreateWindow( win, NN_GX_DISPLAY0, 0, 0 );
    
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "InitializeCSound() start\n");
    
    s_pCsnd = new uji::eva::csnd::CSound;
    s_pCsnd->InitializeCSound();
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "InitializeCSound() done\n");
    
    s_pCsnd->SetCSound( soundFileId, true );
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "SetCSound() done\n");
    
    s_pCsnd->PlayCSound();
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "PlayCSound() done\n");
    
//    WaitMilliSeconds(500);
    
    Menu::m_WindowManager.DestroyWindow(win);
    delete win;
    
    return true;
}

/*---------------------------------------------------------------------------
  Desc: I2S1 バスからの音を止める
---------------------------------------------------------------------------*/
bool TestSound::StopSoundI2S1()
{
    StopSound(LR_SIN_16BIT_1000HZ);
    
    //s_pTs->FinalizeCodecHardwareCheck();      // ToDo: もしかするとファイナライズしない方が良いかも
    
    return true;
}

/*---------------------------------------------------------------------------
  Desc: I2S2 バスからの音を止める
---------------------------------------------------------------------------*/
bool TestSound::StopSoundI2S2()
{
    sys::InputTextWindow *win = new uji::sys::InputTextWindow(56,33,14,uji::sys::Menu::m_WindowManager);
    win->SetTitle( "DebugWindow" );
    Menu::m_WindowManager.CreateWindow( win, NN_GX_DISPLAY0, 0, 0 );
    
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "StopCSound() start\n");
    
    s_pCsnd->StopCSound();
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "StopCSound() done\n");
    
    s_pCsnd->FinalizeCSound();
    LogPrintfAndUpdateDisplay(win, sys::ATTR_COLOR_WHITE, "FinalizeCSound() done\n");
    
    delete s_pCsnd;
    
    Menu::m_WindowManager.DestroyWindow(win);
    delete win;
    
    //s_pTs->FinalizeCodecHardwareCheck();      // ToDo: もしかするとファイナライズしない方が良いかも
    
    return true;
}


//===========================================================================
//===========================================================================
//                        インスタンスの作成／破棄
//===========================================================================
//===========================================================================

/*---------------------------------------------------------------------------
  Desc: TestSound クラスのインスタンス作成
---------------------------------------------------------------------------*/
void CreateInstance(f32 volume, u8 outputChannel, bool loopFlag)
{
    if( s_IsInitializeSound==false )
    {
        s_pTs = new TestSound;
        s_pTs->InitializeSound(volume, outputChannel, loopFlag);
        
        NN_LOG("@ CreateInstance(%d): completed. \n", outputChannel);
        s_IsInitializeSound=true;
    }
}
void CreateInstanceUsingFileName(char* soundFileName, f32 volume, u8 outputChannel, bool loopFlag)
{
    if( s_IsInitializeSound==false )
    {
        s_pTs = new TestSound;
        s_pTs->InitializeSoundUsingFileName(soundFileName, volume, outputChannel, loopFlag);
        
        NN_LOG("@ CreateInstance(%d)(%s): completed. \n", outputChannel, soundFileName);
        s_IsInitializeSound=true;
    }
}

/*---------------------------------------------------------------------------
  Desc: TestSound クラスのインスタンス破棄
---------------------------------------------------------------------------*/
void DeleteInstance()
{
    if( s_IsInitializeSound==true )
    {
        s_pTs->FinalizeSound();
        delete s_pTs;
        
        NN_LOG("@ DeleteInstance(): completed. \n");
        s_IsInitializeSound=false;
    }
}
void DeleteInstanceUsingFileName()
{
    if( s_IsInitializeSound==true )
    {
        s_pTs->FinalizeSoundUsingFileName();
        delete s_pTs;
        
        NN_LOG("@ DeleteInstance(): completed. \n");
        s_IsInitializeSound=false;
    }
}


//===========================================================================
//===========================================================================
//                         基板／ＩＦ検査用
//===========================================================================
//===========================================================================
/*---------------------------------------------------------------------------
  Desc: (CTR10-1) I2S1 バス経由で正弦波基準音を鳴らす
---------------------------------------------------------------------------*/
bool TestPlaySoundI2S1(uji::seq::TestResult &result)
{
    CreateInstance(0.5f, sound::CHANNEL_ALL);
    result.m_Result = s_pTs->PlaySoundI2S1();
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-14) I2S1 バス経由で正弦波基準音を鳴らす
---------------------------------------------------------------------------*/
bool TestPlaySoundI2S1_NEC(uji::seq::TestResult &result)
{
    CreateInstance(0.5f, sound::CHANNEL_ALL);
    result.m_Result = s_pTs->PlaySoundI2S1_NEC();
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-2) I2S2 バス経由で正弦波基準音を鳴らす
---------------------------------------------------------------------------*/
bool TestPlaySoundI2S2(uji::seq::TestResult &result)
{
    result.m_Result = s_pTs->PlaySoundI2S2();
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-13) I2S2 バス経由で正弦波基準音を鳴らす
---------------------------------------------------------------------------*/
bool TestPlaySoundI2S2_NEC(uji::seq::TestResult &result)
{
    result.m_Result = s_pTs->PlaySoundI2S2_NEC();
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-5) I2S2 バスからの音を止める
---------------------------------------------------------------------------*/
bool TestStopSoundI2S2(uji::seq::TestResult &result)
{
    result.m_Result = s_pTs->StopSoundI2S2();
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-6) I2S1 バスからの音を止める
---------------------------------------------------------------------------*/
bool TestStopSoundI2S1(uji::seq::TestResult &result)
{
    result.m_Result = s_pTs->StopSoundI2S1();
    DeleteInstance();
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-3) スピーカ R 出力
---------------------------------------------------------------------------*/
bool TestOutputSpeakerR(uji::seq::TestResult &result)
{
    CreateInstance(0.5f, sound::CHANNEL_FRONT_RIGHT);
    
    bool isPlaying = false;
    result.m_Result = s_pTs->PlaySound(LR_SIN_16BIT_1000HZ, &isPlaying);
    
    WaitMilliSeconds(100);
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-4) スピーカ L 出力
---------------------------------------------------------------------------*/
bool TestOutputSpeakerL(uji::seq::TestResult &result)
{
    CreateInstance(0.5f, sound::CHANNEL_FRONT_LEFT);
    
    bool isPlaying = false;
    result.m_Result = s_pTs->PlaySound(LR_SIN_16BIT_1000HZ, &isPlaying);
    
    WaitMilliSeconds(100);
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-9) スピーカ R 出力（インターフェース検査用）
---------------------------------------------------------------------------*/
bool TestOutputSpeakerRVolUp(uji::seq::TestResult &result)
{
    CreateInstance(2.0f, sound::CHANNEL_FRONT_RIGHT);
    
    bool isPlaying = false;
    result.m_Result = s_pTs->PlaySound(LR_SIN_16BIT_1000HZ, &isPlaying);
    
    WaitMilliSeconds(100);
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-10) スピーカ L 出力（インターフェース検査用）
---------------------------------------------------------------------------*/
bool TestOutputSpeakerLVolUp(uji::seq::TestResult &result)
{
    CreateInstance(2.0f, sound::CHANNEL_FRONT_LEFT);
    
    bool isPlaying = false;
    result.m_Result = s_pTs->PlaySound(LR_SIN_16BIT_1000HZ, &isPlaying);
    
    WaitMilliSeconds(100);
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-7) スピーカ R 停止
---------------------------------------------------------------------------*/
bool TestDeleteInstance1(uji::seq::TestResult &result)
{
    result.m_Result = s_pTs->StopSound(LR_SIN_16BIT_1000HZ);
    DeleteInstance();
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: (CTR10-8) スピーカ L 停止（10-7 と同等）
---------------------------------------------------------------------------*/
bool TestDeleteInstance2(uji::seq::TestResult &result)
{
    result.m_Result = s_pTs->StopSound(LR_SIN_16BIT_1000HZ);
    DeleteInstance();
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: ヘッドホンプラグが挿されるのを待ちます
---------------------------------------------------------------------------*/
bool TestWaitJackInsert(uji::seq::TestResult &result)
{
    bool IsInserting = false;
    
    // dsp, snd の初期化
    uji::eva::SoundInitializer().InitSDK();
    
    do
    {
        nn::dsp::CTR::GetHeadphoneStatus(&IsInserting);
        nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(16));
    }
    while( IsInserting==false );
    
    // ファイナライズはしない
    
    WaitMilliSeconds(500);  // 500msec待つ（やや長めに設定）
    
    result.m_Result = true;
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: ヘッドホンプラグが抜かれるのを待ちます
---------------------------------------------------------------------------*/
bool TestWaitJackPullout(uji::seq::TestResult &result)
{
    bool IsInserting = true;
    
    // dsp, snd の初期化
    uji::eva::SoundInitializer().InitSDK();
    
    do
    {
        nn::dsp::CTR::GetHeadphoneStatus(&IsInserting);
        nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(16));
    }
    while( IsInserting );
    
    // ファイナライズはしない
    
    WaitMilliSeconds(100);  // 100msec待つ
    
    result.m_Result = true;
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: 正弦波を3秒鳴らす
---------------------------------------------------------------------------*/
bool SoundSinPulse3sec(uji::seq::TestResult &result)
{    
    sound::CreateInstanceUsingFileName("rom:/snd/LR_SIN_16bit_1000Hz.wav", 2.0f, sound::CHANNEL_FRONT_RIGHT);
    
    s_pTs->PlaySoundUsingFileNameOnMilliseconds(3000);
    
    sound::DeleteInstanceUsingFileName();
    
    result.m_Result = true;
    
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: ビビり音が分かりやすい音源を4秒以上鳴らす
---------------------------------------------------------------------------*/
bool TestBibiriSound(uji::seq::TestResult &result)
{   
    // CTRの場合は検査せずにＯＫ判定で返す。
#if (NN_VERSION_MAJOR >= 3)
    if( uji::sys::PLATFORM_CTR != uji::sys::GetPlatformType())
    {
        bool isPlaying = false; // サウンド停止中
        nn::fnd::TimeSpan StartTimeSpan = nn::os::Tick::GetSystemCurrent().ToTimeSpan();
        uji::sys::Pad pad;
        sound::CreateInstanceUsingFileName("rom:/snd/Ctr_Mset_BGM_4sec.wav", 1.0f, sound::CHANNEL_ALL);
        s_pTs->PlaySoundUsingFileName(&isPlaying);
        
        do
        {
            pad.UpdatePad();
        }while( !(pad.IsButtonRepeat( Pad::BUTTON_A ) && ( nn::os::Tick::GetSystemCurrent().ToTimeSpan().GetSeconds() - StartTimeSpan.GetSeconds() > 4 ) ) );

        s_pTs->StopSoundUsingFileName(&isPlaying);
        sound::DeleteInstanceUsingFileName();
    }
#endif

    result.m_Result = true;
    return result.m_Result;
}

void UpdateDisplay(sys::JpegDrawer *jpegDrawer, wchar_t *pass)
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();

    /* ------------------------------------------------------------------------
            下画面描画
    ------------------------------------------------------------------------ */
    gfx->m_DrawFramework->SetRenderTarget(NN_GX_DISPLAY1);
    gfx->m_DrawFramework->Clear();

    // 画像表示
    jpegDrawer->OpenPicture(pass);
    jpegDrawer->DrawPicture(NN_GX_DISPLAY1);

    gfx->m_DrawFramework->SwapBuffers();
}


/*---------------------------------------------------------------------------
  Desc: ビビり音が分かりやすい音源を左右切り替えて鳴らす
---------------------------------------------------------------------------*/
bool TestLeftAndRightSpeaker(uji::seq::TestResult &result)
{   
    bool done = false;
    bool isPlaying = false; // サウンド停止中
    u8 sndChannel = sound::CHANNEL_FRONT_LEFT;
    f32 volume = 1.0f;
    
    uji::sys::Pad pad;
    
    sound::CreateInstanceUsingFileName("rom:/snd/Ctr_Mset_BGM_4sec.wav", volume, sndChannel);
    s_pTs->PlaySoundUsingFileName(&isPlaying);

    sys::JpegDrawer* jpegDrawer = new sys::JpegDrawer;
    UpdateDisplay(jpegDrawer, L"rom:/jpeg/left.jpg");

    do
    {
        pad.UpdatePad();
        
        if(pad.IsButtonDown(Pad::BUTTON_A))
        {
            s_pTs->StopSoundUsingFileName(&isPlaying);
            //一度インスタンスを消してから再生しないと、反映されないため
            sound::DeleteInstanceUsingFileName();
            if (sndChannel == sound::CHANNEL_FRONT_RIGHT)
            {
            UpdateDisplay(jpegDrawer, L"rom:/jpeg/left.jpg");
                sndChannel = sound::CHANNEL_FRONT_LEFT;
            }
            else
            {
            UpdateDisplay(jpegDrawer, L"rom:/jpeg/right.jpg");
                sndChannel = sound::CHANNEL_FRONT_RIGHT;
                done = true;
            }
            sound::CreateInstanceUsingFileName("rom:/snd/Ctr_Mset_BGM_4sec.wav", volume, sndChannel);
            s_pTs->PlaySoundUsingFileName(&isPlaying);
        }
        
    }while(!pad.IsButtonDown(Pad::BUTTON_B) || !done);
    
    s_pTs->StopSoundUsingFileName(&isPlaying);
    
    sound::DeleteInstanceUsingFileName();
    jpegDrawer->ClosePicture();
    delete jpegDrawer;

    result.m_Result = true;
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: 正弦波音源を左右切り替えて鳴らす
---------------------------------------------------------------------------*/
bool TestLeftAndRightSpeakerSin(uji::seq::TestResult &result)
{   
    bool done = false;
    bool isPlaying = false; // サウンド停止中
    u8 sndChannel = sound::CHANNEL_FRONT_LEFT;
    f32 volume = 1.0f;
    
    uji::sys::Pad pad;
    
    sound::CreateInstanceUsingFileName("rom:/snd/LR_SIN_16bit_1000Hz.wav", volume, sndChannel);
    s_pTs->PlaySoundUsingFileName(&isPlaying);

    sys::JpegDrawer* jpegDrawer = new sys::JpegDrawer;
    UpdateDisplay(jpegDrawer, L"rom:/jpeg/left.jpg");

    do
    {
        pad.UpdatePad();
        if( uji::sys::PLATFORM_FTR != uji::sys::GetPlatformType())
        {
            if(pad.IsButtonDown(Pad::BUTTON_A))
            {
                s_pTs->StopSoundUsingFileName(&isPlaying);
                //一度インスタンスを消してから再生しないと、反映されないため
                sound::DeleteInstanceUsingFileName();
                if (sndChannel == sound::CHANNEL_FRONT_RIGHT)
                {
                UpdateDisplay(jpegDrawer, L"rom:/jpeg/left.jpg");
                    sndChannel = sound::CHANNEL_FRONT_LEFT;
                }
                else
                {
                UpdateDisplay(jpegDrawer, L"rom:/jpeg/right.jpg");
                    sndChannel = sound::CHANNEL_FRONT_RIGHT;
                    done = true;
                }
                sound::CreateInstanceUsingFileName("rom:/snd/LR_SIN_16bit_1000Hz.wav", volume, sndChannel);
                s_pTs->PlaySoundUsingFileName(&isPlaying);
            }
        }else
        {
            if( false == done )
            {
                nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(3000));
                done = true;
            }
        }
        
    }while(!pad.IsButtonDown(Pad::BUTTON_B) || !done);
    
    s_pTs->StopSoundUsingFileName(&isPlaying);
    
    sound::DeleteInstanceUsingFileName();
    jpegDrawer->ClosePicture();
    delete jpegDrawer;

    result.m_Result = true;
    return result.m_Result;
}

/*---------------------------------------------------------------------------
  Desc: 無線音響用 スピーカー検査用
---------------------------------------------------------------------------*/
bool TestStartWlAudioSp(void)
{   
    bool isPlaying = false;
    
    sound::CreateInstanceUsingFileName("rom:/snd/LR_SIN_16bit_1000Hz.wav", 1.0f, sound::CHANNEL_ALL);
    s_pTs->PlaySoundUsingFileName(&isPlaying);
    
    return isPlaying;
}

bool TestStopWlAudioSp(void)
{
    bool isPlaying = true;
    
    s_pTs->StopSoundUsingFileName(&isPlaying);
    sound::DeleteInstanceUsingFileName();
    
    return true;
}

} // namespace sound
} // namespace eva
} // namespace uji

