o
    OZh_                     @   s   d Z ddlZddlZddlZddlZddlmZ ejj	Z	ejj
Z
g dZddgZd&ddZdd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zdd ZG dd dZG dd dZdd Zdd ZG dd deZd d! Zd"d# Zd$d% ZdS )'a  pygame.midi
pygame module for interacting with midi input and output.

The midi module can send output to midi devices, and get input
from midi devices.  It can also list midi devices on the system.

Including real midi devices, and virtual ones.

It uses the portmidi library.  Is portable to which ever platforms
portmidi supports (currently windows, OSX, and linux).

This uses pyportmidi for now, but may use its own bindings at some
point in the future.  The pyportmidi bindings are included with pygame.

New in pygame 1.9.0.
    N)InputMIDIINMIDIOUTMidiExceptionOutput	get_countget_default_input_idget_default_output_idget_device_infoinitmidis2eventsquitget_inittimefrequency_to_midimidi_to_frequencymidi_to_ansi_noter   r   c                 C   s6   | d ur	| t _| S zt j W t jS  ty   Y dS w )NF)_module_initvalueAttributeError)state r   :/var/www/auris/lib/python3.10/site-packages/pygame/midi.pyr   <   s   r   c                   C   s(   t  st  t d tt dS dS )zinitialize the midi module
    pygame.midi.init(): return None

    Call the initialisation function before using the midi module.

    It is safe to call this more than once.
    TN)r   _pypmZ
Initializeatexitregisterr   r   r   r   r   r   J   s
   r   c                   C   s   t  rt  t d dS dS )zuninitialize the midi module
    pygame.midi.quit(): return None


    Called automatically atexit if you don't call it.

    It is safe to call this function more than once.
    FN)r   r   Z	Terminater   r   r   r   r   X   s   	r   c                   C   s   t  S )zreturns True if the midi module is currently initialized
    pygame.midi.get_init(): return bool

    Returns True if the pygame.midi module is currently initialized.

    New in pygame 1.9.5.
    )r   r   r   r   r   r   g   s   r   c                   C   s   t  stdd S )Nzpygame.midi not initialised.)r   RuntimeErrorr   r   r   r   _check_initr   s   r   c                   C      t   t S )zgets the number of devices.
    pygame.midi.get_count(): return num_devices


    Device ids range from 0 to get_count() -1
    )r   r   ZCountDevicesr   r   r   r   r   w   s   r   c                   C   r   )a  gets default input device number
    pygame.midi.get_default_input_id(): return default_id


    Return the default device ID or -1 if there are no devices.
    The result can be passed to the Input()/Output() class.

    On the PC, the user can specify a default device by
    setting an environment variable. For example, to use device #1.

        set PM_RECOMMENDED_INPUT_DEVICE=1

    The user should first determine the available device ID by using
    the supplied application "testin" or "testout".

    In general, the registry is a better place for this kind of info,
    and with USB devices that can come and go, using integers is not
    very reliable for device identification. Under Windows, if
    PM_RECOMMENDED_OUTPUT_DEVICE (or PM_RECOMMENDED_INPUT_DEVICE) is
    *NOT* found in the environment, then the default device is obtained
    by looking for a string in the registry under:
        HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Input_Device
    and HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Output_Device
    for a string. The number of the first device with a substring that
    matches the string exactly is returned. For example, if the string
    in the registry is "USB", and device 1 is named
    "In USB MidiSport 1x1", then that will be the default
    input because it contains the string "USB".

    In addition to the name, get_device_info() returns "interf", which
    is the interface name. (The "interface" is the underlying software
    system or API used by PortMidi to access devices. Examples are
    MMSystem, DirectX (not implemented), ALSA, OSS (not implemented), etc.)
    At present, the only Win32 interface is "MMSystem", the only Linux
    interface is "ALSA", and the only Max OS X interface is "CoreMIDI".
    To specify both the interface and the device name in the registry,
    separate the two with a comma and a space, e.g.:
        MMSystem, In USB MidiSport 1x1
    In this case, the string before the comma must be a substring of
    the "interf" string, and the string after the space must be a
    substring of the "name" name string in order to match the device.

    Note: in the current release, the default is simply the first device
    (the input or output device with the lowest PmDeviceID).
    )r   r   ZGetDefaultInputDeviceIDr   r   r   r   r         .r   c                   C   r   )a  gets default output device number
    pygame.midi.get_default_output_id(): return default_id


    Return the default device ID or -1 if there are no devices.
    The result can be passed to the Input()/Output() class.

    On the PC, the user can specify a default device by
    setting an environment variable. For example, to use device #1.

        set PM_RECOMMENDED_OUTPUT_DEVICE=1

    The user should first determine the available device ID by using
    the supplied application "testin" or "testout".

    In general, the registry is a better place for this kind of info,
    and with USB devices that can come and go, using integers is not
    very reliable for device identification. Under Windows, if
    PM_RECOMMENDED_OUTPUT_DEVICE (or PM_RECOMMENDED_INPUT_DEVICE) is
    *NOT* found in the environment, then the default device is obtained
    by looking for a string in the registry under:
        HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Input_Device
    and HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Output_Device
    for a string. The number of the first device with a substring that
    matches the string exactly is returned. For example, if the string
    in the registry is "USB", and device 1 is named
    "In USB MidiSport 1x1", then that will be the default
    input because it contains the string "USB".

    In addition to the name, get_device_info() returns "interf", which
    is the interface name. (The "interface" is the underlying software
    system or API used by PortMidi to access devices. Examples are
    MMSystem, DirectX (not implemented), ALSA, OSS (not implemented), etc.)
    At present, the only Win32 interface is "MMSystem", the only Linux
    interface is "ALSA", and the only Max OS X interface is "CoreMIDI".
    To specify both the interface and the device name in the registry,
    separate the two with a comma and a space, e.g.:
        MMSystem, In USB MidiSport 1x1
    In this case, the string before the comma must be a substring of
    the "interf" string, and the string after the space must be a
    substring of the "name" name string in order to match the device.

    Note: in the current release, the default is simply the first device
    (the input or output device with the lowest PmDeviceID).
    )r   r   ZGetDefaultOutputDeviceIDr   r   r   r   r	      r   r	   c                 C   s   t   t| S )aP  returns information about a midi device
    pygame.midi.get_device_info(an_id): return (interf, name,
                                                input, output,
                                                opened)

    interf - a byte string describing the device interface, eg b'ALSA'.
    name - a byte string for the name of the device, eg b'Midi Through Port-0'
    input - 0, or 1 if the device is an input device.
    output - 0, or 1 if the device is an output device.
    opened - 0, or 1 if the device is opened.

    If the id is out of range, the function returns None.
    )r   r   ZGetDeviceInfo)Zan_idr   r   r   r
      s   
r
   c                   @   s:   e Zd ZdZdddZdd Zdd Zd	d
 Zdd ZdS )r   zInput is used to get midi input from midi devices.
    Input(device_id)
    Input(device_id, buffer_size)

    buffer_size - the number of input events to be buffered waiting to
      be read using Input.read()
       c                 C   s   t   |dkrtdzt|}W n ty   td ty&   tdw |rV|\}}}}}|rLz	t||| _W n tyF   tdw || _dS |rRtdtdtd)	z
        The buffer_size specifies the number of input events to be buffered
        waiting to be read using Input.read().
        _Device id is -1, not a valid output id.  -1 usually means there were no default Output devices.an integer is required$long int too large to convert to intz<Device id given is not a valid input id, it is an output id.z(Device id given is not a valid input id. Device id invalid, out of range.N)	r   r   r
   	TypeErrorOverflowErrorr   r   _input	device_id)selfr)   buffer_sizeresult_is_input	is_outputr   r   r   __init__  s6   
zInput.__init__c                 C   s   | j d u r	tdd S )Nmidi not open.)r(   r   r*   r   r   r   _check_open*  s   
zInput._check_openc                 C   $   t   | jdur| j  d| _dS )zcloses a midi stream, flushing any pending buffers.
        Input.close(): return None

        PortMidi attempts to close open streams when the application
        exits -- this is particularly difficult under Windows.
        N)r   r(   Closer2   r   r   r   close.     


zInput.closec                 C   s   t   |   | j|S )a  reads num_events midi events from the buffer.
        Input.read(num_events): return midi_event_list

        Reads from the Input buffer and gives back midi events.
        [[[status,data1,data2,data3],timestamp],
         [[status,data1,data2,data3],timestamp],...]
        )r   r3   r(   ZRead)r*   Z
num_eventsr   r   r   read:  s   z
Input.readc                 C   sJ   t   |   | j }|tjkrdS |tjkrdS t|}t||f)zreturns true if there's data, or false if not.
        Input.poll(): return Bool

        raises a MidiException on error.
        TF)	r   r3   r(   ZPollr   TRUEFALSEZGetErrorTextr   )r*   r,   Zerr_textr   r   r   pollF  s   



z
Input.pollN)r    )	__name__
__module____qualname____doc__r0   r3   r6   r8   r;   r   r   r   r   r      s    
)c                   @   st   e Zd ZdZdddZdd Zdd	 Zd
d Zdd ZdddZ	dd Z
dddZdddZdddZdddZdS )r   a  Output is used to send midi to an output device
    Output(device_id)
    Output(device_id, latency = 0)
    Output(device_id, buffer_size = 4096)
    Output(device_id, latency, buffer_size)

    The buffer_size specifies the number of output events to be
    buffered waiting for output.  (In some cases -- see below --
    PortMidi does not buffer output at all and merely passes data
    to a lower-level API, in which case buffersize is ignored.)

    latency is the delay in milliseconds applied to timestamps to determine
    when the output should actually occur. (If latency is < 0, 0 is
    assumed.)

    If latency is zero, timestamps are ignored and all output is delivered
    immediately. If latency is greater than zero, output is delayed until
    the message timestamp plus the latency. (NOTE: time is measured
    relative to the time source indicated by time_proc. Timestamps are
    absolute, not relative delays or offsets.) In some cases, PortMidi
    can obtain better timing than your application by passing timestamps
    along to the device driver or hardware. Latency may also help you
    to synchronize midi data to audio data by matching midi latency to
    the audio buffer latency.

    r      c                 C   s   t   d| _|dkrtdzt|}W n ty   td ty)   tdw |rZ|\}}}}}|rPz
t|||| _W n tyJ   tdw || _	d	S |rVtdtdtd)
a  Output(device_id)
        Output(device_id, latency = 0)
        Output(device_id, buffer_size = 4096)
        Output(device_id, latency, buffer_size)

        The buffer_size specifies the number of output events to be
        buffered waiting for output.  (In some cases -- see below --
        PortMidi does not buffer output at all and merely passes data
        to a lower-level API, in which case buffersize is ignored.)

        latency is the delay in milliseconds applied to timestamps to determine
        when the output should actually occur. (If latency is < 0, 0 is
        assumed.)

        If latency is zero, timestamps are ignored and all output is delivered
        immediately. If latency is greater than zero, output is delayed until
        the message timestamp plus the latency. (NOTE: time is measured
        relative to the time source indicated by time_proc. Timestamps are
        absolute, not relative delays or offsets.) In some cases, PortMidi
        can obtain better timing than your application by passing timestamps
        along to the device driver or hardware. Latency may also help you
        to synchronize midi data to audio data by matching midi latency to
        the audio buffer latency.
        r   r!   r"   r#   r$   z<Device id given is not a valid output id, it is an input id.z)Device id given is not a valid output id.r%   N)
r   _abortedr   r
   r&   r'   r   r   _outputr)   )r*   r)   Zlatencyr+   r,   r-   r.   r/   r   r   r   r0   v  s8   
zOutput.__init__c                 C   s$   | j d u r	td| jrtdd S )Nr1   zmidi aborted.)rB   r   rA   r2   r   r   r   r3     s
   
zOutput._check_openc                 C   r4   )zcloses a midi stream, flushing any pending buffers.
        Output.close(): return None

        PortMidi attempts to close open streams when the application
        exits -- this is particularly difficult under Windows.
        N)r   rB   r5   r2   r   r   r   r6     r7   zOutput.closec                 C   s    t   | jr| j  d| _dS )au  terminates outgoing messages immediately
        Output.abort(): return None

        The caller should immediately close the output port;
        this call may result in transmission of a partial midi message.
        There is no abort for Midi input because the user can simply
        ignore messages in the buffer and close an input device at
        any time.
           N)r   rB   ZAbortrA   r2   r   r   r   abort  s   

zOutput.abortc                 C   s   t   |   | j| dS )a  writes a list of midi data to the Output
        Output.write(data)

        writes series of MIDI information in the form of a list:
             write([[[status <,data1><,data2><,data3>],timestamp],
                    [[status <,data1><,data2><,data3>],timestamp],...])
        <data> fields are optional
        example: choose program change 1 at time 20000 and
        send note 65 with velocity 100 500 ms later.
             write([[[0xc0,0,0],20000],[[0x90,60,100],20500]])
        notes:
          1. timestamps will be ignored if latency = 0.
          2. To get a note to play immediately, send MIDI info with
             timestamp read from function Time.
          3. understanding optional data fields:
               write([[[0xc0,0,0],20000]]) is equivalent to
               write([[[0xc0],20000]])

        Can send up to 1024 elements in your data list, otherwise an
         IndexError exception is raised.
        N)r   r3   rB   ZWrite)r*   datar   r   r   write  s   zOutput.writec                 C   s"   t   |   | j||| dS )a  write_short(status <, data1><, data2>)
        Output.write_short(status)
        Output.write_short(status, data1 = 0, data2 = 0)

        output MIDI information of 3 bytes or less.
        data fields are optional
        status byte could be:
             0xc0 = program change
             0x90 = note on
             etc.
             data bytes are optional and assumed 0 if omitted
        example: note 65 on with velocity 100
             write_short(0x90,65,100)
        N)r   r3   rB   Z
WriteShort)r*   statusdata1data2r   r   r   write_short  s   zOutput.write_shortc                 C   s    t   |   | j|| dS )a  writes a timestamped system-exclusive midi message.
        Output.write_sys_ex(when, msg)

        msg - can be a *list* or a *string*
        when - a timestamp in milliseconds
        example:
          (assuming o is an onput MIDI stream)
            o.write_sys_ex(0,'\xF0\x7D\x10\x11\x12\x13\xF7')
          is equivalent to
            o.write_sys_ex(pygame.midi.time(),
                           [0xF0,0x7D,0x10,0x11,0x12,0x13,0xF7])
        N)r   r3   rB   Z
WriteSysEx)r*   whenmsgr   r   r   write_sys_ex  s   zOutput.write_sys_exc                 C   :   d|  krdkst d t d| d| || dS )aU  turns a midi note on.  Note must be off.
        Output.note_on(note, velocity, channel=0)

        note is an integer from 0 to 127
        velocity is an integer from 0 to 127
        channel is an integer from 0 to 15

        Turn a note on in the output stream.  The note must already
        be off for this to work correctly.
        r      Channel not between 0 and 15.   N
ValueErrorrJ   r*   Znotevelocitychannelr   r   r   note_on  
   zOutput.note_onc                 C   rN   )ak  turns a midi note off.  Note must be on.
        Output.note_off(note, velocity=0, channel=0)

        note is an integer from 0 to 127
        velocity is an integer from 0 to 127 (release velocity)
        channel is an integer from 0 to 15

        Turn a note off in the output stream.  The note must already
        be on for this to work correctly.
        r   rO   rP      NrR   rT   r   r   r   note_off'  rX   zOutput.note_offc                 C   s\   d|  kr
dksn t d| d|  krdks$t d t d| d| | dS )zselect an instrument for a channel, with a value between 0 and 127
        Output.set_instrument(instrument_id, channel=0)

        Also called "patch change" or "program change".
        r      zUndefined instrument id: rO   rP      NrR   )r*   Zinstrument_idrV   r   r   r   set_instrument7  s   zOutput.set_instrumentc                 C   sx   d|  krdkst d t dd|  krdks%n t d| d|d }|d	@ }|d
? }| d| || dS )a  modify the pitch of a channel.
        Output.pitch_bend(value=0, channel=0)

        Adjust the pitch of a channel.  The value is a signed integer
        from -8192 to +8191.  For example, 0 means "no change", +4096 is
        typically a semitone higher, and -8192 is 1 whole tone lower (though
        the musical range corresponding to the pitch bend range can also be
        changed in some synthesizers).

        If no value is given, the pitch bend is returned to "no change".
        r   rO   rP   i i  z6Pitch bend value must be between -8192 and +8191, not .i    r[         NrR   )r*   r   rV   ZlsbZmsbr   r   r   
pitch_bendE  s   
zOutput.pitch_bendN)r   r@   )r   r   )r   )r<   r=   r>   r?   r0   r3   r6   rD   rF   rJ   rM   rW   rZ   r]   ra   r   r   r   r   r   Z  s    
?



c                   C   r   )zreturns the current time in ms of the PortMidi timer
    pygame.midi.time(): return time

    The time is reset to 0, when the module is inited.
    )r   r   ZTimer   r   r   r   r   n  s   r   c           
   
   C   sF   g }| D ]}|\\}}}}}t jjt||||||d}	||	 q|S )zconverts midi events to pygame events
    pygame.midi.midis2events(midis, device_id): return [Event, ...]

    Takes a sequence of midi events and returns list of pygame events.
    )rG   rH   rI   data3	timestampZvice_id)pygameeventEventr   append)
Zmidisr)   ZevsZmidirG   rH   rI   rb   rc   re   r   r   r   r   x  s   	r   c                       s(   e Zd ZdZ fddZdd Z  ZS )r   zXexception that pygame.midi functions and classes can raise
    MidiException(errno)
    c                    s   t  | || _d S N)superr0   	parameter)r*   r   	__class__r   r   r0     s   
zMidiException.__init__c                 C   s
   t | jS rh   )reprrj   r2   r   r   r   __str__  s   
zMidiException.__str__)r<   r=   r>   r?   r0   rn   __classcell__r   r   rk   r   r     s    r   c                 C   s(   t tddt| d  td  S )zconverts a frequency into a MIDI note.

    Rounds to the closest midi note.

    ::Examples::

    >>> frequency_to_midi(27.5)
    21
    >>> frequency_to_midi(36.7)
    26
    >>> frequency_to_midi(4186.0)
    108
    E           {@   )introundmathlog)Z	frequencyr   r   r   r     s   (r   c                 C   s   t dd| d d   dS )zConverts a midi note to a frequency.

    ::Examples::

    >>> midi_to_frequency(21)
    27.5
    >>> midi_to_frequency(26)
    36.7
    >>> midi_to_frequency(108)
    4186.0
    rr   rs   rp   gUUUUUU?rC   )ru   )	midi_noter   r   r   r     s   r   c                 C   s8   g d}d}|t | d |  }| d | }| | S )zreturns the Ansi Note name for a midi number.

    ::Examples::

    >>> midi_to_ansi_note(21)
    'A0'
    >>> midi_to_ansi_note(102)
    'F#7'
    >>> midi_to_ansi_note(108)
    'C8'
    )AzA#BCzC#DzD#EFzF#GzG#rq      )rt   )rx   notesZ	num_notesZ	note_nameZnote_numberr   r   r   r     s
   r   rh   )r?   rv   r   rd   Zpygame.localsZpygame.pypmZpypmr   localsr   r   __all__Z__theclasses__r   r   r   r   r   r   r   r	   r
   r   r   r   r   	Exceptionr   r   r   r   r   r   r   r   <module>   s:    
22b  
