Sound Generator Library

Fork of Sound_Generator by GR-PEACH_producer_meeting

Information

Japanese version is available in lower part of this page.
このページの後半に日本語版が用意されています.

Sound Generator

What is this?

Driver library for Sound Generator that is function of RZ/A1H.

API

Driver Wrapper API

You can use music playback function to call following APIs.

void piano4int_start( const int8_t *scores[SDG_CH_TOTAL], PIANO4INT_CB callback )

descriptionstarts music playback
argumentsscores : music data of each chanel. The number of channels is specified by SDG_CH_TOTAL.
callback : call back function by playing synchonized marker
return value-
explanationStarts music playback.
For channels not to play, set NULL to the corresponding element of scores[].
Playback is controlled by interrupt handler.
So, this function returns after initialization.
"Callback" function will be called from interrupt handler when synchronized marker is played.

void piano4int_stop( bool force )

descriptionstops music playback
argumentsforce : When this value is 1, force stop will be executed (not implemented).
return value-
explanationStop misic playback.
This function returns after finishing music playback of all channels.
This function stops interrupts, but does not release objects.

bool piano4int_status( void )

descriptionGets the plaback status
arguments-
return valueThe plaback status
explanationGets the plaback status.
If any of the channel plays music, this function returns true.

typedef void (*PIANO4INT_CB)( uint32_t channel, uint32_t value )

descriptioncall back function by playing synchonized marker
argumentschannel : Channel number
value : Synchronized marker ID
return value-
explanationThis is a user function call back by playing synchronized marker..
The argument "value" is set to the number that is described after synchronized marker.
This function is called in interrupt hander, so please shorten the processing of this function.


Driver API

int32_t R_SDG_Open( uint32_t channel, R_SDG_CLOCK clock )

descriptionopens driver
argumentschannel : Channel number (0~3)
clock : clock
return valuesuccess : DEVDRV_SUCCESS
error : DEVDRV_ERROR, etc.
explanationThis function initializes sound generator specified by argument "channel".
"clock" to set the clock to be used in the internal sound generator from either from P0φ/2 to P0φ/16.
Sample code accepts channel 1 and channel 3 only. If channel 0 or 2 is specified, this function returns an error.

int32_t R_SDG_Close( uint32_t channel )

descriptionCloses driver
argumentschannel : Channel number (0~3)
return valuesuccess : DEVDRV_SUCCESS
error : DEVDRV_ERROR,etc.
explanationThis function terminates sound generator specified by argument "channel".
In Sample code, once this function is called, clock supply is stopped, this driver will not work until calling R_SDG_Open().
If target channel has not initialized by R_SDG_Open(), this function returns error code.

int32_t R_SDG_Tone( uint32_t channel, NOTE *note )

descriptionGenerates single tone.
argumentschannel : Channel number (0~3)
note : Tone parameters
return valuesuccess : DEVDRV_SUCCESS
error : DEVDRV_ERROR,etc.
explanationThis function generates single tone. Tone is specified by argument "note".
Pitch is determined by the following equation.

Reference frequency = "clock" / [note->sfs]
Pitch = [Reference frequency] / ( 2 × [note->tone] )

Loudness is determined by note->loud. note->loud specifies the duty of the square wave to be syncthesized sound to be output.
Period square wave is high will be calculated in [note->loud / 256].
Attenuation rate is specified by note->attenuation. Attenuation is achieved by make the note->loud to 31/32 with the given period by note->attenuation.
If target channel has not initialized by R_SDG_Open(), this function returns error code.

User Definition Functions

int32_t Userdef_SDG0_Open( void )

int32_t Userdef_SDG1_Open( void )

int32_t Userdef_SDG2_Open( void )

int32_t Userdef_SDG3_Open( void )

descriptionOpen driver
argument-
return valuesuccess : DEVDRV_SUCCESS
error : the other
explanationUser of this driver must create this function.
This function is called from R_SDG_Open(), so user must create this function for each 4 channels.
In this function, user must operate following operation.
・Supplies clock to the sound generator.
・Sets pin-mux for the sound generator.
In the case this function is succeed, please set the return value of this function to DEVDRV_SUCCESS. The other value indicate an error and copy to the return value of R_SDG_Open() function.
In the sample code, initializing routine is described for channel 1 and 3, and an error routine is described for channel 0 and 2.

int32_t Userdef_SDG0_Close( void )

int32_t Userdef_SDG1_Close( void )

int32_t Userdef_SDG2_Close( void )

int32_t Userdef_SDG3_Close( void )

descriptionClose driver
argument-
return valuesuccess : DEVDRV_SUCCESS
error : the other
explanationUser of this driver must create this function.
This function is called from R_SDG_Close(), so user must create this function for each 4 channels.
In this function, user must operate following operation.
・Sets pin-mux for GPIO.
・Stops the clock supply to the sound generator
In the case this function is succeed, please set the return value of this function to DEVDRV_SUCCESS. The other value indicate an error and copy to the return value of R_SDG_Close() function.
In the sample code, uninitializing routine is described for channel 1 and 3, and an error routine is described for channel 0 and 2.

structures

typedef struct {
    UINT8_T TONE;		/* TONE VALUE ( 0 < TONE <= 127 )	*/
    UINT8_T SFS;		/* SFS VALUE ( 0 < SFS <= 255 )		*/
    UINT8_T LOUD;		/* LD VALUE ( 0 <= LD <= 255 )		*/
    UINT8_T ATTENUATION;	/* ATTENUATION VALUE			*/
} NOTE;

This structure specifies single tone.This structure is used in argument of R_SDG_Tone().

membermeaninghardware register
tonespecifies single toneTONE[6:0]
sfsreferrence frequencySFS[7:0]
loudstores the duty data for pulse output.LD[7:0]
attenuationTurns the attenuator function on and off, and select the attenuation cycleDPF[2:0]

enumerate

typedef enum {
    R_SDG_CLOCK_2  = 0,
    R_SDG_CLOCK_4  = 1,
    R_SDG_CLOCK_8  = 2,
    R_SDG_CLOCK_16 = 3,
} R_SDG_CLOCK;

Selects the operating clock.

enumereatemeaning
R_SDG_CLOCK_2P0φ/2
R_SDG_CLOCK_4P0φ/4
R_SDG_CLOCK_8P0φ/8
R_SDG_CLOCK_16P0φ/16


typedef enum {
    R_SDG_ATT_OFF = 0,
    R_SDG_ATT_1	  = 1,
    R_SDG_ATT_2	  = 2,
    R_SDG_ATT_4	  = 3,
    R_SDG_ATT_8	  = 4,
    R_SDG_ATT_16  = 5,
    R_SDG_ATT_32  = 6,
} R_SDG_ATTENUATION;

Turns the attenuator function on and off, and select the attenuation cycle.

enumeratemeaning
R_SDG_ATT_OFFAttenuator function is off.
R_SDG_ATT_1Attenuates at the TONE frequency
R_SDG_ATT_2Attenuates at the TONE frequency/2
R_SDG_ATT_4Attenuates at the TONE frequency/4
R_SDG_ATT_8Attenuates at the TONE frequency/8
R_SDG_ATT_16Attenuates at the TONE frequency/16
R_SDG_ATT_32Attenuates at the TONE frequency/32




サウンドジェネレータ

概要

RZ/A1Hに搭載されているサウンドジェネレータを使用するためのライブラリです。

API

Driver Wrapper API

下記に示すAPIはDriver APIをコールすることで楽曲再生機能を実現します。

void piano4int_start( const int8_t *scores[SDG_CH_TOTAL], PIANO4INT_CB callback )

概要楽曲再生開始関数
引数scores : SDG_CH_TOTALで指定されるチャネル数分の楽譜
callback : 同期指示関数
戻り値なし
解説楽曲の再生を開始します。
再生しないチャネルは、scores[ ]の該当する要素にNULLを設定します。
再生は、内部でもっているTickerオブジェクトに従って、すべて割り込みで行われます。
従って、この関数は初期化を終えると戻ってきます。
同期指示関数callbackは、楽曲データに埋め込まれた同期マーカを再生したとき、割り込みから呼び出されます。

void piano4int_stop( bool force )

概要楽曲再生停止関数
引数force : 強制停止フラグ(未実装)
戻り値なし
解説楽曲の再生を停止します。
この関数を呼び出すと、すべての楽曲を再生し終えた後、戻ってきます。
割り込みは使用しなくなりますが、オブジェクトの解放はしません。

bool piano4int_status( void )

概要楽曲再生状態取得関数
引数なし
戻り値再生状態
解説現在の再生の状況を取得します。
与えられた楽曲の一つでも再生中ならば、trueを返します。

typedef void (*PIANO4INT_CB)( uint32_t channel, uint32_t value )

概要同期提示関数
引数channel : チャネル番号
value : 同期マーカID
戻り値なし
解説楽曲データに組み込んだ同期マーカ付音符を再生するときに呼び出されるユーザ関数です。
valueは、同期マーカの次に書かれている1~2桁の数字を整数型にしたものです。
割り込みの中から呼ばれますので、処理は軽めにしてください。あまり長いと音がずれます。


Driver API

int32_t R_SDG_Open( uint32_t channel, R_SDG_CLOCK clock )

概要サウンドジェネレータ初期化関数
引数channel : チャネル番号 (0~3)
clock : 動作クロック
戻り値正常終了 : DEVDRV_SUCCESS
エラー終了 : DEVDRV_ERRORなど
解説チャネル番号で指定したサウンドジェネレータを初期化します。
動作クロックは、P0φ/2~P0φ/16から、今後使用するTONEやLOUDNESSに合わせて選択します。
サンプルコードでは、チャネル1及びチャネル3だけが使用できます。チャネル0及びチャネル2を指定した場合はエラー終了します。

int32_t R_SDG_Close( uint32_t channel )

概要サウンドジェネレータ終了関数
引数channel : チャネル番号 (0~3)
戻り値正常終了 : DEVDRV_SUCCESS
エラー終了 : DEVDRV_ERRORなど
解説指定したチャネルのサウンドジェネレータの使用を終了します。サンプルコードでは、クロックの供給も停止しますので、
再びR_SDG_Open( )で初期化するまで使用できなくなります。
R_SDG_Open( )を呼び出していないチャネルを指定した場合はエラー終了します。

int32_t R_SDG_Tone( uint32_t channel, NOTE *note )

概要単音作成関数
引数channel : チャネル番号 (0~3)
note : トーン設定パラメータ
戻り値正常終了 : DEVDRV_SUCCESS
エラー終了 : DEVDRV_ERRORなど
解説単音を出力します。音はnoteで指定します。
note->tone、note->sfs、R_SDG_Open( )で指定した動作クロックから、次の式で音の高さを決めます。

基準周波数 = 動作クロック/sfs
TONE周波数 = 基準周波数/( 2 × tone )

note->loudで音の大きさを指定します。loudは出力する音に合成する方形波のデューティ比で、
loud /256が方形波のHighの区間になります。
note->attenuationで減衰率を指定します。指定した周期ごとに、loudを31/32にすることで減衰します。
R_SDG_Open( )を呼び出していないチャネルを指定した場合はエラー終了します。

ユーザ定義関数

int32_t Userdef_SDG0_Open( void )

int32_t Userdef_SDG1_Open( void )

int32_t Userdef_SDG2_Open( void )

int32_t Userdef_SDG3_Open( void )

概要サウンドジェネレータ初期化ユーザ定義関数
引数なし
戻り値正常終了 : DEVDRV_SUCCESS
エラー終了 : その他
解説このドライバの利用者が作成する関数です。
R_SDG_Open( )から呼び出される関数で、4チャネル分の関数が必要です。
使用するサウンドジェネレータのサウンドジェネレータ初期化ユーザ定義関数では、
最低限、次のことを実施してください。

・サウンドジェネレータにクロックを供給します。
・サウンドジェネレータが使う出力ピンの設定をします。

また、正常に終了したとき、DEVDRV_SUCCESSを返してください。この値以外はエラーとみなし、
R_SDG_Open( )の戻り値になります。
サンプルコードでは、チャネル1及びチャネル3は初期化処理を行い、チャネル0及びチャネル2はエラーになります。

int32_t Userdef_SDG0_Close( void )

int32_t Userdef_SDG1_Close( void )

int32_t Userdef_SDG2_Close( void )

int32_t Userdef_SDG3_Close( void )

概要サウンドジェネレータ終了ユーザ定義関数
引数なし
戻り値正常終了 : DEVDRV_SUCCESS
エラー終了 : その他
解説このドライバの利用者が作成する関数です。
R_SDG_Close( )から呼び出される関数で、4チャネル分の関数が必要です。
これらの関数では、次のことを実施してください。

・サウンドジェネレータが使う出力ピンをGPIOに変更します。
・サウンドジェネレータへのクロックの供給を停止します。

また、正常に終了したとき、DEVDRV_SUCCESSを返してください。
この値以外はエラーとみなし、R_SDG_Close( )の戻り値になります。
サンプルコードでは、チャネル1及びチャネル3は終了処理を行い、チャネル0及びチャネル2はエラーになります。

構造体

typedef struct {
    UINT8_T TONE;		/* TONE VALUE ( 0 < TONE <= 127 )	*/
    UINT8_T SFS;		/* SFS VALUE ( 0 < SFS <= 255 )		*/
    UINT8_T LOUD;		/* LD VALUE ( 0 <= LD <= 255 )		*/
    UINT8_T ATTENUATION;	/* ATTENUATION VALUE			*/
} NOTE;

単音を表す構造体です。R_SDG_Tone( )の引数で使用します。意味と設定するビットを次に示します。

要素意味ビット名
tone音色を決める値ですTONE[6:0]
sfs基準周波数を決める値ですSFS[7:0]
loud出力パルスのデューティ比を決める値ですLD[7:0]
attenuation出力の減衰率を決める値ですDPF[2:0]

列挙型

typedef enum {
    R_SDG_CLOCK_2  = 0,
    R_SDG_CLOCK_4  = 1,
    R_SDG_CLOCK_8  = 2,
    R_SDG_CLOCK_16 = 3,
} R_SDG_CLOCK;

動作クロックを表す列挙型です。それぞれ、次の意味をもちます。

要素意味
R_SDG_CLOCK_2P0φ/2
R_SDG_CLOCK_4P0φ/4
R_SDG_CLOCK_8P0φ/8
R_SDG_CLOCK_16P0φ/16


typedef enum {
    R_SDG_ATT_OFF = 0,
    R_SDG_ATT_1	  = 1,
    R_SDG_ATT_2	  = 2,
    R_SDG_ATT_4	  = 3,
    R_SDG_ATT_8	  = 4,
    R_SDG_ATT_16  = 5,
    R_SDG_ATT_32  = 6,
} R_SDG_ATTENUATION;

減衰率を表す列挙型です。それぞれ、次の意味をもちます。

要素意味
R_SDG_ATT_OFF減衰しません
R_SDG_ATT_1TONE周波数で減衰します
R_SDG_ATT_2TONE周波数の1/2で減衰します
R_SDG_ATT_4TONE周波数の1/4で減衰します
R_SDG_ATT_8TONE周波数の1/8で減衰します
R_SDG_ATT_16TONE周波数の1/16で減衰します
R_SDG_ATT_32TONE周波数の1/32で減衰します

piano4int.cpp

Committer:
Osamu Nakamura
Date:
2017-04-24
Revision:
1:cd3d332d4499
Parent:
0:a3a1d4768307

File content as of revision 1:cd3d332d4499:

/******************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only
* intended for use with Renesas products. No other uses are authorized. This
* software is owned by Renesas Electronics Corporation and is protected under
* all applicable laws, including copyright laws.
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT
* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.
* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS
* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE
* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR
* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software
* and to discontinue the availability of this software. By using this software,
* you agree to the additional terms and conditions found by accessing the
* following link:
* http://www.renesas.com/disclaimer
* Copyright (C) 2012 - 2015 Renesas Electronics Corporation. All
* rights reserved.
******************************************************************************/

/******************************************************************************
Includes   <System Includes> , "Project Includes"
******************************************************************************/
#include <stdio.h>
#include <ctype.h>
#include <stdint.h>
extern "C" {
#include "iodefine.h"
#include "dev_drv.h"
#include "devdrv_sdg.h"
}
#include "mbed.h"
#include "PinNames.h"

#include "piano4int.h"

/******************************************************************************
Macro definitions
******************************************************************************/
#define ASSERT( eval )                          \
    if (!(eval)) {                              \
        printf(                                 \
            "%s: failed! at %d in %s\n",        \
            #eval,                              \
            __LINE__,                           \
            __FILE__);                          \
    }

/* message to caller */
#define     UNIT_MSG    (32)


/******************************************************************************
Typedef definitions
******************************************************************************/
/* a sound generator unit */
typedef struct {
    uint16_t        speed;          /* count of a tempo     */
    uint8_t         loudness;       /* current loudness     */
    uint16_t        count;          /* remain of time       */
    NOTE            note;           /* a next note          */
    const int8_t    *score;         /* a next score         */
    const int8_t    *top;           /* top of a score       */
    uint8_t         channel;        /* channel number       */
#ifdef UNIT_MSG
    char            msg[UNIT_MSG];  /* message              */
#endif
} UNIT;


/******************************************************************************
Imported global variables and functions (from other files)
******************************************************************************/


/******************************************************************************
Exported global variables and functions (to be accessed by other files)
******************************************************************************/


/******************************************************************************
Private global variables and functions
******************************************************************************/
/* interrupt routine */
static void play_score(void);


/* all work area for piano */
struct {
    UNIT            unit[SDG_CH_TOTAL];
    uint16_t        fin;
    Ticker          metronome;          /* base tempo */
    PIANO4INT_CB    callback;
} pianoT;


/* init params for sound generator */
static const struct {
    uint16_t    channel;
    R_SDG_CLOCK clock;
} unitHW[SDG_CH_TOTAL] = {
    {   DEVDRV_CH_0, R_SDG_CLOCK_4 },
    {   DEVDRV_CH_1, R_SDG_CLOCK_4 },
    {   DEVDRV_CH_2, R_SDG_CLOCK_4 },
    {   DEVDRV_CH_3, R_SDG_CLOCK_4 },
};


/* dummy entry of score (no sounds)*/
static const int8_t noscore[] = "";

/* parameters of a rest */
static const NOTE   rest4 = {
    0,  /* tone         */
    0,  /* sfs          */
    0,  /* loud         */
    0,  /* attenuation  */
};


/* table of notes */
static const struct {
    uint8_t     tone;
    uint8_t     sfs;
} note_timing[MAXOCTAVE][MAXNOTE] = {
    {   /* octave 0 */
        {   0,   0 },  /* -A  */
        {   0,   0 },  /* -A# */
        {   0,   0 },  /* -B  */
        { 124, 255 },  /* -C  */
        { 117, 255 },  /* -C# */
        { 111, 255 },  /* -D  */
        { 105, 255 },  /* -D# */
        {  99, 255 },  /* -E  */
        {  93, 255 },  /* -F  */
        {  88, 255 },  /* -F# */
        {  83, 255 },  /* -G  */
        {  78, 255 },  /* -G# */
        {   0,   0 },  /* -R  */
    },
    {   /* octave 1 */
        {  86, 220 },  /*  A  */
        {  81, 220 },  /*  A# */
        {  76, 220 },  /*  B  */
        {  72, 220 },  /*  C  */
        {  68, 220 },  /*  C# */
        {  64, 220 },  /*  D  */
        {  60, 220 },  /*  D# */
        {  57, 220 },  /*  E  */
        {  54, 220 },  /*  F  */
        {  51, 220 },  /*  F# */
        {  48, 220 },  /*  G  */
        {  45, 220 },  /*  G# */
        {   0,   0 },  /*  R  */
    },
    {   /* octave 2 */
        {  49, 190 },  /* +A  */
        {  47, 190 },  /* +A# */
        {  44, 190 },  /* +B  */
        {  41, 190 },  /* +C  */
        {  39, 190 },  /* +C# */
        {  37, 190 },  /* +D  */
        {  35, 190 },  /* +D# */
        {  33, 190 },  /* +E  */
        {  31, 190 },  /* +F  */
        {  29, 190 },  /* +F# */
        {  27, 190 },  /* +G  */
        {  26, 190 },  /* +G# */
        {   0,   0 },  /* +R  */
    },
    {   /* octave 3 */
        {  31, 150 },  /* *A  */
        {  29, 150 },  /* *A# */
        {  28, 150 },  /* *B  */
        {  26, 150 },  /* *C  */
        {  25, 150 },  /* *C# */
        {  23, 150 },  /* *D  */
        {  22, 150 },  /* *D# */
        {  21, 150 },  /* *E  */
        {  19, 150 },  /* *F  */
        {  18, 150 },  /* *F# */
        {  17, 150 },  /* *G  */
        {  16, 150 },  /* *G# */
        {   0,   0 },  /* *R  */
    },
};


/* name table of notes */
#ifdef UNIT_MSG
static const char *note_name[MAXNOTE] = {
    "A",
    "A#",
    "B",
    "C",
    "C#",
    "D",
    "D#",
    "E",
    "F",
    "F#",
    "G",
    "G#",
    "R",
};
#endif /*UNIT_MSG*/


/******************************************************************************
* Function Name: piano4int_start
* Description  : Play the score thru sound generator.
*              : This function receives the sound language,
*              : and plays specified sound language.
* Arguments    : const int8_t *scores  : score
*              : PIANO4INT_CB callback : callback function
* Return Value : none
******************************************************************************/
void piano4int_start(const int8_t *scores[SDG_CH_TOTAL], PIANO4INT_CB callback)
{
    const int8_t    *score;     /* pointer to score */
    uint16_t        speed;      /* sound speed */
    int32_t         ch;         /* channel no */
    int32_t         ret;        /* function result */

    /* prepare for playing the score */
    for (ch = 0; ch < SDG_CH_TOTAL; ch++) {
        if (scores[ch] == NULL) {
            /* score is not specified */
            pianoT.unit[ch].score = noscore;
            pianoT.unit[ch].top   = noscore;
        } else {
            /* prepare for playing a score */
            score = scores[ch];

            /* get the speed */
            speed = 0;
            while (isdigit(*score)) {
                speed = (speed * 10) + ((*score++) - '0');
            }
            if (0 == speed) {
                /* can not play the score */
                printf("speed[%d]:%d, can not play, there is no speed information.\n", (int)ch, speed);
                return;
            } else {
                printf("speed[%d]:%d\n", (int)ch, speed);
                /* calculate a base speed for ticker */
                pianoT.unit[ch].speed = BASESPEED / speed;

                /* default loudness (unsupported to change) */
                pianoT.unit[ch].loudness = DEFLOUDNESS;

                /* set top of a score */
                pianoT.unit[ch].top   = score;
                pianoT.unit[ch].score = score;

                /* play no sounds */
                pianoT.unit[ch].count = 0;

                /* rest4 */
                pianoT.unit[ch].note = rest4;

                /* channel number */
                pianoT.unit[ch].channel = unitHW[ch].channel;

#ifdef  UNIT_MSG
                /* message */
                pianoT.unit[ch].msg[0] = '\0';
#endif

                /* Initialize Sound Generator */
                ret = R_SDG_Open(unitHW[ch].channel, unitHW[ch].clock);
                ASSERT(0 == ret);
            }
        }
    }

    /* set callback function */
    pianoT.callback = callback;

    /* clear flags to finish playing */
    pianoT.fin = 0;

    /* start the metronome  (unit: 1ms) */
    pianoT.metronome.attach_us(&play_score, 1000.0);
}

/******************************************************************************
* Function Name: piano4int_stop
* Description  : Stop the sounds through sound generator.
* Arguments    : bool force : flag to stop forcedly (now, ignored)
* Return Value : none
******************************************************************************/
void piano4int_stop(bool force)
{
    int32_t         ch;
    int32_t         ret;

    /* wait until sounds stop */
    do {
        /* wait 10.0 sec */
        wait_us(10.0 * 1000.0);
#ifdef UNIT_MSG
        for (ch = 0; ch < SDG_CH_TOTAL; ch++) {
            if ('\0' != pianoT.unit[ch].msg[0]) {
                printf(&pianoT.unit[ch].msg[0]);
                pianoT.unit[ch].msg[0] = '\0';
            }
        }
#endif /*UNIT_MSG*/
    } while (pianoT.fin != ((1 << SDG_CH_TOTAL) - 1));
    /* all scores finished */

    /* stops the metronome */
    pianoT.metronome.detach();

    /* stop all sound generators */
    for (ch = 0; ch < SDG_CH_TOTAL; ch++) {
        if (pianoT.unit[ch].top != noscore) {
            /* stop sound generator */
            ret = R_SDG_Close(unitHW[ch].channel);
            ASSERT(0 == ret);
        }
    }
}

/******************************************************************************
* Function Name: piano4int_status
* Description  : Get the flag to finish playing the score
* Arguments    : none
* Return Value : The flag
* Note         : Output the comment if the macro "UNIT_MSG" is defined
******************************************************************************/
bool piano4int_status(void)
{
#ifdef UNIT_MSG
    int32_t ch;

    /* output the comments from interrupts */
    for (ch = 0; ch < SDG_CH_TOTAL; ch++) {
        if ('\0' != pianoT.unit[ch].msg[0]) {
            printf(&pianoT.unit[ch].msg[0]);
            pianoT.unit[ch].msg[0] = '\0';
        }
    }
#endif

    return (pianoT.fin != ((1 << SDG_CH_TOTAL) - 1));
}


/******************************************************************************
* Function Name: play_score
* Description  : Play the score on interrupt
* Arguments    : none
* Return Value : none
******************************************************************************/
void play_score(void)
{
    UNIT            *unit;
    const int8_t    *score;
    uint16_t        octave;
    uint16_t        key;
    uint16_t        pitch;
    uint16_t        dot;
    uint16_t        tie;
    uint8_t         loud;
    uint16_t        duration;
    uint16_t        value;
    uint16_t        ch;
    bool            err;

    for (ch = 0; ch < SDG_CH_TOTAL; ch++) {
        /* Check finish flag */
        if (0 != (pianoT.fin & (1 << ch))) {
            continue;   /* finish */
        }

        if (0 == pianoT.unit[ch].count) {
            unit    = &pianoT.unit[ch];
            score   = unit->score;

            if ('\0' == *score) {
                /* set finish flag */
                pianoT.fin |= (1 << ch);
                continue;
            }

            /* Initialize parameters */
            octave  = 0;
            key     = 0;
            pitch   = 0;
            dot     = 0;
            tie     = 0;
            err     = false;

            /* skip some spaces */
            while (' ' == *score) {
                score++;
            }

            /* octave */
            switch (*score) {
                case OCTAVE0_CHAR:  { octave = OCTAVE_LEVEL_0; score++; break; }
                case OCTAVE1_CHAR:  { octave = OCTAVE_LEVEL_1; score++; break; }
                case OCTAVE2_CHAR:  { octave = OCTAVE_LEVEL_2; score++; break; }
                case OCTAVE3_CHAR:  { octave = OCTAVE_LEVEL_3; score++; break; }
                default:            { octave = OCTAVE_LEVEL_1;          break; }
            }

            /* key */
            switch (toupper(*score)) {
                case NOTE_DO_CHAR:  { key = KEY_C; score++; break; }
                case NOTE_RE_CHAR:  { key = KEY_D; score++; break; }
                case NOTE_MI_CHAR:  { key = KEY_E; score++; break; }
                case NOTE_FA_CHAR:  { key = KEY_F; score++; break; }
                case NOTE_SO_CHAR:  { key = KEY_G; score++; break; }
                case NOTE_RA_CHAR:  { key = KEY_A; score++; break; }
                case NOTE_SI_CHAR:  { key = KEY_B; score++; break; }
                case NOTE_REST_CHAR:{ key = KEY_R; score++; break; }
                default:
                    err = true;
            }

            if (((KEY_A == key) && (OCTAVE_LEVEL_0 == octave)) ||
                ((KEY_B == key) && (OCTAVE_LEVEL_0 == octave))) {
                err = true;
            }

            /* sharp */
            if (NOTE_SHARP == (*score)) {
                if (KEY_R == key) {
                    err = true;
                } else {
                    key++;
                    score++;
                }
            }

            /* pitch */
            if (isdigit(*score)) {
                pitch = ((*score++) - '0');
                if (isdigit(*score)) {
                    pitch = (pitch * 10) + ((*score++) - '0');
                }
            } else {
                err = true;
            }

            /* dotted */
            if (NOTE_DOT == (*score)) {
                dot = DOTTED_NOTE;
                score++;
            } else {
                dot = NOT_DOTTED_NONE;
            }

            /* tie */
            if (NOTE_TIE == (*score)) {
                tie = TIED_NOTE;
                score++;
            } else {
                tie = NOT_TIED_NONE;
            }

            /* set score */
            unit->score = score;

#ifdef  UNIT_MSG
            snprintf(&unit->msg[0], UNIT_MSG - 1, "%d)%d%s%d -> %d/%d/%d\n",
                unit->channel,
                octave,
                note_name[key],
                pitch,
                note_timing[octave][key].tone,
                note_timing[octave][key].sfs,
                unit->speed / pitch);
#endif /* UNIT_MSG */

            if (!err) {
                /* set the sound volume */
                loud     = (0 == note_timing[octave][key].sfs) ? (0): (unit->loudness);
                /* set */
                duration = unit->speed / pitch;
                if (dot) {
                    duration += (duration >> 1);
                }

                /* set next note or rest */
                unit->note.tone         = note_timing[octave][key].tone;
                unit->note.sfs          = note_timing[octave][key].sfs;
                unit->note.loud         = loud;
                unit->note.attenuation  = tie;

                R_SDG_Tone(pianoT.unit[ch].channel, &pianoT.unit[ch].note);
                pianoT.unit[ch].count = duration;
            } else {
                pianoT.fin |= (1 << ch);
            }

            /* marker */
            if (NOTE_MARKER == (*score)) {
                score++;
                value = 0;
                if (isdigit(*score)) {
                    value = ((*score++) - '0');
                    if (isdigit(*score)) {
                        value = (value * 10) + ((*score++) - '0');
                    }
                }
                unit->score = score;

                if (NULL != pianoT.callback) {
                    pianoT.callback(pianoT.unit[ch].channel, value);
                }
            }
        } else {
            pianoT.unit[ch].count--;
        }
    }
}

/* End of File */