2013-05-07 37 views
24

Tôi đang chạy ứng dụng phát trực tuyến âm thanh SIP trên iOS 6.1.3 iPad2 và iPad mới.Ứng dụng iOS bị treo khi tai nghe được cắm vào hoặc rút phích cắm

Tôi bắt đầu ứng dụng của mình trên iPad (không có gì được cắm vào).
Hoạt động âm thanh.
Tôi cắm tai nghe.
Các treo ứng dụng: malloc: lỗi cho 0x đối tượng ....: con trỏ được trả tự do đã không được phân bổ hoặc EXC_BAD_ACCESS

Hoặc:

tôi bắt đầu ứng dụng của tôi trên iPad của tôi (với tai nghe cắm vào).
Âm thanh xuất phát từ tai nghe.
Tôi rút phích cắm tai nghe ra.
Các treo ứng dụng: malloc: lỗi cho 0x đối tượng ....: con trỏ được trả tự do đã không được phân bổ hoặc EXC_BAD_ACCESS

Các mã ứng dụng sử dụng AudioUnit api dựa trên http://code.google.com/p/ios-coreaudio-example/ mẫu mã (xem dưới đây).

Tôi sử dụng cuộc gọi lại kAudioSessionProperty_AudioRouteChange để nhận nhận thức thay đổi. Vì vậy, có ba callbacks fro người quản lý âm thanh Hệ điều hành:
1) Quy trình ghi mẫu mic
2) Cung cấp mẫu cho loa
3) Thông báo cho âm thanh HW hiện diện

Sau rất nhiều thử nghiệm cảm giác của tôi là khó khăn là mã thực hiện ghi micrô. Sau khi hành động cắm/rút phích cắm, phần lớn thời gian ghi âm cuộc gọi đang được gọi một vài lần trước khi RouteChange được gọi là gây ra 'lỗi phân đoạn' sau này và gọi lại RouteChange không bao giờ được gọi. Cụ thể hơn, tôi nghĩ rằng chức năng AudioUnitRender gây ra một 'truy cập xấu bộ nhớ' trong khi một ngoại lệ không được ném ra.

Cảm giác của tôi là cuộc gọi mã ghi âm không nguyên tử với cập nhật hệ điều hành của các cấu trúc liên quan đến thiết bị âm thanh. Vì vậy, nhiều phi nguyên tử là khả năng gọi lại ghi âm nhiều khả năng là đồng thời cập nhật OS HW và ghi lại cuộc gọi lại.

Tôi đã sửa đổi mã của mình để rời khỏi cuộc gọi ghi âm mỏng nhất có thể nhưng cảm giác của tôi là tải xử lý cao được đưa bởi các chủ đề khác của ứng dụng của tôi là cho ăn các cuộc đua đồng thời được mô tả trước đây. Vì vậy, lỗi malloc/free tăng lên ở các phần khác của mã do truy cập xấu AudioUnitRender.

tôi đã cố gắng để giảm độ trễ ghi callback bởi:

UInt32 numFrames = 256; 
UInt32 dataSize = sizeof(numFrames); 

AudioUnitSetProperty(audioUnit, 
    kAudioUnitProperty_MaximumFramesPerSlice, 
    kAudioUnitScope_Global, 
    0, 
    &numFrames, 
    dataSize); 

và tôi đã cố gắng để thúc đẩy các mã có vấn đề:

dispatch_async(dispatch_get_main_queue(), ^{ 

Hiện ai có một lời khuyên hoặc giải pháp cho điều đó? Để sao chép các lỗi ở đây là mã phiên âm thanh của tôi:

// 
// IosAudioController.m 
// Aruts 
// 
// Created by Simon Epskamp on 10/11/10. 
// Copyright 2010 __MyCompanyName__. All rights reserved. 
// 

#import "IosAudioController.h" 
#import <AudioToolbox/AudioToolbox.h> 

#define kOutputBus 0 
#define kInputBus 1 

IosAudioController* iosAudio; 

void checkStatus(int status) { 
    if (status) { 
     printf("Status not 0! %d\n", status); 
     // exit(1); 
    } 
} 

/** 
* This callback is called when new audio data from the microphone is available. 
*/ 
static OSStatus recordingCallback(void *inRefCon, 
    AudioUnitRenderActionFlags *ioActionFlags, 
    const AudioTimeStamp *inTimeStamp, 
    UInt32 inBusNumber, 
    UInt32 inNumberFrames, 
    AudioBufferList *ioData) { 

    // Because of the way our audio format (setup below) is chosen: 
    // we only need 1 buffer, since it is mono 
    // Samples are 16 bits = 2 bytes. 
    // 1 frame includes only 1 sample 

    AudioBuffer buffer; 

    buffer.mNumberChannels = 1; 
    buffer.mDataByteSize = inNumberFrames * 2; 
    buffer.mData = malloc(inNumberFrames * 2); 

    // Put buffer in a AudioBufferList 
    AudioBufferList bufferList; 
    bufferList.mNumberBuffers = 1; 
    bufferList.mBuffers[0] = buffer; 

    NSLog(@"Recording Callback 1 0x%x ? 0x%x",buffer.mData, 
     bufferList.mBuffers[0].mData); 

    // Then: 
    // Obtain recorded samples 

    OSStatus status; 
    status = AudioUnitRender([iosAudio audioUnit], 
     ioActionFlags, 
     inTimeStamp, 
     inBusNumber, 
     inNumberFrames, 
     &bufferList); 
     checkStatus(status); 

    // Now, we have the samples we just read sitting in buffers in bufferList 
    // Process the new data 
    [iosAudio processAudio:&bufferList]; 

    NSLog(@"Recording Callback 2 0x%x ? 0x%x",buffer.mData, 
     bufferList.mBuffers[0].mData); 

    // release the malloc'ed data in the buffer we created earlier 
    free(bufferList.mBuffers[0].mData); 

    return noErr; 
} 

/** 
* This callback is called when the audioUnit needs new data to play through the 
* speakers. If you don't have any, just don't write anything in the buffers 
*/ 
static OSStatus playbackCallback(void *inRefCon, 
    AudioUnitRenderActionFlags *ioActionFlags, 
    const AudioTimeStamp *inTimeStamp, 
    UInt32 inBusNumber, 
    UInt32 inNumberFrames, 
    AudioBufferList *ioData) { 
     // Notes: ioData contains buffers (may be more than one!) 
     // Fill them up as much as you can. 
     // Remember to set the size value in each 
     // buffer to match how much data is in the buffer. 

    for (int i=0; i < ioData->mNumberBuffers; i++) { 
     // in practice we will only ever have 1 buffer, since audio format is mono 
     AudioBuffer buffer = ioData->mBuffers[i]; 

     // NSLog(@" Buffer %d has %d channels and wants %d bytes of data.", i, 
      buffer.mNumberChannels, buffer.mDataByteSize); 

     // copy temporary buffer data to output buffer 
     UInt32 size = min(buffer.mDataByteSize, 
      [iosAudio tempBuffer].mDataByteSize); 

     // dont copy more data then we have, or then fits 
     memcpy(buffer.mData, [iosAudio tempBuffer].mData, size); 
     // indicate how much data we wrote in the buffer 
     buffer.mDataByteSize = size; 

     // uncomment to hear random noise 
     /* 
     * UInt16 *frameBuffer = buffer.mData; 
     * for (int j = 0; j < inNumberFrames; j++) { 
     *  frameBuffer[j] = rand(); 
     * } 
     */ 
    } 

    return noErr; 
} 

@implementation IosAudioController 
@synthesize audioUnit, tempBuffer; 

void propListener(void *inClientData, 
    AudioSessionPropertyID inID, 
    UInt32 inDataSize, 
    const void *inData) { 

    if (inID == kAudioSessionProperty_AudioRouteChange) { 

     UInt32 isAudioInputAvailable; 
     UInt32 size = sizeof(isAudioInputAvailable); 
     CFStringRef newRoute; 
     size = sizeof(CFStringRef); 

     AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &size, &newRoute); 

     if (newRoute) { 
      CFIndex length = CFStringGetLength(newRoute); 
      CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, 
       kCFStringEncodingUTF8); 

      char *buffer = (char *)malloc(maxSize); 
      CFStringGetCString(newRoute, buffer, maxSize, 
       kCFStringEncodingUTF8); 

      //CFShow(newRoute); 
      printf("New route is %s\n",buffer); 

      if (CFStringCompare(newRoute, CFSTR("HeadsetInOut"), NULL) == 
       kCFCompareEqualTo) // headset plugged in 
      { 
       printf("Headset\n"); 
      } else { 
       printf("Another device\n"); 

       UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; 
       AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, 
        sizeof (audioRouteOverride),&audioRouteOverride); 
      } 
      printf("New route is %s\n",buffer); 
      free(buffer); 
     } 
     newRoute = nil; 
    } 
} 

/** 
* Initialize the audioUnit and allocate our own temporary buffer. 
* The temporary buffer will hold the latest data coming in from the microphone, 
* and will be copied to the output when this is requested. 
*/ 
- (id) init { 
    self = [super init]; 
    OSStatus status; 

    // Initialize and configure the audio session 
    AudioSessionInitialize(NULL, NULL, NULL, self); 

    UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord; 
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, 
     sizeof(audioCategory), &audioCategory); 
    AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, 
     propListener, self); 

    Float32 preferredBufferSize = .020; 
    AudioSessionSetProperty(kAudioSessionProperty_PreferredHardwareIOBufferDuration, 
     sizeof(preferredBufferSize), &preferredBufferSize); 

    AudioSessionSetActive(true); 

    // Describe audio component 
    AudioComponentDescription desc; 
    desc.componentType = kAudioUnitType_Output; 
    desc.componentSubType = 
     kAudioUnitSubType_VoiceProcessingIO/*kAudioUnitSubType_RemoteIO*/; 
    desc.componentFlags = 0; 
    desc.componentFlagsMask = 0; 
    desc.componentManufacturer = kAudioUnitManufacturer_Apple; 

    // Get component 
    AudioComponent inputComponent = AudioComponentFindNext(NULL, &desc); 

    // Get audio units 
    status = AudioComponentInstanceNew(inputComponent, &audioUnit); 
    checkStatus(status); 

    // Enable IO for recording 
    UInt32 flag = 1; 
    status = AudioUnitSetProperty(audioUnit, 
     kAudioOutputUnitProperty_EnableIO, 
     kAudioUnitScope_Input, 
     kInputBus, 
     &flag, 
     sizeof(flag)); 
     checkStatus(status); 

    // Enable IO for playback 
    flag = 1; 
    status = AudioUnitSetProperty(audioUnit, 
     kAudioOutputUnitProperty_EnableIO, 
     kAudioUnitScope_Output, 
     kOutputBus, 
     &flag, 
     sizeof(flag)); 

    checkStatus(status); 

    // Describe format 
    AudioStreamBasicDescription audioFormat; 
    audioFormat.mSampleRate = 8000.00; 
    //audioFormat.mSampleRate = 44100.00; 
    audioFormat.mFormatID = kAudioFormatLinearPCM; 
    audioFormat.mFormatFlags = 
     kAudioFormatFlagsCanonical/* kAudioFormatFlagIsSignedInteger | 
     kAudioFormatFlagIsPacked*/; 
    audioFormat.mFramesPerPacket = 1; 
    audioFormat.mChannelsPerFrame = 1; 
    audioFormat.mBitsPerChannel = 16; 
    audioFormat.mBytesPerPacket = 2; 
    audioFormat.mBytesPerFrame = 2; 

    // Apply format 
    status = AudioUnitSetProperty(audioUnit, 
     kAudioUnitProperty_StreamFormat, 
     kAudioUnitScope_Output, 
     kInputBus, 
     &audioFormat, 
     sizeof(audioFormat)); 

    checkStatus(status); 
    status = AudioUnitSetProperty(audioUnit, 
     kAudioUnitProperty_StreamFormat, 
     kAudioUnitScope_Input, 
     kOutputBus, 
     &audioFormat, 
     sizeof(audioFormat)); 

    checkStatus(status); 


    // Set input callback 
    AURenderCallbackStruct callbackStruct; 
    callbackStruct.inputProc = recordingCallback; 
    callbackStruct.inputProcRefCon = self; 
    status = AudioUnitSetProperty(audioUnit, 
     AudioOutputUnitProperty_SetInputCallback, 
     kAudioUnitScope_Global, 
     kInputBus, 
     &callbackStruct, 
     sizeof(callbackStruct)); 

    checkStatus(status); 
    // Set output callback 
    callbackStruct.inputProc = playbackCallback; 
    callbackStruct.inputProcRefCon = self; 
    status = AudioUnitSetProperty(audioUnit, 
     kAudioUnitProperty_SetRenderCallback, 
     kAudioUnitScope_Global, 
     kOutputBus, 
     &callbackStruct, 
     sizeof(callbackStruct)); 

    checkStatus(status); 

    // Disable buffer allocation for the recorder (optional - do this if we want to 
    // pass in our own) 

    flag = 0; 
    status = AudioUnitSetProperty(audioUnit, 
     kAudioUnitProperty_ShouldAllocateBuffer, 
     kAudioUnitScope_Output, 
     kInputBus, 
     &flag, 
     sizeof(flag)); 


    flag = 0; 
    status = AudioUnitSetProperty(audioUnit, 
    kAudioUnitProperty_ShouldAllocateBuffer, 
     kAudioUnitScope_Output, 
     kOutputBus, 
     &flag, 
     sizeof(flag)); 

    // Allocate our own buffers (1 channel, 16 bits per sample, thus 16 bits per 
    // frame, thus 2 bytes per frame). 
    // Practice learns the buffers used contain 512 frames, 
    // if this changes it will be fixed in processAudio. 
    tempBuffer.mNumberChannels = 1; 
    tempBuffer.mDataByteSize = 512 * 2; 
    tempBuffer.mData = malloc(512 * 2); 

    // Initialise 
    status = AudioUnitInitialize(audioUnit); 
    checkStatus(status); 

    return self; 
} 

/** 
* Start the audioUnit. This means data will be provided from 
* the microphone, and requested for feeding to the speakers, by 
* use of the provided callbacks. 
*/ 
- (void) start { 
    OSStatus status = AudioOutputUnitStart(audioUnit); 
    checkStatus(status); 
} 

/** 
* Stop the audioUnit 
*/ 
- (void) stop { 
    OSStatus status = AudioOutputUnitStop(audioUnit); 
    checkStatus(status); 
} 

/** 
* Change this function to decide what is done with incoming 
* audio data from the microphone. 
* Right now we copy it to our own temporary buffer. 
*/ 
- (void) processAudio: (AudioBufferList*) bufferList { 
    AudioBuffer sourceBuffer = bufferList->mBuffers[0]; 

    // fix tempBuffer size if it's the wrong size 
    if (tempBuffer.mDataByteSize != sourceBuffer.mDataByteSize) { 
     free(tempBuffer.mData); 
     tempBuffer.mDataByteSize = sourceBuffer.mDataByteSize; 
     tempBuffer.mData = malloc(sourceBuffer.mDataByteSize); 
    } 

    // copy incoming audio data to temporary buffer 
    memcpy(tempBuffer.mData, bufferList->mBuffers[0].mData, 
     bufferList->mBuffers[0].mDataByteSize); 
    usleep(1000000); // <- TO REPRODUCE THE ERROR, CONCURRENCY MORE LIKELY 

} 

/** 
* Clean up. 
*/ 
- (void) dealloc { 
    [super dealloc]; 
    AudioUnitUninitialize(audioUnit); 
    free(tempBuffer.mData); 
} 

@end 
+1

Bạn có thử thêm một breakpoint tại 'malloc_error_break' - nó sẽ cho bạn con trỏ đó là được giải thoát hai lần. – Mar0ux

+2

Bạn có bị rò rỉ 'char * buffer = (char *) malloc (maxSize);'? Bạn không cần bất kỳ mã btw nào - 'CFStringRef' là cầu nối miễn phí tới' NSString', vì vậy bạn có thể chỉ cần nhập 'newRoute' vào' NSString * 'và sử dụng các phương thức' NSString'. – Mar0ux

+1

Tôi quên bao gồm trong mã kiểm tra, tôi đã cung cấp các bản sửa lỗi cho các vấn đề mà bạn @ Mar0ux đánh dấu, nhưng trong ứng dụng của tôi chúng đã được sửa ('free (buffer);' và 'newRoute = nil;') .Không phải lúc nào lỗi là _malloc: * lỗi cho đối tượng 0x ....: con trỏ được giải phóng không được phân bổ_, lần khác lỗi là EXC_BAD_ACCESS trong một memcpy. –

Trả lời

8

Theo thử nghiệm của tôi, dòng đã kích hoạt lỗi SEGV là cuối cùng

AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, 
            sizeof (audioRouteOverride),&audioRouteOverride); 

Thay đổi các thuộc tính của một giữa chuỗi AudioUnit -flight luôn phức tạp, nhưng nếu bạn dừng AudioUnit trước khi chuyển đổi và bắt đầu lại, nó sẽ kết thúc bằng cách sử dụng hết tất cả bộ đệm mà nó đã lưu trữ và sau đó tiếp tục với các tham số mới.

Điều đó có thể chấp nhận được hay bạn cần ít khoảng trống hơn giữa thay đổi tuyến đường và khởi động lại bản ghi?

Những gì tôi đã làm là:

void propListener(void *inClientData, 
       AudioSessionPropertyID inID, 
       UInt32 inDataSize, 
       const void *inData) { 

[iosAudio stop]; 
// ... 

[iosAudio start]; 
} 

Không sụp đổ thêm về iPhone 5 của tôi (mileage của bạn có thể thay đổi với phần cứng khác nhau)

Lời giải thích hợp lý nhất mà tôi có cho hành vi đó, phần nào được hỗ trợ bởi những kiểm tra, là các ống render là không đồng bộ. Nếu bạn mất thời gian để thao tác bộ đệm của bạn, họ chỉ xếp hàng đợi. Nhưng nếu bạn thay đổi các thiết lập của AudioUnit, bạn kích hoạt một thiết lập lại hàng loạt trong hàng đợi render với các hiệu ứng phụ không rõ. Rắc rối là, những thay đổi này là đồng bộ, ảnh hưởng đến một cách hồi tố tất cả các cuộc gọi không đồng bộ chờ đợi kiên nhẫn cho đến lượt của họ.

nếu bạn không quan tâm đến các mẫu bỏ lỡ, bạn có thể làm điều gì đó như:

static BOOL isStopped = NO; 
static OSStatus recordingCallback(void *inRefCon, //... 
{ 
    if(isStopped) { 
    NSLog(@"Stopped, ignoring"); 
    return noErr; 
    } 
    // ... 
} 

static OSStatus playbackCallback(void *inRefCon, //... 
{ 
    if(isStopped) { 
    NSLog(@"Stopped, ignoring"); 
    return noErr; 
    } 
    // ... 
} 

// ... 

/** 
* Start the audioUnit. This means data will be provided from 
* the microphone, and requested for feeding to the speakers, by 
* use of the provided callbacks. 
*/ 
- (void) start { 
    OSStatus status = AudioOutputUnitStart(_audioUnit); 
    checkStatus(status); 

    isStopped = NO; 
} 

/** 
* Stop the audioUnit 
*/ 
- (void) stop { 

    isStopped = YES; 

    OSStatus status = AudioOutputUnitStop(_audioUnit); 
    checkStatus(status); 
} 

// ... 
+0

Cảm ơn @krug, đề xuất của bạn khắc phục vấn đề của mã này. Tuy nhiên, trong ứng dụng của tôi ghi âm và chơi callbacks được gọi là một 3-4 lần sau khi cắm/rút phích cắm hoạt động và trước khi 'propListener' gọi lại được gọi là. Bên trong các callback ghi âm và phát lại một số con trỏ cấu trúc bên ngoài được liên tục sửa đổi thành giá trị xấu cho đến khi gọi lại 'propListener' được gọi, khi sửa đổi các con trỏ đó dừng lại, nhưng thiệt hại đã được gây ra. Vì vậy, ở cuối của giao tiếp sản xuất sau này con trỏ được giải phóng không được cấp phát_ khi mã phá hủy các cấu trúc bên ngoài. –

+1

Một giải pháp có thể là phải có một mutex khóa quá trình ngay sau khi dừng lại, để được mở khóa khi tất cả các mẫu đã được xử lý? – krug

+0

Xin chào @krug, tôi đã cố gắng bảo vệ ghi âm và phát lại cuộc gọi bằng '@synchronized (iosAudio) {...}' (như một mutex), tôi đã đặt khối đồng bộ trong ghi âm và phát lại cuộc gọi khi lần đầu tiên bạn thay đổi câu trả lời được bao gồm với cùng một kết quả. –

Các vấn đề liên quan