Setting the position on a mixer channel

Started by kafffee,

kafffee

Hi :)

I am trying to set the position on a mixer channel like this, but I get ErrorCode "BASS_ERROR_POSITION". When I set the postion to 0L, it works though. This is my code:


MainModule.Mixer = BassMix.BASS_Mixer_StreamCreate(CInt(NativeASIODevSampleRate), MainModule.Song.NumberOfChannels, BASSFlag.BASS_MIXER_NONSTOP Or BASSFlag.BASS_STREAM_DECODE Or BASSFlag.BASS_SAMPLE_FLOAT)

Bass.BASS_ChannelSetAttribute(MainModule.Mixer, BASSAttribute.BASS_ATTRIB_BUFFER, 0.0F) ' disable playback buffering
Bass.BASS_ChannelSetSync(MainModule.Mixer, BASSSync.BASS_SYNC_POS, MainModule.TotalTrackLengthInBytes, MixerEndProcedure, IntPtr.Zero)

Recording.DummyHandle = Bass.BASS_StreamCreate(MainModule.Song.SampleRate, MainModule.Song.NumberOfChannels, BASSFlag.BASS_STREAM_DECODE Or BASSFlag.BASS_MIXER_END Or BASSFlag.BASS_SAMPLE_FLOAT, StreamProcedure, CType(Recording.RecPointer, IntPtr))

Bass.BASS_ChannelSetAttribute(Recording.DummyHandle, BASSAttribute.BASS_ATTRIB_BUFFER, 0.0F)
Bass.BASS_ChannelSetSync(MainModule.Mixer, BASSSync.BASS_SYNC_POS, Recording.StartOffsetInBytes, RecordingSetInProcedure, CType(Recording.DummyHandle, IntPtr))
Bass.BASS_ChannelSetSync(MainModule.Mixer, BASSSync.BASS_SYNC_POS, Recording.EndOffsetInBytes, RecordingSuspendProcedure, CType(Recording.DummyHandle, IntPtr))

Private Sub MixerEndCallback(handle As Integer, channel As Integer, data As Integer, user As IntPtr)
    Bass.BASS_StreamFree(MainModule.Mixer)
    MainModule.Mixer = 0
End Sub

Private Sub RecordingSetInCallback(handle As Integer, channel As Integer, data As Integer, user As IntPtr)
    Dim RecordingHandle = user.ToInt32
    BassMix.BASS_Mixer_StreamAddChannel(MainModule.Mixer, RecordingHandle, BASSFlag.BASS_DEFAULT Or BASSFlag.BASS_MIXER_CHAN_NORAMPIN)
End Sub

Private Sub RecordingSuspendCallback(handle As Integer, channel As Integer, data As Integer, user As IntPtr)
    Dim RecordingHandle = user.ToInt32
    BassMix.BASS_Mixer_ChannelRemove(RecordingHandle)
End Sub

Private Sub JumpToPos()
MainModule.TotalTrackLengthInBytes = 2 * (MainModule.Song.Tracks.SelectMany(Function(t) t.Recordings).Max(Function(r) r.EndOffsetInBytes))
'there is only one recording right now, so the mixer channel should end at twice the length of the recording
Bass.BASS_ChannelSetPosition(MainModule.Mixer, MainModule.TotalTrackLengthInBytes \ 2, BASSMode.BASS_POS_BYTE)
End Sub

In case that it's relevant (this is the callback of StreamProcedure; it's supposed to provide the audio data in relation to the playback position of MainModule.Mixer):

Private Function DummyProcedure(handle As Integer, buffer As IntPtr, length As Integer, user As IntPtr) As Integer
    Dim rec = CType(GCHandle.FromIntPtr(user).Target, Recording)
    If rec.SuperiorTrack.IsMuted Then Return 0

    ' 1. get current playback position
    Dim currentMixerBytePos As Long = Bass.BASS_ChannelGetPosition(MainModule.Mixer, BASSMode.BASS_POS_BYTE)

    ' 2. check if playback position is even whithin recording position
    If currentMixerBytePos < rec.StartOffsetInBytes OrElse currentMixerBytePos > rec.EndOffsetInBytes Then
        Return 0 'return silence
    End If

    ' 3. calculate relative cursor
    Dim relativeBytePos As Long = currentMixerBytePos - rec.StartOffsetInBytes
    Dim currentSampleIndex As Long = relativeBytePos \ 4

    ' 4. calculate available samples
    Dim totalSamples As Long = (rec.EndOffsetInBytes - rec.StartOffsetInBytes) \ 4

    ' 5. calculate how many samples are left from current position on
    Dim samplesRequested As Integer = length \ 4
    Dim samplesRemaining As Long = totalSamples - currentSampleIndex

    If samplesRemaining <= 0 Then Return 0

    ' limit samples to copy
    Dim samplesToCopy As Integer = CInt(Math.Min(CLng(samplesRequested), samplesRemaining))

    ' 6. copy audio data right from calculated index of the array
    Dim src = rec.SampleData
    Marshal.Copy(src, CInt(currentSampleIndex), buffer, samplesToCopy)

    Return samplesToCopy * 4
End Function

What am I doing wrong?

Ian @ un4seen

Unfortunately, it isn't possible to set the position of a mixer. What you need to do instead is set the position of the mixer's sources to where they would be at the target mix position. If the mixer is playing, it should be stopped before doing that and then reset (using either BASS_ChannelPlay with restart=true or BASS_ChannelSetPosition with pos=0) afterwards to clear its buffers.

kafffee

First of all, sry for this huge post, you might read the code after you have read the rest (normal text) of this post. The code is only there to support my questions that I asked :) :

Okay, I got it to work on Windows Audio the way you suggested. But how will I do it when using ASIO?

First questions:

Also: How will I set a synchronizer on a dummy stream that is also a mixer source channel? Because once the recording has been played beyond its end point (EndOffsetInBytes), and I set the timeline cursor to a position before the recording starts it will not restart when the timeline cursor reaches StartOffsetInBytes of the recording. Does a dummy stream handle somehow get invalid once it's been fully played back?

In order to fix this, I tried to re-init the recording in a BASS_SYNC_END callback, but it never gets called. Here is my complete code:

Private Sub RecEndCallback(ByVal handle As Integer, ByVal channel As Integer, ByVal data As Integer, ByVal user As IntPtr)
    InitRecording(Me, New RecordingStartEndChangedEventArgs(Me)) 're-intitialize recording
End Sub

Public Sub InitRecording(sender As Object, e As RecordingStartEndChangedEventArgs)
    If e.Rec IsNot Me Then Return

    MainModule.MVM.DAW.PrepareMixerForASIO() 'initializing ASIO

    BassMix.BASS_Mixer_ChannelRemove(DummyHandle)

    RecPointer = GCHandle.Alloc(Me, GCHandleType.Normal)  'will be used to pass the user data
    Dim flags = BASSFlag.BASS_STREAM_DECODE Or BASSFlag.BASS_MIXER_END Or BASSFlag.BASS_SAMPLE_FLOAT 'set the flags
    DummyHandle = Bass.BASS_StreamCreate(MainModule.Song.SampleRate, MainModule.Song.NumberOfChannels, flags, MainModule.MVM.DAW.StreamProcedure, CType(RecPointer, IntPtr))  'create a dummy stream; callback function of StreamProcedure is DummyProcedure (see below)
    Cursor = 0  'set the cursor whithin the recording/sample
    Dim StartPos As Long
    If ReArrangeAfterSetPos Then
        StartPos = 0
        ReArrangeAfterSetPos = False
    Else
        StartPos = StartOffsetInBytes - MainModule.RelativePos 'StartOffsetInBytes = beginning position of recording in the mixer timeline, also regarding left trim; RelativePos: will be set to actual position in the timeline of the mixer relative to the last RelativePos every time timeline position is being set
    End If
    If Not BassMix.BASS_Mixer_StreamAddChannelEx(MainModule.Mixer, DummyHandle, BASSFlag.BASS_DEFAULT Or BASSFlag.BASS_MIXER_CHAN_NORAMPIN, StartPos, LengthInBytes) Then MessageBox.Show("addchannelex Not succeeded!: " & Bass.BASS_ErrorGetCode.ToString)
    BassMix.BASS_Mixer_ChannelSetSync(DummyHandle, BASSSync.BASS_SYNC_END, 0, RecEndProc, IntPtr.Zero) 'callback function of RecEndProc is RecEndCallback (see below)

End Sub

When I set the postion, i.e. instead of setting the total position on the mixer, I am doing this now:

Public Sub SetSongPos(argPosInBytes As Long) Implements IMainModule.SetSongPos 'argPosInBytes: new (absolute) position

    Dim PosBeforeSet = Bass.BASS_ChannelGetPosition(Mixer, BASSMode.BASS_POS_BYTE) 'getting current position of mixer before changing anything
    Bass.BASS_ChannelStop(Mixer)
    Dim diff As Long = argPosInBytes - (PosBeforeSet + RelativePos) 'difference between new absolute position and absolute position of the mixer
    RelativePos = argPosInBytes 'in order to be able to set the position more than once I am using a position relative to the last setting of position

    For Each Track In Song.Tracks 'iterating thru each track in song
        For Each Recording In Track.Recordings 'iterating thru each recording on each traack
            If ((argPosInBytes) >= Recording.StartOffsetInBytes) And ((argPosInBytes) <= Recording.EndOffsetInBytes) Then 'if new position is whithin the "range" of the recording
                If Recording.DummyHandle = 0 Then
                    Recording.ReArrangeAfterSetPos = True  'is InitRecording called when Position changed? = True
                    Recording.InitRecording(Me, New RecordingStartEndChangedEventArgs(Recording))
                    Recording.Cursor = (argPosInBytes - Recording.StartOffsetInBytes) \ BytesPerFrame
                Else

                    Recording.Cursor = ((Recording.Cursor * BytesPerFrame) + diff) \ BytesPerFrame
                End If
            Else
                Recording.ReArrangeAfterSetPos = False
                Recording.InitRecording(Me, New RecordingStartEndChangedEventArgs(Recording))
            End If
        Next
    Next

    Bass.BASS_ChannelSetPosition(Mixer, 0.0)
    Bass.BASS_ChannelPlay(Mixer, False)

End Sub

In order for you to better understand what I'm trying to do this is the callback function of my DummyHandle stream:


Private Function DummyProcedure(handle As Integer,
                            buffer As IntPtr,
                            length As Integer,
                            user As IntPtr) As Integer

    Dim rec = CType(GCHandle.FromIntPtr(user).Target, Recording)

    ' muted or idle
    If rec.SuperiorTrack.IsMuted OrElse rec.LengthInBytes = 0 Then
        Return 0
        Dim zeroBuffer(length - 1) As Byte
        Marshal.Copy(zeroBuffer, 0, buffer, length)
        Return length
    End If

    ' number of frames in recording
    Dim totalFrames As Long = rec.LengthInBytes \ MainModule.BytesPerFrame
    '(rec.EndOffsetInBytes - rec.StartOffsetInBytes) \ bytesPerFrame

    ' requested amount of frames
    Dim framesRequested As Integer =
    length \ MainModule.BytesPerFrame

    ' remaining frames
    Dim framesRemaining As Long =
    totalFrames - rec.Cursor

    If framesRemaining <= 0 Then
        Return 0
    End If

    ' frames that are a
    Dim framesToCopy As Integer =
    CInt(Math.Min(CLng(framesRequested), framesRemaining))

    ' start index whithin Single() array
    Dim startFloatIndex As Long =
    (rec.TrimLeftInBytes \ 4) +
    rec.Cursor * MainModule.Song.NumberOfChannels

    If startFloatIndex < 0 OrElse startFloatIndex > (rec.LengthInBytes - 1) Then Return 0 'suspend playback when cursor outside range of recording

    ' amount of floats to be copied
    Dim floatsToCopy As Integer =
    framesToCopy * MainModule.Song.NumberOfChannels

    Marshal.Copy( 'copy audio data
    rec.SampleData,
    CInt(startFloatIndex),
    buffer,
    floatsToCopy)

    rec.Cursor += framesToCopy

    Return floatsToCopy * 4

 End Function

Last question:
Is there a better way to do this or am I on the right track?

Background: What I am trying to achieve is something like a DAW: I have different tracks with recordings (audio samples) on them. I want to set the position absolute to the song thar contains these tracks. Also, I want to set in the playback of these recordings when StartOffsetInBytes is reached und suspend it when EndOffsetInBytes of the recording is reached.

Ian @ un4seen

Quote from: kafffeeOkay, I got it to work on Windows Audio the way you suggested. But how will I do it when using ASIO?

It should work exactly the same, but you must to use BASS_ChannelSetPosition to reset the mixer (BASS_ChannelPlay isn't an option).

Quote from: kafffeeHow will I set a synchronizer on a dummy stream that is also a mixer source channel? Because once the recording has been played beyond its end point (EndOffsetInBytes), and I set the timeline cursor to a position before the recording starts it will not restart when the timeline cursor reaches StartOffsetInBytes of the recording. Does a dummy stream handle somehow get invalid once it's been fully played back?

If you're using the "dummy" stream to start/end playback of a recording and it isn't working well, then you could try BASS_Mixer_StreamAddChannelEx and its start/length parameters instead. Note that when you want to change the start/length parameters (eg. when seeking), you will need to remove the source (BASS_Mixer_ChannelRemove) before re-adding it with the new parameters.

kafffee

QuoteIt should work exactly the same, but you must to use BASS_ChannelSetPosition to reset the mixer (BASS_ChannelPlay isn't an option).

So after having stopped the mixer, I will only need to call BASS_ChannelSetPosition and it will restart playing back? No additional BASS_ASIO_Start?

_______________________________________


QuoteIf you're using the "dummy" stream to start/end playback of a recording and it isn't working well, then you could try BASS_Mixer_StreamAddChannelEx and its start/length parameters instead. Note that when you want to change the start/length parameters (eg. when seeking), you will need to remove the source (BASS_Mixer_ChannelRemove) before re-adding it with the new parameters.

Oh it is actually working well, I even combined it with BASS_Mixer_StreamAddChannelEx, because I thought it would save performance (when a recording does not call the callback all the time but only when it is actually up to start), even though it's more diffcult to implement. Does it?
The question was just: When a recording, that I added with BASS_Mixer_StreamAddChannelEx, does reach its "natural end", do I have to re-initialize it, i.e. will the dummy stream be "invalid" for some reason? Because it seems to be this way.
And if yes, that's why I asked, why does my BASS_MIXER_END callback not get called? I am trying to re-initialize after it has ended.
Please take a look at the code in my last post #2 in order to better understand.

Ian @ un4seen

Quote from: kafffeeSo after having stopped the mixer, I will only need to call BASS_ChannelSetPosition and it will restart playing back? No additional BASS_ASIO_Start?

Yes, once the mixer is reset (with BASS_ChannelSetPosition), the ASIO channel should continue playing it.

Quote from: kafffeeThe question was just: When a recording, that I added with BASS_Mixer_StreamAddChannelEx, does reach its "natural end", do I have to re-initialize it, i.e. will the dummy stream be "invalid" for some reason? Because it seems to be this way.
And if yes, that's why I asked, why does my BASS_MIXER_END callback not get called? I am trying to re-initialize after it has ended.

The natural end is when your STREAMPROC returns BASS_STREAMPROC_END. If it never does that then it'll never really end (it may stall instead).

When using BASS_Mixer_StreamAddChannelEx, remember to re-add the source to the mix (with updated parameters) when seeking, as in my last post.

kafffee

QuoteThe natural end is when your STREAMPROC returns BASS_STREAMPROC_END. If it never does that then it'll never really end (it may stall instead).

Used BASSSync.BASS_SYNC_STALL instead, but still it never gets called either.

I am trying to re-init the dummy handle, after it has ended. Do I even have to? Because it seems to me as if the dummy handle seems to be freed respectively invalid after it has reached its natural end.

QuoteWhen using BASS_Mixer_StreamAddChannelEx, remember to re-add the source to the mix (with updated parameters) when seeking, as in my last post.

When talking about "seeking", you mean when I change the position/start/end of the dummy in the timeline or when I actually set a new timeline position (which refers to the mixer position here)?

Ian @ un4seen

Quote from: kafffeeUsed BASSSync.BASS_SYNC_STALL instead, but still it never gets called either.

Did you set the BASS_SYNC_STALL sync via BASS_Mixer_ChannelSetSync? If not, try that. BASSmix rather than BASS is playing the source, so the sync needs to be set with BASSmix.

Quote from: kafffeeI am trying to re-init the dummy handle, after it has ended. Do I even have to? Because it seems to me as if the dummy handle seems to be freed respectively invalid after it has reached its natural end.

In the code you posted above, it doesn't look like it does ever end, ie. BASS_STREAMPROC_END is never returned by DummyProcedure. Are you freeing it elsewhere? If not, you can probably keep using it after resetting "rec.Cursor".

Quote from: kafffeeWhen talking about "seeking", you mean when I change the position/start/end of the dummy in the timeline or when I actually set a new timeline position (which refers to the mixer position here)?

I'm referring to the process of seeking to a position in the mix by setting the position of each source accordingly.