OSDN Git Service

#39490 環境によっては同じ名前のWASAPIデバイスが複数定義されている場合に対応。 実際に利用可能なWASAPIデバイスのみ利用する。
[dtxmania/dtxmania.git] / FDK / コード / 03.サウンド / CSoundDeviceWASAPI.cs
index 6cd0824..4ad9cff 100644 (file)
@@ -29,6 +29,8 @@ namespace FDK
                        protected set;
                }
 
+               public string strRecordFileType = null;
+
                // CSoundTimer 用に公開しているプロパティ
 
                public long n経過時間ms
@@ -102,6 +104,13 @@ namespace FDK
                                }
                        }
                }
+
+               public string strDefaultSoundDeviceBusType {
+                       get;
+                       protected set;
+               }
+
+               
                // メソッド
 
                /// <summary>
@@ -110,7 +119,7 @@ namespace FDK
                /// <param name="mode"></param>
                /// <param name="n希望バッファサイズms">WASAPIのサウンドバッファサイズ</param>
                /// <param name="n更新間隔ms">サウンドバッファの更新間隔</param>
-               public CSoundDeviceWASAPI( Eデバイスモード mode, long n希望バッファサイズms, long n更新間隔ms )
+               public CSoundDeviceWASAPI( Eデバイスモード mode, long n希望バッファサイズms, long n更新間隔ms, string strRecordFileType, string strEncoderPath )
                {
                        // 初期化。
 
@@ -181,20 +190,32 @@ namespace FDK
                        #region [ デバッグ用: サウンドデバイスのenumerateと、ログ出力 ]
                        //(デバッグ用)
                        Trace.TraceInformation("サウンドデバイス一覧:");
-                       int a, count = 0;
+                       int a;
+                       string strDefaultSoundDeviceName = null;
                        BASS_DEVICEINFO[] bassDevInfos = Bass.BASS_GetDeviceInfos();
                        for (a = 0; a < bassDevInfos.GetLength(0); a++)
                        {
                                {
-                                       Trace.TraceInformation("Sound Device #{0}: {1}: IsDefault={2}, isEnabled={3}, flags={4}, driver={5}",
+                                       Trace.TraceInformation("Sound Device #{0}: {1}: IsDefault={2}, isEnabled={3}, flags={4}, id={5}",
                                                a,
                                                bassDevInfos[a].name,
                                                bassDevInfos[a].IsDefault,
                                                bassDevInfos[a].IsEnabled,
                                                bassDevInfos[a].flags,
-                                               bassDevInfos[a].driver
+                                               bassDevInfos[a].id
                                        );
-                                       count++; // count it
+                                       if (bassDevInfos[a].IsDefault)
+                                       {
+                                               // これはOS標準のdefault device。後でWASAPIのdefault deviceと比較する。
+                                               strDefaultSoundDeviceName = bassDevInfos[a].name;
+                                               
+                                               // 以下はOS標準 default deviceのbus type (PNPIDの頭の文字列)。上位側で使用する。
+                                               string[] s = bassDevInfos[a].id.ToString().ToUpper().Split(new char[] { '#' });
+                                               if (s != null && s[0] != null)
+                                               {
+                                                       strDefaultSoundDeviceBusType = s[0];
+                                               }
+                                       }
                                }
                        }
                        #endregion
@@ -213,9 +234,23 @@ namespace FDK
                        BASS_WASAPI_DEVICEINFO deviceInfo;
                        for ( int n = 0; ( deviceInfo = BassWasapi.BASS_WASAPI_GetDeviceInfo( n ) ) != null; n++ )
                        {
-                               if ( deviceInfo.IsDefault )
+                               // #37940 2018.2.15: BASS_DEVICEINFOとBASS_WASAPI_DEVICEINFOで、IsDefaultとなっているデバイスが異なる場合がある。
+                               // (WASAPIでIsDefaultとなっているデバイスが正しくない場合がある)
+                               // そのため、BASS_DEVICEでIsDefaultとなっているものを探し、それと同じ名前のWASAPIデバイスを使用する。
+                               // #39490 2019.8.19: 更に、環境によっては同じ名前のWASAPIデバイスが複数定義されている場合があるため、
+                               // 実際に利用可能なWASAPIデバイスのみに対象を絞り込む。
+                               // (具体的には、defperiod, minperiod, mixchans, mixfreqがすべて0のデバイスは使用不可のため
+                               //  これらが0でないものを選択する)
+                               //if ( deviceInfo.IsDefault )
+                               if ( deviceInfo.name == strDefaultSoundDeviceName && deviceInfo.mixfreq > 0 )
                                {
                                        nDevNo = n;
+#region [ 既定の出力デバイスの情報を表示 ]
+Trace.TraceInformation("WASAPI Device #{0}: {1}: IsDefault={2}, defPeriod={3}s, minperiod={4}s, mixchans={5}, mixfreq={6}",
+       n,
+       deviceInfo.name,
+       deviceInfo.IsDefault, deviceInfo.defperiod, deviceInfo.minperiod, deviceInfo.mixchans, deviceInfo.mixfreq);
+#endregion
                                        break;
                                }
                        }
@@ -257,7 +292,6 @@ namespace FDK
                                                a,
                                                wasapiDevInfo.name,
                                                wasapiDevInfo.IsDefault, wasapiDevInfo.defperiod, wasapiDevInfo.minperiod, wasapiDevInfo.mixchans, wasapiDevInfo.mixfreq);
-                                       count++; // count it
                                }
                        }
                #endregion
@@ -265,7 +299,7 @@ namespace FDK
                Retry:
                        var flags = (mode == Eデバイスモード.排他) ? BASSWASAPIInit.BASS_WASAPI_AUTOFORMAT | BASSWASAPIInit.BASS_WASAPI_EXCLUSIVE : BASSWASAPIInit.BASS_WASAPI_AUTOFORMAT;
                        //var flags = ( mode == Eデバイスモード.排他 ) ? BASSWASAPIInit.BASS_WASAPI_AUTOFORMAT | BASSWASAPIInit.BASS_WASAPI_EVENT | BASSWASAPIInit.BASS_WASAPI_EXCLUSIVE : BASSWASAPIInit.BASS_WASAPI_AUTOFORMAT | BASSWASAPIInit.BASS_WASAPI_EVENT;
-                       if ( COS.bIsWin7OrLater && CSound管理.bSoundUpdateByEventWASAPI )
+                       if ( COS.bIsWin7OrLater() && CSound管理.bSoundUpdateByEventWASAPI )
                        {
                                flags |= BASSWASAPIInit.BASS_WASAPI_EVENT;      // Win7以降の場合は、WASAPIをevent drivenで動作させてCPU負荷減、レイテインシ改善
                        }
@@ -307,8 +341,8 @@ namespace FDK
                                        f希望バッファサイズsec = f更新間隔sec * 2;
                                }
                        }
-
-                       if (COS.bIsWin10OrLater && (mode == Eデバイスモード.共有))             // Win10 low latency shared mode support
+                       else
+                       if (COS.bIsWin10OrLater() && (mode == Eデバイスモード.共有))           // Win10 low latency shared mode support
                        {
                                // バッファ自動設定をユーザーが望む場合は、periodを最小値にする。さもなくば、バッファサイズとしてユーザーが指定した値を、periodとして用いる。
                                if (n希望バッファサイズms == 0)
@@ -318,6 +352,10 @@ namespace FDK
                                else
                                {
                                        f更新間隔sec = n希望バッファサイズms / 1000.0f;
+                                       if (f更新間隔sec < deviceInfo.minperiod)
+                                       {
+                                               f更新間隔sec = deviceInfo.minperiod;
+                                       }
                                }
                                f希望バッファサイズsec = 0.0f;
                        }
@@ -325,7 +363,7 @@ namespace FDK
                        Trace.TraceInformation("f希望バッファサイズsec=" + f希望バッファサイズsec + ", f更新間隔sec=" + f更新間隔sec + ": Win10 low latency audio 考慮後");
 
                        Trace.TraceInformation("Start Bass_Wasapi_Init(device=" + nDevNo + ", freq=" + n周波数 + ", nchans=" + nチャンネル数 + ", flags=" + flags + "," +
-                               " buffer=" + f希望バッファサイズsec + ", period=" + f更新間隔sec);
+                               " buffer=" + f希望バッファサイズsec + ", period=" + f更新間隔sec + ")" );
                        if (BassWasapi.BASS_WASAPI_Init(nDevNo, n周波数, nチャンネル数, flags, f希望バッファサイズsec, f更新間隔sec, this.tWasapiProc, IntPtr.Zero))
                        {
                                        if ( mode == Eデバイスモード.排他 )
@@ -420,20 +458,33 @@ namespace FDK
                                //-----------------
                                #endregion
                        }
-
+#if TEST_MultiThreadedMixer
+                       //LoadLibraryに失敗する・・・
+                       //BASSThreadedMixerLibraryWrapper.InitBASSThreadedMixerLibrary();
+#endif
 
 
                        // WASAPI出力と同じフォーマットを持つ BASS ミキサーを作成。
+                       // 1つのまとめとなるmixer (hMixer) と、そこにつなぐ複数の楽器別mixer (hMixer _forChips)を作成。
 
                        //Debug.Assert( Bass.BASS_SetConfig( BASSConfig.BASS_CONFIG_MIXER_BUFFER, 5 ),          // バッファ量を最大量の5にする
                        //      string.Format( "BASS_SetConfig(CONFIG_MIXER_BUFFER) に失敗しました。[{0}", Bass.BASS_ErrorGetCode() ) );
 
                        var info = BassWasapi.BASS_WASAPI_GetInfo();
+#if TEST_MultiThreadedMixer
+                       this.hMixer = BASSThreadedMixerLibraryWrapper.BASS_ThreadedMixer_Create(
+                               info.freq,
+                               info.chans,
+                               (int)(BASSFlag.BASS_MIXER_NONSTOP | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_MIXER_POSEX),
+                               out hMixerThreaded
+                       );
+#else
                        this.hMixer = BassMix.BASS_Mixer_StreamCreate(
                                info.freq,
                                info.chans,
-                               BASSFlag.BASS_MIXER_NONSTOP | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_MIXER_POSEX );   // デコードのみ=発声しない。WASAPIに出力されるだけ。
-                       if ( this.hMixer == 0 )
+                               BASSFlag.BASS_MIXER_NONSTOP | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_MIXER_POSEX);    // デコードのみ=発声しない。WASAPIに出力されるだけ。
+#endif
+                       if (this.hMixer == 0 )
                        {
                                BASSError errcode = Bass.BASS_ErrorGetCode();
                                BassWasapi.BASS_WASAPI_Free();
@@ -443,6 +494,50 @@ namespace FDK
                        }
 
 
+                       for (int i = 0; i <= (int)CSound.EInstType.Unknown; i++)
+                       {
+#if TEST_MultiThreadedMixer
+                               this.hMixer_Chips[i] = BASSThreadedMixerLibraryWrapper.BASS_ThreadedMixer_Create(
+                                       info.freq,
+                                       info.chans,
+                                       (int)(BASSFlag.BASS_MIXER_NONSTOP | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_MIXER_POSEX),
+                                       out this.hMixerThreaded_Chips[i]
+                               );    // デコードのみ=発声しない。WASAPIに出力されるだけ。
+#else
+                               this.hMixer_Chips[ i ] = BassMix.BASS_Mixer_StreamCreate(
+                                       info.freq,
+                                       info.chans,
+                                       BASSFlag.BASS_MIXER_NONSTOP | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_MIXER_POSEX);    // デコードのみ=発声しない。WASAPIに出力されるだけ。
+#endif
+                               if (this.hMixer_Chips[ i ] == 0)
+                               {
+                                       BASSError errcode = Bass.BASS_ErrorGetCode();
+                                       BassWasapi.BASS_WASAPI_Free();
+                                       Bass.BASS_Free();
+                                       this.bIsBASSFree = true;
+                                       throw new Exception(string.Format("BASSミキサ(楽器[{1}]ごとのmixing)の作成に失敗しました。[{0}]", errcode, i));
+                               }
+
+                               // Mixerのボリューム設定
+                               Bass.BASS_ChannelSetAttribute(this.hMixer_Chips[i], BASSAttribute.BASS_ATTRIB_VOL, CSound管理.nMixerVolume[i] / 100.0f);
+                               //Trace.TraceInformation("Vol{0}: {1}", i, CSound管理.nMixerVolume[i]);
+
+#if TEST_MultiThreadedMixer
+                               bool b1 = BASSThreadedMixerLibraryWrapper.BASS_ThreadedMixer_AddSource(this.hMixerThreaded, this.hMixer_Chips[i], IntPtr.Zero);
+#else
+                               bool b1 = BassMix.BASS_Mixer_StreamAddChannel(this.hMixer, this.hMixer_Chips[i], BASSFlag.BASS_DEFAULT);
+#endif
+                               if (!b1)
+                               {
+                                       BASSError errcode = Bass.BASS_ErrorGetCode();
+                                       BassWasapi.BASS_WASAPI_Free();
+                                       Bass.BASS_Free();
+                                       this.bIsBASSFree = true;
+                                       throw new Exception(string.Format("個別BASSミキサ({1}}から(mixing)への接続に失敗しました。[{0}]", errcode, i));
+                               };
+
+                       }
+
                        // BASS ミキサーの1秒あたりのバイト数を算出。
 
                        var mixerInfo = Bass.BASS_ChannelGetInfo( this.hMixer );
@@ -481,41 +576,122 @@ namespace FDK
                        }
 
 
-                       //録音テスト
-                       //w = new EncoderWAV( this.hMixer_DeviceOut );
-                       //w.InputFile = null;    //STDIN
-                       //w.OutputFile = "test2.wav";
-                       //w.Start( null, IntPtr.Zero, false );
-                       // decode the stream (if not using a decoding channel, simply call "Bass.BASS_ChannelPlay" here) 
+                       // 録音設定(DTX2WAV)
+                       if (!string.IsNullOrEmpty(strRecordFileType))
+                       {
+                               switch (strRecordFileType.ToUpper())
+                               {
+                                       case "WAV":
+                                               {
+                                                       var e = new EncoderWAV(this.hMixer_DeviceOut);
+                                                       //e.WAV_EncoderType = BASSChannelType.BASS_CTYPE_STREAM_WAV_PCM;
+                                                       encoder = e;
+                                               }
+                                               break;
+                                       case "OGG":
+                                               {
+                                                       var e = new EncoderOGG(this.hMixer_DeviceOut);
+                                                       e.EncoderDirectory = strEncoderPath;
+                                                       e.OGG_UseQualityMode = true;
+                                                       e.OGG_Quality = (float)CSound管理.nBitrate;
+                                                       //e.OGG_Bitrate = 128;
+                                                       //e.OGG_MinBitrate = 0;
+                                                       //e.OGG_MaxBitrate = 0;
+
+                                                       encoder = e;
+                                               }
+                                               break;
+                                       case "MP3":
+                                               {
+                                                       var e = new EncoderLAME(this.hMixer_DeviceOut);
+                                                       e.EncoderDirectory = strEncoderPath;
+                                                       e.LAME_UseVBR = false;
+                                                       e.LAME_Bitrate = CSound管理.nBitrate;
+                                                       encoder = e;
+                                               }
+                                               break;
+                                       default:
+                                               encoder = new EncoderWAV(this.hMixer_DeviceOut);
+                                               break;
+                               }
+                               encoder.InputFile = null;    //STDIN
+                               encoder.OutputFile = CSound管理.strRecordOutFilename;
+                               encoder.UseAsyncQueue = true;
+                               encoder.Start(null, IntPtr.Zero, true);     // PAUSE状態で録音開始
+                       }
+                       //Bass.BASS_ChannelSetAttribute(this.hMixer_DeviceOut, BASSAttribute.BASS_ATTRIB_VOL, 0.10f);
+                       //Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_GVOL_SAMPLE, 1000);
+                       //Bass.BASS_SetVolume(0.1f);
 
                        // 出力を開始。
-
                        BassWasapi.BASS_WASAPI_Start();
                }
-               #region [ tサウンドを作成する() ]
-               public CSound tサウンドを作成する( string strファイル名 )
+
+#region [録音開始]
+               public bool tStartRecording()
+               {
+                       return encoder.Pause(false);
+               }
+#endregion
+#region [録音終了]
+               public bool tStopRecording()
+               {
+                       return encoder.Stop(true);
+               }
+#endregion
+
+#region [ tサウンドを作成する() ]
+               public CSound tサウンドを作成する(string strファイル名)
+               {
+                       return tサウンドを作成する( strファイル名, CSound.EInstType.Unknown );
+               }
+               public CSound tサウンドを作成する( string strファイル名, CSound.EInstType eInstType )
                {
                        var sound = new CSound();
-                       sound.tWASAPIサウンドを作成する( strファイル名, this.hMixer, this.e出力デバイス );
+#if TEST_MultiThreadedMixer
+                       int hmixer = (int)hMixerThreaded_Chips[ (int)eInstType ];
+#else
+                       int hmixer = hMixer_Chips[(int)eInstType];
+#endif
+                       sound.tWASAPIサウンドを作成する( strファイル名, hmixer, this.e出力デバイス, eInstType );
                        return sound;
                }
                public CSound tサウンドを作成する( byte[] byArrWAVファイルイメージ )
                {
+                       return tサウンドを作成する( byArrWAVファイルイメージ, CSound.EInstType.Unknown);
+               }
+               public CSound tサウンドを作成する( byte[] byArrWAVファイルイメージ, CSound.EInstType eInstType )
+               {
                        var sound = new CSound();
-                       sound.tWASAPIサウンドを作成する( byArrWAVファイルイメージ, this.hMixer, this.e出力デバイス );
+#if TEST_MultiThreadedMixer
+                       int hmixer = (int)hMixerThreaded_Chips[(int)eInstType];
+#else
+                       int hmixer = hMixer_Chips[(int)eInstType];
+#endif
+                       sound.tWASAPIサウンドを作成する( byArrWAVファイルイメージ, hmixer, this.e出力デバイス, eInstType );
                        return sound;
                }
-               public void tサウンドを作成する( string strファイル名, ref CSound sound )
+               public void tサウンドを作成する( string strファイル名, ref CSound sound, CSound.EInstType eInstType )
                {
-                       sound.tWASAPIサウンドを作成する( strファイル名, this.hMixer, this.e出力デバイス );
+#if TEST_MultiThreadedMixer
+                       int hmixer = (int)hMixerThreaded_Chips[(int)eInstType];
+#else
+                       int hmixer = hMixer_Chips[(int)eInstType];
+#endif
+                       sound.tWASAPIサウンドを作成する( strファイル名, hmixer, this.e出力デバイス, eInstType );
                }
-               public void tサウンドを作成する( byte[] byArrWAVファイルイメージ, ref CSound sound )
+               public void tサウンドを作成する( byte[] byArrWAVファイルイメージ, ref CSound sound, CSound.EInstType eInstType)
                {
-                       sound.tWASAPIサウンドを作成する( byArrWAVファイルイメージ, this.hMixer, this.e出力デバイス );
+#if TEST_MultiThreadedMixer
+                       int hmixer = (int)hMixerThreaded_Chips[(int)eInstType];
+#else
+                       int hmixer = hMixer_Chips[(int)eInstType];
+#endif
+                       sound.tWASAPIサウンドを作成する( byArrWAVファイルイメージ, hmixer, this.e出力デバイス, eInstType );
                }
-               #endregion
+#endregion
 
-               #region [ Dispose-Finallizeパターン実装 ]
+#region [ Dispose-Finallizeパターン実装 ]
                //-----------------
                public void Dispose()
                {
@@ -524,15 +700,50 @@ namespace FDK
                }
                protected void Dispose( bool bManagedDispose )
                {
-                       //if ( w != null )
-                       //{
-                       //      w.Stop();  // finish
-                       //}
-                       this.e出力デバイス = ESoundDeviceType.Unknown;            // まず出力停止する(Dispose中にクラス内にアクセスされることを防ぐ)
-                       if ( hMixer != -1 )
+                       if ( encoder != null )
                        {
-                               Bass.BASS_StreamFree( this.hMixer );
+                               encoder.Stop();  // finish
+                               encoder.Dispose();
+                               encoder = null;
                        }
+                       this.e出力デバイス = ESoundDeviceType.Unknown;        // まず出力停止する(Dispose中にクラス内にアクセスされることを防ぐ)
+
+                       if ( this.hMixer_DeviceOut != 0 )
+                       {
+                               BassMix.BASS_Mixer_ChannelPause(this.hMixer_DeviceOut);
+                               Bass.BASS_StreamFree(this.hMixer_DeviceOut);
+                               this.hMixer_DeviceOut = 0;
+                       }
+                       if (this.hMixer_Record != 0)
+                       {
+                               BassMix.BASS_Mixer_ChannelPause(this.hMixer_Record);
+                               Bass.BASS_StreamFree(this.hMixer_Record);
+                               this.hMixer_Record = 0;
+                       }
+
+                       if (hMixer != 0)
+                       {
+                               BassMix.BASS_Mixer_ChannelPause(this.hMixer_Record);
+                               Bass.BASS_StreamFree(this.hMixer);
+                       }
+                       if (this.hMixer_Chips != null)
+                       {
+                               for (int i = 0; i <= (int)CSound.EInstType.Unknown; i++)
+                               {
+                                       if (this.hMixer_Chips[i] != 0)
+                                       {
+                                               // Mixerにinputされるchannelsがfreeされると、Mixerへのinputも自動でremoveされる。
+                                               // 従い、ここでは、mixer本体をfreeするだけでよい
+                                               BassMix.BASS_Mixer_ChannelPause(this.hMixer_Chips[i]);
+                                               Bass.BASS_StreamFree(this.hMixer_Chips[i]);
+                                               this.hMixer_Chips[i] = 0;
+                                       }
+                               }
+                       }
+#if TEST_MultiThreadedMixer
+                       //BASSThreadedMixerLibraryWrapper.FreeBASSThreadedMixerLibrary();               
+#endif
+
                        if ( !this.bIsBASSFree )
                        {
                                BassWasapi.BASS_WASAPI_Free();  // システムタイマより先に呼び出すこと。(tWasapi処理() の中でシステムタイマを参照してるため)
@@ -549,12 +760,18 @@ namespace FDK
                        this.Dispose( false );
                }
                //-----------------
-               #endregion
-
-               protected int hMixer = -1;
-               protected int hMixer_DeviceOut = -1;
-               protected int hMixer_Record = -1;
-               protected EncoderWAV w;
+#endregion
+
+               protected int hMixer = 0;
+               protected int hMixer_DeviceOut = 0;
+               protected int hMixer_Record = 0;
+               protected int[] hMixer_Chips = new int[(int)CSound.EInstType.Unknown + 1];  //DTX2WAV対応 BGM, SE, Drums...を別々のmixerに入れて、個別に音量変更できるようにする
+
+#if TEST_MultiThreadedMixer
+               protected IntPtr hMixerThreaded = IntPtr.Zero;
+               protected IntPtr[] hMixerThreaded_Chips = new IntPtr[(int)CSound.EInstType.Unknown + 1];
+#endif
+               protected BaseEncoder encoder;
                protected int stream;
                protected WASAPIPROC tWasapiProc = null;
 
@@ -562,7 +779,8 @@ namespace FDK
                {
                        // BASSミキサからの出力データをそのまま WASAPI buffer へ丸投げ。
 
-                       int num = Bass.BASS_ChannelGetData( this.hMixer_DeviceOut, buffer, length );            // num = 実際に転送した長さ
+                       int num = Bass.BASS_ChannelGetData( this.hMixer_DeviceOut, buffer, length );        // num = 実際に転送した長さ
+                       //int num = BassMix.BASS_Mixer_ChannelGetData(this.hMixer_DeviceOut, buffer, length);      // これだと動作がめちゃくちゃ重くなる
                        if ( num == -1 ) num = 0;