Author Topic: [SOLVED] Encoder affecting unrelated listening Socket  (Read 227 times)

Chris Oakley

  • Posts: 212
I've found a real oddity which I can't find any reasoning or documentation for. If you run this code which starts a socket listening and then also starts an encoder, from this point forward you can't close the listening socket.

Code: [Select]
        Dim backlog As Integer = 0
        listenSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Dim hostIP As IPAddress = Dns.Resolve(IPAddress.Any.ToString()).AddressList(0)
        Dim ep As IPEndPoint = New IPEndPoint(hostIP, 9000)
        listenSocket.Bind(ep)
        listenSocket.Listen(backlog)

        Bass.BASS_Init(0, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero) 'Set to no sound device
        Dim _Mixer As Integer = BassMix.BASS_Mixer_StreamCreate(44100, 2, BASSFlag.BASS_DEFAULT Or BASSFlag.BASS_MIXER_NONSTOP) 'Create a mixer
        Bass.BASS_ChannelPlay(_Mixer, False) 'Play mixer
        Dim _EncoderString As String = "ffmpeg.exe -loglevel -8 -f s16le -ac 2 -ar 44100 -i - -f adts -b:a 128k  -c:a aac -"
        Dim _EncoderContent As String = BassEnc.BASS_ENCODE_TYPE_AAC
        _Encoder = BassEnc.BASS_Encode_Start(_Mixer, _EncoderString, BASSEncode.BASS_ENCODE_NOHEAD Or BASSEncode.BASS_ENCODE_FP_16BIT Or BASSEncode.BASS_ENCODE_LIMIT, Nothing, IntPtr.Zero)

If you open up Performance Monitor and go to the network tab you can see on the listening port that port 9000 will be open, but if you then try to close the socket:

Code: [Select]
        listenSocket.Close()

It doesn't grey out and is still alive for connections, although those connections don't register and you can't send data to them. It's really odd.

If you try to close the socket and then close the encoder then it greys out in performance monitor as expected. I've tried the encoder using lame and ffmpeg, it's the same issue.

So what am I missing here? Why is the encoder having a hold over the socket?
« Last Edit: 10 Oct '22 - 20:15 by Chris Oakley »

Ian @ un4seen

  • Administrator
  • Posts: 24939
Re: Encoder affecting unrelated listening Socket
« Reply #1 on: 10 Oct '22 - 16:32 »
The issue there is that the socket handle is inherited by the launched encoder (ffmpeg.exe) process, so it then needs to be closed/released by both processes, which of course the encoder won't do (until terminated) because it knows nothing about the socket. To prevent that, you need to set your socket as uninheritable. I'm not sure if .Net has another way, but in plain Win32 that is done by setting HANDLE_FLAG_INHERIT to 0 on the socket via SetHandleInformation:

Code: [Select]
SetHandleInformation((HANDLE)socket, HANDLE_FLAG_INHERIT, 0);

Chris Oakley

  • Posts: 212
Re: Encoder affecting unrelated listening Socket
« Reply #2 on: 10 Oct '22 - 20:14 »
Thanks Ian, this did the trick. I wouldn't ever have figured that out.