HaishinKit.swift icon indicating copy to clipboard operation
HaishinKit.swift copied to clipboard

Audio issue while transmitting. WebRTC. 4 channels

Open CedricEugeni opened this issue 1 year ago • 27 comments

Describe the bug

Hi,

On some devices, there is a strange audio behavior seems like audio is cutting in and out quickly. I could reproduce it on iPhone 12 Pro on iOS 16.xx and iPhone 14 Pro on iOS 16.xx and 17.0 beta.

Maybe this is a duplicate from this issue : https://github.com/shogo4405/HaishinKit.swift/issues/1208

But I read the thread and a PR in late July should've fixed this.

I made a view to add some technical information. Chart is representing numSamples in AudioCode.swift file in public func appendSampleBuffer(_ sampleBuffer: CMSampleBuffer, offset: Int = 0) method.

You can see on iPhone 13 mini that I either have a steady 1024 numSamples value or something that bounce between 2 values like for example 955 & 69 (my example makes the sum of it 1024 but I'm not sure that's the case). You can also see on the iPhone 14, chart is kinda crazy and not looking as steady as the iPhone 13 min.

(On these screenshots, other info is coming from the same place where numSamples values come from, where I display the inSourceFormat information.)

To Reproduce

Start a RTMPStream for the first time, wait for mic authorization request, then accept it and record. I reproduce it doing this on iPhone 12 Pro. On iPhone 14 Pro, it happens every time.

Expected behavior

Audio should be fine.

Version

latest from main branch

Smartphone info.

  • iPhone 12 Pro / iOS 16.6.1
  • iPhone 14 Pro / iOS 16 (all minor versions) - iOS 17 beta

Additional context

I have a WebRTC connection to display the user what is being streamed online (RTMP stream is sent to the cloud to render a streaming scene, then WebRTC feed shows the user this streaming rendering that can be broadcasted on Twitch and everything afterwards)

WebRTC connection tends to change AudioSession, so I made sure to attachAudio on my RTMPStream only after WebRTC connection is done playing with audio session to try to avoid issues.

Screenshots

iPhone 13 mini iPhone 13 mini 2 iPhone 14 pro

Relevant log output

No response

CedricEugeni avatar Sep 08 '23 09:09 CedricEugeni

The fix made in #1208 was for the case of 2-channel stereo. It might not work correctly for 3 channels or more. It seems like the iPhone 14 Pro is detecting 4 channels.

shogo4405 avatar Sep 08 '23 11:09 shogo4405

Thanks for your reply @shogo4405 😊

I tried to force the AVAudioSession preferredIntputChannels to 1 or 2 using the setPreferredIntputChannels. While it seems to work on my iPhone 13mini, it seems it doesn't work on iPhone 14.

So if I have to deal with 4-channels samples. what would be the best way to deal with it inside Haishinkit from your point of view ? Would I need to "remove" 2 channels from the CMSAmpleBuffer and then give it to the actual Haishinkit code to make it work or have you another idea about something that would make it work ? 🤔

CedricEugeni avatar Sep 08 '23 15:09 CedricEugeni

I have no idea. We have recently added support for multi-channels in #1273 and #1280. I have also tested it and it seems to work fine with 4 channels.

shogo4405 avatar Sep 08 '23 22:09 shogo4405

You can try to discard channels within HK by providing a channel map. Negative value is used to discard an input channel:

myStream.audioSettings.outputChannelsMap = [0: 0, 1: 1, 2: -1, 3: -1]

leo150 avatar Sep 19 '23 16:09 leo150

Also the format descriptions that show on the screenshots look like "input" audio format. HK does conversion from PCM to compressed AAC format. The "output" format can be found in AudioCodecSettings. There's hardcoded maximum number of output channels which is 2. Any extra channels are removed, say you convert from 4 to 2 channels, channels 3 and 4 will be removed.

leo150 avatar Sep 19 '23 16:09 leo150

I've made significant changes to the internal audio processing in https://github.com/shogo4405/HaishinKit.swift/pull/1294. There's a possibility that it brings improvements. You can test it on the 'main' branch.

shogo4405 avatar Sep 19 '23 23:09 shogo4405

I'm currently testing it and will tell you if there is improvements or not. If this does not improve things, I'll take a look and try some things about what @leo150 said earlier to see if it helps. Thanks for your replies

CedricEugeni avatar Sep 22 '23 04:09 CedricEugeni

Hi,

I took some time to make several tests and waited for the iPhone 15 Pro release to confirm what I thought. My issue is also happening on the iPhone 15 Pro.

As @leo150 mentioned, I tried to set audioSettings as below:

stream.audioSettings.bitRate = <info given by my backend>
stream.audioSettings.channels = 1
stream.audioSettings.channelMap = [0: 0, 1: 0, 2: -1, 3: -1]

But it seems it doesn't have any effect on the audio.

I also tried to update the library to use the latest code but it also doesn't seem to change anything.

One piece of info I may provide you is that my AVAudioSession is using playAndRecord category & videoChat mode because I have possible audio feedback on speaker and I want echo canceling/voice processing.

If I'm using AirPods or so, I use default mode and it works as expected, but as soon as my AVAudioSession change, sound is behaving in this weird way.

I also tried, when AVAudioSession change, to detach audio from rtmpStream and then reattach it, thinking that maybe it'd get new settings from incoming audio and set things up in a different way that'd be able to handle audio. But it doesn't work either.

Are all of these info giving you any piece of idea or advice for me ?

CedricEugeni avatar Sep 27 '23 12:09 CedricEugeni

@shogo4405 @leo150 @CedricEugeni unfortunately we're facing the very same issue. What we've found is that the crackling sound is due to recurring silences or missing samples in the audio. Here are Audacity screenshots :

missing_samples

Here you can see the recurring silences or missing samples.

missing_frame_with_samples

What we've found is that there's exactly 1024 samples between each recurring silences or missing samples. Therefore we concluded they are either at the beginning or at the end of each audio frame.

We've tried to dig into the resampler and ring buffer but we couldn't find anything that would help us determine where this could come from.

Do the screenshots and/or explanation make you think of anything ? Any help would be greatly appreciated 👍

Cheers Quentin

asticode avatar Sep 29 '23 14:09 asticode

  1. Fork this code and provide logs of the print results showing the occurring symptoms. A log of about 30 seconds should be sufficient.
  2. If possible, please provide a simple code snippet for reproduction along with server access details. You can share the reproduction code via a pull request, and the server credentials can be sent via email.

shogo4405 avatar Sep 29 '23 16:09 shogo4405

  1. We've managed to pin point what is causing the issue : when dealing with WebRTC and 4 channels, CMSampleBuffers sent by the AVCaptureSession sometimes start with 256 "padding/dummy" samples equal to 0 (it happens when the buffer number of samples > 960, there's no problem when the number of samples is exactly 960), the rest of the buffer being fine (here is an example). It leads to 64 silence samples being added per channel, which is exactly the length of silence observed in Audacity.

Unfortunately there doesn't seem to be any information in the CMSampleBuffer informing its user that there's padding to be skipped at the start of the buffer 😱

Do you have any thought on that? Or any idea on how we could go about fixing this issue?

  1. It's not easy to provide reproducible steps, but we'll try it when we exhaust all other possibilities 👍

asticode avatar Sep 29 '23 16:09 asticode

Fork this code and provide logs of the print results showing the occurring symptoms. A log of about 30 seconds should be sufficient.

Code is here. https://github.com/shogo4405/HaishinKit.swift/tree/feature/print-samplebuffer

I'm not interested in the byte sequence of the CMSampleBuffer. I want to know the PTS (Presentation Time Stamp). Please provide the dump result.

shogo4405 avatar Sep 29 '23 16:09 shogo4405

Fork this code and provide logs of the print results showing the occurring symptoms. A log of about 30 seconds should be sufficient.

Code is here. https://github.com/shogo4405/HaishinKit.swift/tree/feature/print-samplebuffer

I'm not interested in the byte sequence of the CMSampleBuffer. I want to know the PTS (Presentation Time Stamp). Please provide the dump result.

Here's our dump. I had to add a ".zip" extension so that Github let me upload it.

Dump_haishinkit.zip

Is it what you were looking for?

asticode avatar Oct 01 '23 10:10 asticode

There is a difference between the PTS (Presentation Time Stamp) calculated theoretically and the PTS received in practice. I believe this difference is manifesting as silence. スクリーンショット 2023-10-03 1 46 47

shogo4405 avatar Oct 02 '23 17:10 shogo4405

Thanks for clearing that out 👍

Is there anything this lib or we could do to fix the issue? 🤔

asticode avatar Oct 03 '23 07:10 asticode

Maybe this fix could have improved it. If you don't mind, I would like to ask you to test it. https://github.com/shogo4405/HaishinKit.swift/pull/1310

shogo4405 avatar Oct 03 '23 11:10 shogo4405

First off, thanks for providing a fix to test ❤️

Here's how it went: we had 2 problems

  • a crackling sound
  • audio was getting late compared to video which resulted in linear desynchronization between audio and video

Your patch fixed the second problem but not the first one.

Therefore I think it would be a good idea to merge it, but we still have an issue with the crackling sound.

asticode avatar Oct 04 '23 14:10 asticode

I confirmed that the issue can be reproduced when launching Example.app while having a Discord call. As indicated by 'Offset 128,' I confirmed that there is a corresponding gap in that area. It seems like using this value should work well.

CMBlockBuffer 0x282eea880 totalDataLength: 7680 retainCount: 1 allocator: 0x1e753bb30 subBlockCapacity: 2
 [0] 7680 bytes @ offset 128 Buffer Reference:
    CMBlockBuffer 0x282eea910 totalDataLength: 7832 retainCount: 1 allocator: 0x1e753bb30 subBlockCapacity: 2
     [0] 7832 bytes @ offset 0 Memory Block 0x116782240, 7832 bytes (allocator 0x2827f2700)
}

shogo4405 avatar Oct 06 '23 12:10 shogo4405

That looks pretty good indeed! Let us know whether you need any help testing a fix 👍

asticode avatar Oct 06 '23 12:10 asticode

It's being discussed on the developer forum. https://developer.apple.com/forums/thread/715177

It seems like there is blank data at the beginning like this, which can disrupt calculations such as PTS (Presentation Time Stamp). When I remove the blank data, it sounds correct.

▫️▫️▫️▫️▪️▪️▪️▪️▪️
▫️▫️▫️▫️▪️▪️▪️▪️▪️
▪️▪️▪️▪️▪️▪️▪️▪️▪️
▫️▫️▫️▫️▪️▪️▪️▪️▪️
▫️▫️▫️▫️▪️▪️▪️▪️▪️
▪️▪️▪️▪️▪️▪️▪️▪️▪️
▫️▫️▫️▫️▪️▪️▪️▪️▪️
▫️▫️▫️▫️▪️▪️▪️▪️▪️
▪️▪️▪️▪️▪️▪️▪️▪️▪️

shogo4405 avatar Oct 07 '23 08:10 shogo4405

Did you manage to find a way to automatically remove that annoying blank data based on the CMBlockBuffer information (like the offset you mentioned earlier) or are you missing information?

asticode avatar Oct 09 '23 06:10 asticode

I haven't found a way to retrieve it from the parameters.

shogo4405 avatar Oct 09 '23 11:10 shogo4405

@shogo4405 what are you looking to do regarding this issue? We're still experiencing crackling noise.

Cheers

asticode avatar Oct 17 '23 12:10 asticode

Are you saying that it's still occurring in the post-fix branch at https://github.com/shogo4405/HaishinKit.swift/pull/1310/files? If so, I won't be able to fix it because I can't reproduce it in my environment.

shogo4405 avatar Oct 17 '23 12:10 shogo4405

With your post-fix branch, we're experiencing:

  • way less crackling noise but still random ones every 1 or 2 seconds. they are far more difficult to hear but they are there
  • if we record for a few minutes, we see that audio/video get unsynchronized (video is late compared to audio)

Random crackling noises may be due to audio/video getting unsynchronized 🤔

asticode avatar Oct 17 '23 12:10 asticode

The direction of the modifications seems promising. I believe that with extensive debugging, improvements can be achieved. On the other hand, I'm currently allocating my time for the 1.7.0 release, so the subsequent fixes will have to wait.

shogo4405 avatar Oct 17 '23 12:10 shogo4405

OK thanks for the clarifications 👍 we're available if you need help to debug or test improvements whenever you go back to that issue. Thanks again ❤️

asticode avatar Oct 17 '23 12:10 asticode

As a temporary solution, I disabled voice processing in voice_processing_audio_unit.mm:76 and the issue is gone. In our case the voice processing isn't a requirement.

vpio_unit_description.componentSubType = kAudioUnitSubType_RemoteIO;

I don't have time to create a reproducible example, but ideally we need to add a voice processing unit to the HaishinKit example app so the issue could looked into.

levs42 avatar May 23 '24 00:05 levs42

You can reproduce the issue by starting the HaishinKit sample app while on a call in Discord. Since I don't have a good improvement plan at the moment, I will move this to the Discussion section for now.

shogo4405 avatar May 30 '24 10:05 shogo4405