3

I have converted an Objective-C script to Swift for forming header of an AAC frame. However the code fails to run in the app and crashes with an EXC_BAD_ACCESS. Copying the code in to playground outputs what I expect with no errors. Not sure where to go with this, because it seems like it should work. I could always use the Objective-C version but that feels like going around the issue.

enter image description here

func adtsDataForPacketLength(packetLength: Int) -> NSData {
    let adtsLength = 7
    let profile = 2
    let freqIdx = 4
    let chanCfg = 1
    let fullLength = adtsLength + packetLength;

    var packet = [UInt8]()
    packet.append(UInt8(0xFF))
    packet.append(UInt8(0xF9))
    packet.append(UInt8(((profile-1)<<6) + (freqIdx<<2) + (chanCfg>>2)))
    packet.append(UInt8(((chanCfg&3)<<6) + (fullLength>>11)))
    packet.append(UInt8((fullLength&0x7FF) >> 3))
    packet.append(UInt8(((fullLength&7)<<5) + 0x1F))
    packet.append(0xFC)
    return NSData(bytes: packet, length: packet.count)
}
keji
  • 5,947
  • 3
  • 31
  • 47
  • I could not replicate the failure here, did you test run just this lines in a blank project to check it? – Ulysses Jan 31 '16 at 01:39
  • @UlyssesR I just did and I couldn't either – keji Jan 31 '16 at 01:43
  • From what I can tell it has to do with what thread I'm on. I've tested on the main thread and it worked fine. However when I ran it the AVAudio thread from a callback it failed. Also porting the method to Objective-C and running it from the same line worked – keji Jan 31 '16 at 01:48
  • Can you try breakpoint before the error, and step by step in to try to get more info? – Ulysses Jan 31 '16 at 01:55
  • @UlyssesR After stepping through it I can tell that the `UInt8` is getting created but the `append` method is what is failing – keji Jan 31 '16 at 02:08
  • it may sound ridiculous but as a last resource... can you try use insert at position, and see what happens. (another crazy idea, check the size of this UInt8 in this thread is this really 8bits...?) – Ulysses Jan 31 '16 at 02:15
  • @UlyssesR That doesn't sound too insane... I'll check it now – keji Jan 31 '16 at 02:23
  • @UlyssesR calling `sizeof` within the code causes the same crash. If I stop early and call `sizeof(UInt8)` in the debugger I get `1`. Also `insert:atIndex` crashed as well. – keji Jan 31 '16 at 02:30
  • Ok, last shot, as you have a static size, try to code it in one single line, and see if it works (you could use let in this case) : var packet = [UInt8(0xFF), UInt8(0xF9), UInt8(((profile-1)<<6) + (freqIdx<<2) + (chanCfg>>2)), UInt8(((chanCfg&3)<<6) + (fullLength>>11)), UInt8((fullLength&0x7FF) >> 3), UInt8(((fullLength&7)<<5) + 0x1F), 0xFC] – Ulysses Jan 31 '16 at 02:40
  • @UlyssesR actually sorry to say but that was the first thing I tried... – keji Jan 31 '16 at 02:41

0 Answers0