Currently, I am converting the hardware decoding Obj-C code to Swift version. (Xcode 8, Swift 3).
I don't know how to set up a dictionary to set up an output option on the screen, also, I don't know how to use it.
The following code works fine in Obj-C project:
// set some values of the sample buffer's attachments
CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, YES);
CFMutableDictionaryRef dict = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
CFDictionarySetValue(dict, kCMSampleAttachmentKey_DisplayImmediately, kCFBooleanTrue);
I tried the following Swift code, but there was a runtime error:
// i got run-time error
let attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer!, true)
let dict = unsafeBitCast(attachments, to: CFMutableDictionary.self)
CFDictionarySetValue(dict, unsafeBitCast(kCMSampleAttachmentKey_DisplayImmediately, to: UnsafeRawPointer.self), unsafeBitCast(kCFBooleanTrue, to: UnsafeRawPointer.self))
Is it wrong to convert the CFString to UnsafeRawPointer? or Is it wrong to use the CFDictionarySetValue method?
this is my error log.
2016-11-24 16:50:44.458 MyApp[35288:3519253] -[__NSSingleObjectArrayI __setObject:forKey:]: unrecognized selector sent to instance 0x6000002045a0
2016-11-24 16:50:44.466 MyApp[35288:3519253] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSingleObjectArrayI __setObject:forKey:]: unrecognized selector sent to instance 0x6000002045a0'
*** First throw call stack:
(
0 CoreFoundation 0x000000010b02734b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000010a0e421e objc_exception_throw + 48
2 CoreFoundation 0x000000010b096f34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x000000010afacc15 ___forwarding___ + 1013
4 CoreFoundation 0x000000010afac798 _CF_forwarding_prep_0 + 120
5 MyApp 0x000000010937ac7a _TFC14MyApp16ViewerController21receivedRawVideoFramefT5frameGSaVs5UInt8_4withVs5Int32_T_ + 4890
6 MyApp 0x000000010937d8e2 _TFC14MyApp16ViewerController12MainCallBackfTVs5Int3212callbackCodeS1_8argumentGSqSv_7argSizeS1__T_ + 4242
7 MyApp 0x000000010937daed _TToFC14MyApp16ViewerController12MainCallBackfTVs5Int3212callbackCodeS1_8argumentGSqSv_7argSizeS1__T_ + 61
8 MyApp 0x000000010937dd56 _TTDFC14MyApp16ViewerController12MainCallBackfTVs5Int3212callbackCodeS1_8argumentGSqSv_7argSizeS1__T_ + 70
9 MyApp 0x000000010937dcfe _TTWC14MyApp16ViewerControllerS_18IJCallbackProtocolS_FS1_12MainCallBackfTVs5Int3212callbackCodeS2_8argumentGSqSv_7argSizeS2__T_ + 62
10 MyApp 0x00000001093b22b2 _TFC14MyApp11AppDelegate19MainCallBack_StreamfTVs5Int32S1_GSqSv_S1__T_ + 258
11 MyApp 0x00000001093d26d3 _TFZFC14MyApp19IJStreamCoreWrapper6AttachFTSv2ipSS4portSi_T_U_FTVs5Int32S1_GSqSv_S1_GSqSv__T_ + 355
12 MyApp 0x00000001093d2719 _TToFZFC14MyApp19IJStreamCoreWrapper6AttachFTSv2ipSS4portSi_T_U_FTVs5Int32S1_GSqSv_S1_GSqSv__T_ + 9
13 MyApp 0x00000001093ee176 _ZL8CallbackPN14CStreamManager9Session_TEiPvi + 70
14 MyApp 0x00000001093f09d3 _Z25StreamManagerThread_VideoPv + 3155
15 libsystem_pthread.dylib 0x000000010e494aab _pthread_body + 180
16 libsystem_pthread.dylib 0x000000010e4949f7 _pthread_body + 0
17 libsystem_pthread.dylib 0x000000010e494221 thread_start + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I was only able to get this working with the following:
let attachments = CMSampleBufferGetSampleAttachmentsArray(buf!, createIfNecessary: true)
let dict = unsafeBitCast(CFArrayGetValueAtIndex(attachments, 0), to: CFMutableDictionary.self)
CFDictionarySetValue(dict,
unsafeBitCast(kCMSampleAttachmentKey_DisplayImmediately, to: UnsafeRawPointer.self),
unsafeBitCast(kCFBooleanTrue, to: UnsafeRawPointer.self))
I tried #Alexander's suggestion, and although it compiles and executes, the underlying CFDictionary is not mutated and the desired result is not achieved.
// let attachments = CMSampleBufferGetSampleAttachmentsArray(buf!, createIfNecessary: true) as! Array<Dictionary<String, Any>>
// var dict = attachments[0]
// dict[kCMSampleAttachmentKey_DisplayImmediately as String] = true
In the first code snippet, you have a call to CFArrayGetValueAtIndex, which returns a dictionary that you pass to CFDictionarySetValue.
In the second code snippet, you don't call CFArrayGetValueAtIndex. You just pass the array to CFDictionarySetValue. Since an array is not a dictionary, you get a fatal error.
When you convert code to Swift, it's much best to understand the semantic of the program, and rewrite Swift code that matches. Don't try to just convert the syntax bit by bit.
CMSampleBufferGetSampleAttachmentsArray returns you a reference to a CFArray of CFDictionary instances. Casting this CFArrayRef to CFMutableDictionaryRef has the effect of just making a reference to the first instance.
It's best to just use Swift's native types. I can't provide an exact implementation because I'm not to sure of the types in play, but here's a start
//TODO: give me a better name
let array = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer!, true) as [[String: Bool]] //TODO:
//TODO: give me a better name
var firstDict = array[0]
firstDict[kCMSampleAttachmentKey_DisplayImmediately as String] = true
Related
I'm trying to set the fill color of individual features in a Mapbox map layer using the MGL_MATCH expression, but I keep getting:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString mgl_color]: unrecognized selector sent to instance ...
func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) {
let layer = mapView.style!.layer(withIdentifier: "powiaty-1") as! MGLFillStyleLayer
let source = mapView.style!.source(withIdentifier: "composite") as! MGLVectorTileSource
let features = source.features(sourceLayerIdentifiers: NSSet(object: "powiaty") as! Set<String>, predicate: nil);
let query = NSMutableString(format: "MGL_MATCH(jpt_kod_je, ");
for feature in features {
let code = feature.attribute(forKey: "jpt_kod_je") as! String
let color = code.prefix(2) == "06" ? UIColor.red : UIColor.white;
query.appendFormat("%#, %#, ", code, color)
}
query.appendFormat("%#)", UIColor.white);
print(query);
layer.fillColor = NSExpression(format: "%#", query);
}
The expected results:
Features whose 4-digit code (jpt_kod_je : String property) starts with "06" to be filled with red, all others with white.
Actual results:
Crash with the stack:
0 CoreFoundation 0x0000000106f456fb __exceptionPreprocess + 331
1 libobjc.A.dylib 0x00000001064e9ac5 objc_exception_throw + 48
2 CoreFoundation 0x0000000106f63ab4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x0000000106f4a443 ___forwarding___ + 1443
4 CoreFoundation 0x0000000106f4c238 _CF_forwarding_prep_0 + 120
5 Mapbox 0x000000010575d629 _ZN24MGLStyleValueTransformerIN4mbgl5ColorEU8__strongP7UIColorS1_S4_E15toPropertyValueINS0_5style13PropertyValueIS1_EEEENSt3__19enable_ifIXntsr3std7is_sameIT_NS7_22ColorRampPropertyValueEEE5valueESC_E4typeEP12NSExpressionb + 257
6 Mapbox 0x000000010582845e -[MGLFillStyleLayer setFillColor:] + 123
7 MapboxExpressions 0x0000000105443eb3 $s17MapboxExpressions14ViewControllerC03mapC19DidFinishLoadingMapyySo06MGLMapC0CF + 4867 ...
I have a minimal MacOS app (one view controller + one button) with the following code (basically a copy-paste from AudioKit's playground):
public class Player {
static let playRate = 2.0
static let scale = [0, 2, 4, 5, 7, 9, 11, 12]
var pluckedString: AKPluckedString! = nil
var delay: AKDelay! = nil
var reverb: AKReverb! = nil
var performance: AKPeriodicFunction! = nil
public init() {
pluckedString = AKPluckedString()
delay = AKDelay(pluckedString) // <- objc_exception_throw here
delay.time = 1.5 / Player.playRate
delay.dryWetMix = 0.3
delay.feedback = 0.2
reverb = AKReverb(delay)
performance = AKPeriodicFunction(frequency: Player.playRate) {
var note = Player.scale.randomElement()
let octave = [2, 3, 4, 5].randomElement() * 12
if random(0, 10) < 1.0 { note += 1 }
if !Player.scale.contains(note % 12) { print("ACCIDENT!") }
let frequency = (note + octave).midiNoteToFrequency()
if random(0, 6) > 1.0 {
self.pluckedString.trigger(frequency: frequency)
}
}
}
}
The problem is that call to AKDelay(pluckedString) produces ObjC exception:
AKPluckedString.swift:init(frequency:amplitude:lowestFrequency:):94:Parameter Tree Failed
[avae] AVAEInternal.h:70:_AVAE_Check: required condition is false: [AVAudioEngine.mm:353:AttachNode: (node != nil)]
[General] required condition is false: node != nil
[General] (
0 CoreFoundation 0x00007fff49d8d00b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x00007fff7096bc76 objc_exception_throw + 48
2 CoreFoundation 0x00007fff49d92da2 +[NSException raise:format:arguments:] + 98
3 AVFAudio 0x00007fff4610b75e _Z19AVAE_RaiseExceptionP8NSStringz + 158
4 AVFAudio 0x00007fff460ab1a2 _Z11_AVAE_CheckPKciS0_S0_b + 330
5 AVFAudio 0x00007fff4611f2e7 _ZN17AVAudioEngineImpl10AttachNodeEP11AVAudioNodeb + 63
6 AVFAudio 0x00007fff4611f267 -[AVAudioEngine attachNode:] + 67
7 AudioKit 0x000000010051de01 globalinit_33_0214DCBA62A4B4A95DF14CC0DE6A86C6_func60 + 13249
8 AudioKit 0x000000010051f24d globalinit_33_0214DCBA62A4B4A95DF14CC0DE6A86C6_func60 + 18445
9 AudioKit 0x0000000100512284 block_copy_helper.12 + 4852
10 AudioKit 0x0000000100519119 block_copy_helper.12 + 33161
11 AudioKit 0x0000000100639e8f block_copy_helper.12 + 38463
12 AudioKit 0x00000001006397ca block_copy_helper.12 + 36730
...
How can I fix this?
I am using AudioKit 4.0.4 / Swift 4.0.3 / XCode 9.2 (9C40b).
Is it because your App Sandbox is on? My Xcode (9.2) is defaulting to App Sandbox on (Capabilities tab of project). This results in a AudioKit giving this error.
import Foundation
import Swift
var buff = [UInt8](count: 256, repeatedValue: 0)
var index: UInt8
index = 0
for var i = 0; i < 256; ++i {
buff[i] = index;
++index
}
When I increment index outside of the for loop it works fine. But when I increment index inside the for loop, like in the code above, I get the following error
1
0 swift 0x000000010ea31fbb llvm::sys::PrintStackTrace(__sFILE*) + 43
1 swift 0x000000010ea326fb SignalHandler(int) + 379
2 libsystem_platform.dylib 0x00007fff832c3eaa _sigtramp + 26
3 libsystem_platform.dylib 000000000000000000 _sigtramp + 2094252400
4 swift 0x000000010cfa09bf llvm::MCJIT::runFunction(llvm::Function*, std::__1::vector<llvm::GenericValue, std::__1::allocator<llvm::GenericValue> > const&) + 271
5 swift 0x000000010cfa30f6 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, char const* const*) + 1190
6 swift 0x000000010ce34d8c swift::RunImmediately(swift::CompilerInstance&, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, swift::IRGenOptions&, swift::SILOptions const&) + 2188
7 swift 0x000000010cb23151 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&) + 13425
8 swift 0x000000010cb1fad3 frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 2691
9 swift 0x000000010cb1c154 main + 2324
10 libdyld.dylib 0x00007fff975535ad start + 1
11 libdyld.dylib 0x000000000000000c start + 1756023392
Stack dump:
0. Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -interpret File.swift -target x86_64-apple-darwin15.2.0 -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk -color-diagnostics -module-name File
Illegal instruction: 4
Anybody have any idea why this is happening?
The problem there it is in the last loop when you try to increment it overflows your UInt8.max 255.
You have many different options to accomplish what you want:
To keep the loop you will need start your iteration from the second element in your array and increment your var at the same time you assign it to your buff to prevent overflow:
for var i = 1; i < 256; ++i {
buff[i] = ++index
}
or use for in loop to iterate your array indices:
for i in buff.indices {
buff[i] = UInt8(i)
}
Or you can simply initialize your array with a range:
let buff = [UInt8](0...255)
For a project I'm working on I'm using core data to store the application's data. The application loads XML from the internet and tries to store the objects generated from the parsed results in the data model. This used to work fine, until a few days ago. I changed the data model (added one property on an object), so I made a new version and ran mogenerator to generate new stub classes for the objects in the model. Most of it still works fine, but there are some odd errors in code that used to work perfectly.
During the parsing of the XML an object is created and values on it are filled in. One of the values is an URL for an image. In the data model this value may not be NIL, but in the XML it occasionaly is. I use validateForInsert on the item to check if I can commit it. This is the part that used to work fine, but now fails, complaining about the NIL value.
A bit of code from the parser:
...
currentItem = [[[MyItem alloc] initWithEntity:[self.dataModel entityByName:#"MyItem"] insertIntoManagedObjectContext:self.dataModel.managedObjectContext] autorelease];
currentItem.label = [attributeDict objectForKey:LABEL];
currentItem.paramString = [attributeDict objectForKey:QUERY_STRING];
[currentItem setSortOrderValue:[[currentRootItem items] count]];
[currentRootItem addItemsObject:currentItem];
} else if ([elementName isEqualToString:IMAGE]) {
currentItem.imageLocation = [attributeDict objectForKey:IMAGE_URL];
...
Then, when the document is parsed, I do the check:
...
{
NSArray *Items = [[myRootItem items] allObjects];
for (MyItem *item in Items) {
NSLog(#"%#", item);
NSLog(#"before");
NSLog(#"%d", [item validateForInsert:&validationError]);
NSLog(#"after");
if (![item validateForInsert:&validationError]) {
[[self.dataModel managedObjectContext] deleteObject:item];
}
}
}
...
This used to work just fine, but now it crashes in validateForInsert:
2011-03-30 13:38:32.951 xx[915:207] before
2011-03-30 13:38:33.130 xx[915:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: Property/imageLocation/Entity/Item)'
Stacktrace:
0 CoreFoundation 0x022fc5a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x02450313 objc_exception_throw + 44
2 CoreFoundation 0x022b4ef8 +[NSException raise:format:arguments:] + 136
3 CoreFoundation 0x022b4e6a +[NSException raise:format:] + 58
4 CoreFoundation 0x022fae15 -[__NSCFDictionary setObject:forKey:] + 293
5 CoreData 0x013fa87c -[NSValidationErrorLocalizationPolicy _cachedObjectForKey:value:] + 172
6 CoreData 0x013fa629 -[NSValidationErrorLocalizationPolicy _localizedPropertyNameForProperty:entity:] + 201
7 CoreData 0x013fa4e7 -[NSValidationErrorLocalizationPolicy localizedPropertyNameForProperty:] + 71
8 CoreData 0x013a844e -[NSManagedObject(_NSInternalMethods) _substituteEntityAndProperty:inString:] + 142
9 CoreData 0x013a572e -[NSManagedObject(_NSInternalMethods) _generateErrorWithCode:andMessage:forKey:andValue:additionalDetail:] + 254
10 CoreData 0x013598f1 -[NSPropertyDescription(_NSInternalMethods) _nonPredicateValidateValue:forKey:inObject:error:] + 161
11 CoreData 0x01359485 -[NSAttributeDescription(_NSInternalMethods) _nonPredicateValidateValue:forKey:inObject:error:] + 85
12 CoreData 0x01358b22 -[NSManagedObject(_NSInternalMethods) _validateValue:forProperty:andKey:withIndex:error:] + 386
13 CoreData 0x01358847 -[NSManagedObject(_NSInternalMethods) _validatePropertiesWithError:] + 263
14 CoreData 0x013586e1 -[NSManagedObject(_NSInternalMethods) _validateForSave:] + 81
15 xx 0x001af8bf -[MyParser parserDidEndDocument:] + 1039
16 Foundation 0x00742717 _endDocument + 95
I can't figure out what went wrong. As far as I know making a new version of the data model went right (using XCode), setting it to the current version etc, all went right. I didn't have these problems the last time I did all this...
The only thing different is that now I upgraded to XCode 3.2.6, from 3.2.5 or 3.2.4, I don't remember.
My target is iPhone, and I'm using the 4.3 iOS SDK that came with this version of XCode.
I had this problem and I fixed it by checking my data length. If your model has a string field, you must validate that the String you're passing doesn't exceed the field length.
Well, to answer my own question...
The problem is not there in 3.2.5, nor is it there in 4.0.1. Looks like apple has some bugfixing to do on 3.2.6...
any one have any idea why application crash on this place
In code I am doing something like this
RequestOperation* requestOperation = [[[RequestOperation alloc]initWithItem:item delegate:self] autorelease];
[operationQueue addOperation:requestOperation];
Error Code
OS Version: iPhone OS 4.2.1
Report Version: 104
Exception Type: SIGBUS
Exception Codes: BUS_ADRALN at 0x7c
Crashed Thread: 0
Thread 0 Crashed:
0 libSystem.B.dylib 0x000053e4 OSAtomicCompareAndSwap32 + 0
1 Foundation 0x00023235 ____addOperations_block_invoke_1 + 37
2 Foundation 0x00022d91 __addOperations + 229
3 Foundation 0x00022cab -[NSOperationQueue addOperation:] + 11
BUS_ADRALN means that there is an address alignment problem.
I would check if the NSOperation object that is passed to [NSOperationQueue addOperation:] is valid.