Camera bar code scan crash with iPhone 11 and iOS 13 - iphone

We have code in a Xamarin App using bar code scanning. It has been working successfully for 3 years. We have found an issue with the iPhone 11 pro and its three camera setup.
_captureSession = new AVCaptureSession();
CameraMetaDataDelegate del = null;
AVCaptureDevice captureDevice =
AVCaptureDevice.GetDefaultDevice(AVMediaType.Video);
if (captureDevice != null)
{
var videoInput = AVCaptureDeviceInput.FromDevice(captureDevice, out error);
if (videoInput != null) { _captureSession.AddInput(videoInput); }
else { iApp.Log.Error("Video capture error: " + error.LocalizedDescription); }
var metaDataOutput = new AVCaptureMetadataOutput();
_captureSession.AddOutput(metaDataOutput);
del = new CameraMetaDataDelegate(this, _layer);
metaDataOutput.SetDelegate(del, CoreFoundation.DispatchQueue.MainQueue);
metaDataOutput.MetadataObjectTypes = metaDataOutput.AvailableMetadataObjectTypes;
_videoPreviewLayer = new AVCaptureVideoPreviewLayer(_captureSession) {
Frame = View.Bounds,
Orientation = (AVCaptureVideoOrientation)InterfaceOrientation,
};
View.Layer.AddSublayer(_videoPreviewLayer);
...
We have the the necessary entitlements in the info.plist
<key>NSCameraUsageDescription</key>
<string>Scan Barcodes</string>
It seems to be crashing on the AVCaptureDeviceInput. The "Application would like access to the camera" popup remains on the screen after the crash.
This works on older iPhones. We have not tried on an iPhone 11 non-pro.
Log looks like this
default 17:46:52.725211 -0500 tccd PID[30] is checking access for target PID[933]
default 17:46:52.734801 -0500 mediaserverd Updating configuration of monitor <RBSProcessMonitorConfiguration: 0x10cc25430; id: M30-27; qos: 25> {
predicates = {
<RBSProcessPredicate: 0x103735f30> {
predicate = <RBSCompoundPredicate; <RBSCompoundPredicate; <RBSProcessEUIDPredicate; 501>; <RBSProcessBKSLegacyPredicate: 0x103104870>>; <RBSProcessBundleIdentifierPredicate; com.apple.InCallService>>;
};
}
descriptor = <RBSProcessStateDescriptor: 0x10cc46300; values: 11> {
namespaces = {
com.apple.frontboard.visibility;
}
};
}
default 17:46:52.735816 -0500 mediaserverd BKSApplicationStateMonitor updated with invalid process
default 17:46:52.736059 -0500 runningboardd [daemon<com.apple.mediaserverd>:30] handle lookup could not find a matching process
default 17:46:52.736188 -0500 mediaserverd <<<< FigCaptureClientSessionMonitor >>>> -[FigCaptureClientSessionMonitor _updateClientStateCondition:newValue:]: <private> Updating client with application state "Foregrounded" and layout state "None"
default 17:46:52.736343 -0500 mediaserverd <<<< FigCaptureSession >>>> captureSession_updateRunningCondition: <0x102eddb90> (PID:933): ClientStartedSession:0 Cam/Audio:0/0 bg:0 prewarming:0 int:0 windowed:0 devStolen:0, pressured:0, active:0 shouldRun:0, start:0 stop:0 stopRecordingIfActive:0
default 17:46:52.746798 -0500 mediaserverd Creating remote service object
default 17:46:52.748227 -0500 applecamerad <private>
default 17:46:52.748255 -0500 applecamerad <private>
default 17:46:52.748282 -0500 applecamerad <private>
default 17:46:52.748314 -0500 applecamerad <private>
default 17:46:52.748348 -0500 applecamerad H10ISPFlickerDetectorCreate - HWType = 3; pContext = 0x104c0e830
default 17:46:52.748377 -0500 applecamerad FlickerDetector: ArbiterClient resource access granted=1
default 17:46:52.749880 -0500 mediaserverd 2325: [volm/inpt/0] on device [ type: vhaw; id: 233; addr: 0x109a33d60; hidden: 0; VA strms: { i/238/0x109a34bc0, }; agg dev: [ id: 203; addr: 0x10c38d800; uid: "VAD [vhaw] AggDev 6"; virt strms: { }; phys devs: { [ id: 94; addr: 0x102e1af80; uid: "Hawking"; streams: { i/95/0x102e1b2d0, } ] } ] ]: 1.000000.
default 17:46:52.749914 -0500 mediaserverd 161: Setting Input Volume: 18.000000 dB, Final HW Volume: 18.000000 dB, Final SW Volume: 0.000000 dB
default 17:46:52.749945 -0500 mediaserverd 162: PhysicalDevice UID = "Hawking"
default 17:46:52.750012 -0500 mediaserverd 163: Scope = 1768845428 ("inpt")
default 17:46:52.750041 -0500 mediaserverd 164: Element = 0 ("0")
default 17:46:52.750405 -0500 applecamerad AURemoteIO.cpp:1546:Start: Starting AURemoteIO(0x107008c40)
output client: 1 ch, 0 Hz, Float32, output HW: 1 ch, 0 Hz, Float32
input client: 2 ch, 16000 Hz, Float32, inter, input HW: 2 ch, 16000 Hz, Float32, non-inter
default 17:46:52.750485 -0500 applecamerad AURemoteIO.cpp:1556:Start: work interval port 0x607b
default 17:46:52.751151 -0500 mediaserverd MEDeviceStreamClient.cpp:216:AddRunningClient: AQME device VirtualAudioDevice_Hawking: client starting: <RemoteIOClient#0x10500e600(#0x10500e658); input; CMSession(applecamerad[116])>; running count now 1
default 17:46:52.751186 -0500 mediaserverd 671: Client request to start IO proc ID 0x109a4abc0 on VAD 233.
default 17:46:52.751276 -0500 mediaserverd <<<< FigCaptureSession >>>> captureSession_SetConfiguration: <0x102eddb90> (PID:933): New configuration: <private>
default 17:46:52.751375 -0500 mediaserverd <<<< FigCaptureSession >>>> captureSession_updateRunningCondition: <0x102eddb90> (PID:933): ClientStartedSession:0 Cam/Audio:0/0 bg:0 prewarming:0 int:0 windowed:0 devStolen:0, pressured:0, active:0 shouldRun:0, start:0 stop:0 stopRecordingIfActive:0
default 17:46:52.751608 -0500 mediaserverd 599: Starting IO type 0 on AggregateDevice 203.
default 17:46:52.751655 -0500 mediaserverd HALS_IOContext::StartIOProcID: 206 Hawking (VAD [vhaw] AggDev 6):
default 17:46:52.753329 -0500 mediaserverd starting ProcID 0x21 state: Prewarm: 0 Play: 0 State: Stopped IOProc 0x21: no
default 17:46:52.753407 -0500 mediaserverd HALS_Device::_GetCombinedVolumeScalar: client 0 is not present and has a combined volume scalar is 1.000000
default 17:46:52.753633 -0500 mediaserverd <<<< FigCaptureSession >>>> captureSession_SetConfiguration: <0x102eddb90> (PID:933): New configuration: <private>
default 17:46:52.753700 -0500 CommCenter #I <private> request: <private>.
default 17:46:52.753812 -0500 mediaserverd <<<< FigCaptureSession >>>> captureSession_updateRunningCondition: <0x102eddb90> (PID:933): ClientStartedSession:0 Cam/Audio:1/0 bg:0 prewarming:0 int:0 windowed:0 devStolen:0, pressured:0, active:0 shouldRun:0, start:0 stop:0 stopRecordingIfActive:0
default 17:46:52.753934 -0500 CommCenter #I Received Audio State: <private>
default 17:46:52.753974 -0500 nfcd 00000001 57f02250 -[NFCameraStateMonitor _updateCameraStateValue:]:203 current=0, new=5
default 17:46:52.754014 -0500 mediaserverd 65: :413:: IOProc (AggregateDevice 203, IO type NonNullIOProc) running state is now running (2).
default 17:46:52.754047 -0500 nfcd 00000001 57f02250 -[NFCameraStateMonitor _updateCameraStateValue:]:203 current=5, new=7
default 17:46:52.754078 -0500 nfcd 00000001 57f02250 -[NFCameraStateMonitor _updateCameraStateValue:]:203 current=7, new=15
default 17:46:52.754405 -0500 backboardd Connection removed: IOHIDEventSystemConnection uuid:07F3B331-86A0-445F-ABA7-DDDA546740A7 pid:933 process:MYAPP5 type:Passive entitlements:0x0 caller:BackBoardServices: <redacted> + 384 attributes:{
HighFrequency = 1;
bundleID = "com.MYCOMPANY.mobile.MYAPP.development";
pid = 933;
} inactive:0 events:102 mask:0x800
default 17:46:52.754543 -0500 backboardd HIDAnalytics Unregister Send event com.apple.hid.queueUsage
default 17:46:52.755359 -0500 SpringBoard Workspace connection invalidated for <FBWorkspaceServer: 0x2822ce040>
default 17:46:52.755514 -0500 SpringBoard [application<com.MYCOMPANY.mobile.MYAPP.development>:933] Now flagged as pending exit for reason: workspace client connection invalidated
default 17:46:52.755776 -0500 SpringBoard Updating configuration of monitor <RBSProcessMonitorConfiguration: 0x2823ed600; id: M57-6; qos: 25> {
predicates = {
<RBSProcessPredicate: 0x283a521b0> {
predicate = <RBSCompoundPredicate; <RBSCompoundPredicate; <RBSProcessEUIDPredicate; 501>; <RBSProcessBKSLegacyPredicate: 0x283a40340>>; <RBSProcessBundleIdentifierPredicate; com.apple.springboard>>;
};
<RBSProcessPredicate: 0x283a5c2e0> {
predicate = <RBSCompoundPredicate; <RBSCompoundPredicate; <RBSProcessEUIDPredicate; 501>; <RBSProcessBKSLegacyPredicate: 0x283a40340>>; <RBSProcessBundleIdentifierPredicate; com.apple.MailCompositionService>>;
};
<RBSProcessPredicate: 0x283a5c2d0> {
predicate = <RBSCompoundPredicate; <RBSProcessBundleIdentifierPredicate; com.apple.ScreenshotServicesService>; <RBSCompoundPredicate; <RBSProcessEUIDPredicate; 501>; <RBSProcessBKSLegacyPredicate: 0x283a40340>>>;
};
<RBSProcessPredicate: 0x283a5d2e0> {
predicate = <RBSCompoundPredicate; <RBSCompou<…>
default 17:46:52.755823 -0500 SpringBoard connection invalidated
default 17:46:52.755869 -0500 SpringBoard connection invalidated
default 17:46:52.756102 -0500 CommCenter Client [<private>] disconnected (conn=0x101590a20), client list size 35
default 17:46:52.756159 -0500 locationd #Spi, Connection invalidated for process <private>
Not sure if it is another permissions issue, or using the wrong AV API, or need another preliminary step. Perhaps a race condition that should delay until camera responds available?

Junior Jiang's suggestion led me down the path to getting the iPhone 11 pro bar code scanning. First it really is necessary to check the authorization status, which used to fire on the first request before. Once this is established, then the camera will work. The second problem is that, at least in Xamarin C#, I could not assign the list of AvailableMetaDataObjectTypes. There is an earlier Stack Overflow which directs to use that list: Stack Overflow Xcode 9/Swift 4 AVCaptureMetadataOutput setMetadataObjectTypes use availableMetadataObjectTypes
But now the solution was to explicitly state which ones to use.
_captureSession = new AVCaptureSession();
CameraMetaDataDelegate del = null;
var authStatus = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);
AVCaptureDevice captureDevice = null;
// check authorization status
if (authStatus == AVAuthorizationStatus.Authorized)
{
captureDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video); // update for iOS 13
}
else if (authStatus == AVAuthorizationStatus.NotDetermined)
{
AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (granted) =>
{
if (!granted)
{
Log.Error("ViewDidLoadBase ScanLayer RequestAccessForMediaType not granted!");
}
else
{
Log.Error("ViewDidLoadBase ScanLayer RequestAccessForMediaType granted!");
}
});
}
else
{
Log.Error("Not Authorized! Status: " + authStatus.ToString());
}
if (captureDevice != null)
{
var videoInput = AVCaptureDeviceInput.FromDevice(captureDevice, out error);
if (videoInput != null)
{
_captureSession.AddInput(videoInput);
}
else
{
Log.Error("Video capture error: " + error.LocalizedDescription);
}
var metaDataOutput = new AVCaptureMetadataOutput();
_captureSession.AddOutput(metaDataOutput);
del = new CameraMetaDataDelegate(this, _layer);
metaDataOutput.SetDelegate(del, CoreFoundation.DispatchQueue.MainQueue);
//metaDataOutput.MetadataObjectTypes = metaDataOutput.AvailableMetadataObjectTypes;
metaDataOutput.MetadataObjectTypes = AVMetadataObjectType.QRCode | AVMetadataObjectType.Code128Code | AVMetadataObjectType.UPCECode | AVMetadataObjectType.EAN13Code ;
_videoPreviewLayer = new AVCaptureVideoPreviewLayer(_captureSession) {
Frame = View.Bounds,
Orientation = (AVCaptureVideoOrientation)InterfaceOrientation,
};
View.Layer.AddSublayer(_videoPreviewLayer);

Related

Can eBPF's perf_submit() be used in a socket_filter program as well?

So I was trying to send some data from the kernel space program to the user space program using perf_submit.
I've done some studies and here(https://github.com/iovisor/bcc/issues/2423), yonghong-song answered(the last comment) that a socket_filter program can not access bpf_perf_event_output helper and therefore it can only be used for tracing program types.
However, on BCC reference site(https://github.com/iovisor/bcc/blob/master/docs/reference_guide.md#2-bpf_perf_output), if you ctrl+f and search for : 3. perf_submit()
, it says on the fifth line that "for SOCKET_FILTER programs, the struct __sk_buff *skb must be used instead."
I believe this infers that perf_submit() can be used for socket_filter programs as well?
So I have hard time figuring out if perf_submit() can indeed be used for a socket filter program. Maybe some functionalities have been added since Yonghong-song answered the question above?
I'm checking if perf_submit() would work with a socket filter and there's not really a line of code that grabs the data output by perf_submit because just addint perf_submit() in the kernel program already omitted an error.
Here's the code for my program :
from bcc import BPF
# Network interface to be monoitored
INTERFACE = "br-netrome"
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <net/sock.h>
#include <bcc/proto.h>
#include <linux/bpf.h>
#define IP_TCP 6
#define IP_UDP 17
#define IP_ICMP 1
#define ETH_HLEN 14
BPF_PERF_OUTPUT(events); // has to be delcared outside any function
int packet_monitor(struct __sk_buff *skb) {
u8 *cursor = 0;
u64 saddr;
u64 daddr;
u64 ttl;
u64 hchecksum;
struct ethernet_t *ethernet = cursor_advance(cursor, sizeof(*ethernet));
if (!(ethernet -> type == 0x0800)) {
return 0; // drop
}
struct ip_t *ip = cursor_advance(cursor, sizeof(*ip));
/*
if (ip->nextp != IP_TCP)
{
if (ip -> nextp != IP_UDP)
{
if (ip -> nextp != IP_ICMP)
return 0;
}
}
*/
saddr = ip -> src;
daddr = ip -> dst;
ttl = ip -> ttl;
hchecksum = ip -> hchecksum;
events.perf_submit(skb, &saddr, sizeof(saddr));
// bpf_trace_printk("saddr = %llu, daddr = %llu, ttl = %llu", saddr, daddr, ttl); // only three arguments can be passed using printk
// bpf_trace_printk("Incoming packet!!\\n");
return -1;
}
and here is the error code :
R0=inv2048 R6=ctx(id=0,off=0,imm=0) R7=inv0 R10=fp0,call_-1
4: (20) r0 = *(u32 *)skb[26]
5: (7b) *(u64 *)(r10 -8) = r0
6: (18) r2 = 0xffff9bde204ffa00
8: (18) r7 = 0xffffffff
10: (bf) r4 = r10
11: (07) r4 += -8
12: (bf) r1 = r6
13: (18) r3 = 0xffffffff
15: (b7) r5 = 8
16: (85) call bpf_perf_event_output#25
unknown func bpf_perf_event_output#25
Traceback (most recent call last):
File "packet_monitor.py", line 68, in <module>
function_skb_matching = bpf.load_func("packet_monitor", BPF.SOCKET_FILTER)
File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 397, in load_func
(func_name, errstr))
TL;DR. BPF programs of type BPF_PROG_TYPE_SOCKET_FILTER can use bpf_perf_event_output only starting with Linux 5.4.
Which helpers a given BPF program has access to is defined by the get_func_proto member of objects struct bpf_verifier_ops. You can find which bpf_verifier_ops object corresponds to which program type by reading function find_prog_type() and file bpf_types.h. In the case of BPF_PROG_TYPE_SOCKET_FILTER, the corresponding function is sk_filter_func_proto().
If you git blame that function on recent kernel sources, you will get something like the following (you can do the same with GitHub's blame feature):
$ git blame net/core/filter.c
[...]
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6080) static const struct bpf_func_proto *
5e43f899b03a3 (Andrey Ignatov 2018-03-30 15:08:00 -0700 6081) sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6082) {
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6083) switch (func_id) {
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6084) case BPF_FUNC_skb_load_bytes:
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6085) return &bpf_skb_load_bytes_proto;
4e1ec56cdc597 (Daniel Borkmann 2018-05-04 01:08:15 +0200 6086) case BPF_FUNC_skb_load_bytes_relative:
4e1ec56cdc597 (Daniel Borkmann 2018-05-04 01:08:15 +0200 6087) return &bpf_skb_load_bytes_relative_proto;
91b8270f2a4d1 (Chenbo Feng 2017-03-22 17:27:34 -0700 6088) case BPF_FUNC_get_socket_cookie:
91b8270f2a4d1 (Chenbo Feng 2017-03-22 17:27:34 -0700 6089) return &bpf_get_socket_cookie_proto;
6acc5c2910689 (Chenbo Feng 2017-03-22 17:27:35 -0700 6090) case BPF_FUNC_get_socket_uid:
6acc5c2910689 (Chenbo Feng 2017-03-22 17:27:35 -0700 6091) return &bpf_get_socket_uid_proto;
7c4b90d79d0f4 (Allan Zhang 2019-07-23 17:07:24 -0700 6092) case BPF_FUNC_perf_event_output:
7c4b90d79d0f4 (Allan Zhang 2019-07-23 17:07:24 -0700 6093) return &bpf_skb_event_output_proto;
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6094) default:
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6095) return bpf_base_func_proto(func_id);
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6096) }
2492d3b867043 (Daniel Borkmann 2017-01-24 01:06:27 +0100 6097) }
[...]
As you can see, BPF_FUNC_perf_event_output was only recently added to the list of helpers these BPF programs can call. The commit which added this support, 7c4b90d79d0f4, was merged in Linux v5.4:
$ git describe --contains 7c4b90d79d0f4
v5.4-rc1~131^2~248^2~20

How can I track down interference between the flutter libraries audo_recorder and stereo

I'm building an app with Flutter that allows me to record audio and then play it back later. I'm using the package audio_recorder 0.4.0 for recording the audio and the package stereo 1.0.0 for playing back the audio.
When I record using the iOS simulator, everything works fine. But when I run on the physical device (iPhone 6 Plus), I always get a 28 byte file at the end of the recording session - basically just a header to the m4a file.
I've tracked this down to some kind of interference between the two libraries. I can record on the physical device just fine if I use the sample app included with audio_recorder 0.4.0. But all I have to do is add the line stereo: 1.0.0 to the dependencies in pubspec.yml of that same sample project and suddenly I start getting the 28 byte files on the physical device at the end of a recording session instead of a normal size m4a file.
I have a two-part question:
What kind of interference could the stereo library be causing to make this kind of failure in the audio_recorder library? I suspected channel interference, but my attempt to isolate that didn't yield anything.
How can I track down what is causing this?
I have examined the console output from both sessions. When it is failing, I see several (8) of these lines in the the console output right after attempting to start recording:
mediaserverd 1111: AudioConverterNew returned -50
Others have suggested that this error occurs when there is no microphone available.
I also see this suspicious difference between the outputs.
When recording is broken:
default 11:36:57.098825 -0700 mediaserverd 4414: { "action":"set_play_state", "session":{"ID":"0x3315820","PID":14591,"name":"Runner"}, "details":"entry" }
default 11:36:57.100484 -0700 mediaserverd -CMSessionMgr- cmsSetIsPlaying: CMSession: 'sid:0x3315820, Runner(14591), 'prim'' with [MediaPlayback/Default] [NonMixable] [System Audio] starting playing.
default 11:36:57.104699 -0700 mediaserverd CAReportingClient.mm:328:-[CAReportingClient sendMessage:category:type:reporters:]: message {
Volume = "0.75";
VolumeCategory = "Audio/Video";
VolumeOperationProcess = "com.monkela.audioRecordSample";
VolumeOperationTime = 576708;
VolumePlayingState = 1;
}: (
857014545
)
default 11:36:57.105879 -0700 mediaserverd -CMVAEndptMgr- vaemSetDeviceVolume: CMSession: Setting cmsvolume = 0.750 for device ID: VirtualAudioDevice_Default
default 11:36:57.107295 -0700 mediaserverd VirtualAudio_Device.cpp:2046:SetPropertyData: [volm/outp/0] on device [ type: vdef; id: 354; addr: 0x1014e1ba0; hidden: 0; VA strms: { o/883/0x106fc5980 }; agg dev: [ id: 872; addr: 0x106f1a460; uid: "VAD [vdef] AggDev 52"; virt strms: { }; phys devs: { [ id: 292; addr: 0x104b0fdb0; uid: "Speaker"; streams: { i/294/0x104b11cd0, o/293/0x104b12790 } ] } ] ]: 0.750000.
default 11:36:57.108123 -0700 mediaserverd OutputVolumeControl_HAL_Common.cpp:662:CommitVolume: Setting Volume = -14.500000 dB, Final HW Volume = 0.000000 dB, Final SW Volume = -14.500000 dB, External Volume Handler: No
default 11:36:57.109008 -0700 mediaserverd OutputVolumeControl_HAL_Common.cpp:663:CommitVolume: PhysicalDevice UID = "Speaker"
default 11:36:57.109721 -0700 mediaserverd OutputVolumeControl_HAL_Common.cpp:664:CommitVolume: Scope = 1869968496 ("outp")
default 11:36:57.110704 -0700 mediaserverd OutputVolumeControl_HAL_Common.cpp:665:CommitVolume: Element = 0 ("0")
default 11:36:57.112062 -0700 mediaserverd OutputVolumeControl_HAL_Common.cpp:698:CommitVolume: SW Volume: 0.750000 scalar
default 11:36:57.114393 -0700 mediaserverd VirtualAudio_Device.cpp:2066:SetPropertyData: Client request to set nominal sample rate to 44100.000000 on VAD 354.
default 11:36:57.116038 -0700 assertiond [Runner:14591] Attempting to acquire assertion for Runner:14591: <BKProcessAssertion: 0x101349110; "CMSession.14591."com.monkela.audioRecordSample"."MediaPlayback".isPlayingProcessAssertion" (audio:inf); id:…C74721DE1F95>
default 11:36:57.116572 -0700 assertiond [Runner:14591] Add assertion: <BKProcessAssertion: 0x101349110; id: 13077-914DDDE2-35CE-4420-85ED-C74721DE1F95; name: CMSession.14591."com.monkela.audioRecordSample"."MediaPlayback".isPlayingProcessAssertion; state: active; reason: audio; duration: infs> {
owner = <BSProcessHandle: 0x101009be0; mediaserverd:13077; valid: YES>;
flags = preventSuspend, preventThrottleDownCPU, preventIdleSleep, preventSuspendOnSleep;
}
When recording is working:
default 11:39:19.865022 -0700 mediaserverd 2863: { "action":"activate", "session":{"ID":"0x3315826","PID":14609,"name":"Runner"}, "details":"entry" }
default 11:39:19.880637 -0700 mediaserverd CAReportingClient.mm:328:-[CAReportingClient sendMessage:category:type:reporters:]: message {
"active devices" = "[ { vdef, [ ], [ pspk ( 0 ) ] }, { vspd, [ pmbi ( 0 ) ], [ ] }, { vcal, [ pdln ( 0 ) ], [ puln ( 0 ) ] } ]";
category = csav;
"going_active" = 1;
mode = imdf;
"staying_active" = 0;
}: (
857014546
)
The output when recording is broken suggests that my attempt to start recording actually starts playing something (i.e. invoking the wrong library).
I tracked this down and figured out how to make the libraries work together by modifying the stereo package. It turns out the stereo package was activating a playback audio session in application didFinishLaunchingWithOptions. Essentially these lines:
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
[session setActive:YES error:&error];
I forked the stereo package and changed the code to activate the playback session only when it is actually needed. Magically my record function started working.
I'm not sure why it ever worked in the simulator. Somehow the simulator must be able to have both a playback and recording session going simultaneously.
UPDATE: The author of the stereo package accepted my pull request so as long as you have version 1.0.1 of the package, you should be able to avoid this interference issue.

unable to upload an image file to slack through hubot

I am trying to get an image of a web page using pageres package, And post the image to slack using hubot. I am able to get the image, but for some reason i am not able to post it to slack using slack upload api. Here is my code, can you tell me what could be wrong? (not a coffee lint issue)
fs = require("fs")
Pageres = require('pageres')
util = require("util")
request = require("request")
module.exports = (robot) ->
robot.respond /screenshot page (\S*)?( at )?(\S*)?/i, (msg) ->
pageres = new Pageres({delay: 30})
domain = msg.match[1].replace("http://", "")
if msg.match[3] == undefined
size = '960x1024'
else
size = msg.match[3]
dest = './screenshots'
msg.send "Acquiring screenshot of #{domain}"
pageres.src(domain, [size]).dest(dest)
pageres.run (err) ->
if err
robot.logger.error err
msg.send "Um..., you better check the log"
else
opts = {
method: 'POST',
uri: 'https://slack.com/api/files.upload',
formData: {
channels: process.env.HUBOT_SCREENSHOT_SLACK_CHANNEL,
initial_comment: "Screenshot of #{domain}",
token: process.env.HUBOT_SLACK_TOKEN,
file: fs.createReadStream("#{dest}/#{domain}.png")
}
}
request.post opts, (error, response, body) ->
if error
robot.logger.error error
else
robot.logger.debug 'screenshot posted to slack'
return
The bot is connected to slack, and receiving messages from slack, parsing them fine and getting the image back to the local destination, but not able to post it to slack, There are no errors as well in the log.
[Wed Apr 11 2018 16:16:47 GMT+0000 (UTC)] DEBUG Received message: '#hubot screenshot page http://www.google.com' in channel: ****, from: ******
[Wed Apr 11 2018 16:16:47 GMT+0000 (UTC)] DEBUG Message '#hubot screenshot page http://www.google.com' matched regex //^\s*[#]?hubot[:,]?\s*(?:screenshot page (\S*)?( at )?(\S*)?)/i/; listener.options = { id: null }
[Wed Apr 11 2018 16:16:47 GMT+0000 (UTC)] DEBUG Executing listener callback for Message '#hubot screenshot page http://www.google.com'
[Wed Apr 11 2018 16:16:47 GMT+0000 (UTC)] DEBUG Sending to *****: Acquiring screenshot of www.google.com
You can use curl command which can be called using child_process to upload a file in the channel.
curl -F file=#dramacat.gif -F channels=C024BE91L,#general -F token=xxxx-xxxxxxxxx-xxxx https://slack.com/api/files.upload
It seems the formData property in your opts variable should be slightly different like this:
formData: {
token: process.env.HUBOT_SLACK_TOKEN,
title: "Screenshot of #{domain}",
filename: "image.png",
filetype: "auto",
channels: channel_id,
file: fs.createReadStream("path_to_your_image"),
}
The channel_id is your slack channel id which you can see in the browser address bar when you access the channel.

Core data migration - Appstore build crashing on iOS 8 devices, working on iOS 9

My app store update build is crashing, it's a core data crash but I am getting this crash on only iOS 8 devices, it is working fine on iOS 9 devices.
I have correctly performed light weight migration as well added the new model version keeping the old one as a base, added the dictionary in options as well while adding "addPersistentStoreWithType".
ManagedObjectModel
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("abcProject", withExtension: "momd")
NSLog("Url is - \(modelURL)")
return NSManagedObjectModel(contentsOfURL: modelURL!)!
}()
PersistentStoreCoordinator
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("abcProject")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
NSLog("TEST564 - 7 URL - \(url)")
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: mOptions)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("TEST564 Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
NSLog("TEST564 FATAL error")
}
return coordinator
}()
Above is my set of code for reference. I have searched everywhere and I get details about the light weight migration only.
Following is the device log after crash:-
> Jul 19 11:25:00 iPhone abcProject-Production[211] <Warning>: CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null)
URL:file:///var/mobile/Containers/Data/Application/B12FCDA6-C91B-487E-8D03-CBBEB884996D/Documents/abcProject options:{
NSInferMappingModelAutomaticallyOption = 1;
NSMigratePersistentStoresAutomaticallyOption = 1;
} ... returned error Error Domain=NSCocoaErrorDomain Code=134130 "The operation couldn’t be completed. (Cocoa error 134130.)"
UserInfo=0x16b05490 {URL=file:///var/mobile/Containers/Data/Application/B12FCDA6-C91B-487E-8D03-CBBEB884996D/Documents/abcProject, metadata={
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes = {
TabBanner = <3722cf8b 4ac58f43 20c84d7e 7d66865d a1382ecc 1ab25190 7b7c3fa7 843813fe>;
Video = <c51795f8 140c4936 de1b7615 03a944e7 f2b0451f 3c0b5887 2cfb31d3 07610d22>;
};NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "79788D63-BEF2-4339-BF60-1580904D9B44";
"_NSAutoVacuumLevel" = 2;
}, reason=Can't find model for source store} with userInfo dictionary {
URL = "file:///var/mobile/Containers/Data/Application/B12FCDA6-C91B-487E-8D03-CBBEB884996D/Documents/abcProject";
metadata = {
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes = {
TabBanner = <3722cf8b 4ac58f43 20c84d7e 7d66865d a1382ecc 1ab25190 7b7c3fa7 843813fe>;
Video = <c51795f8 140c4936 de1b7615 03a944e7 f2b0451f 3c0b5887 2cfb31d3 07610d22>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "79788D63-BEF2-4339-BF60-1580904D9B44";
"_NSAutoVacuumLevel" = 2;
};
reason = "Can't find model for source store";
}
Jul 19 11:25:00 iPhone abcProject-Production[211] <Warning>: CoreData: annotation: NSPersistentStoreCoordinator's current model hashes are {
TabBanner = <2efd2387 6f370f71 d585132f 9d6aa8fe afcdc841 ef6e9b89 396625d1 cbc99cea>;
Video = <c51795f8 140c4936 de1b7615 03a944e7 f2b0451f 3c0b5887 2cfb31d3 07610d22>;
}
Jul 19 11:25:00 iPhone abcProject-Production[211] <Warning>: Unresolved error Optional(Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data" UserInfo=0x168e0c90 {NSLocalizedDescription=Failed to initialize the application's saved data, NSUnderlyingError=0x16b05350 "The operation couldn’t be completed. (Cocoa error 134130.)", NSLocalizedFailureReason=There was an error creating or loading the application's saved data.}), [NSLocalizedDescription: Failed to initialize the application's saved data, NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=134130 "The operation couldn’t be completed. (Cocoa error 134130.)"
UserInfo=0x16b05490 {URL=file:///var/mobile/Containers/Data/Application/B12FCDA6-C91B-487E-8D03-CBBEB884996D/Documents/abcProject, metadata={
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes = {
TabBanner = <3722cf8b 4ac58f43 20c84d7e 7d66865d a1382ecc 1ab25190 7b7c3fa7 843813fe>;
Video = <c51795f8 140c4936 de1b7615 03a944e7 f2b0451f 3c0b5887 2cfb31d3 07610d22>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "79788D63-BEF2-4339-BF60-1580904D9B44";
"_NSAutoVacuumLevel" = 2;
}, reason=Can't find model for source store}, NSLocalizedFailureReason: There was an error creating or loading the application's saved data.]
Jul 19 11:25:01 iPhone ReportCrash[212] <Error>: task_set_exception_ports(B07, 400, D03, 0, 0) failed with error (4: (os/kern) invalid argument)
Jul 19 11:25:01 iPhone ReportCrash[212] <Notice>: ReportCrash acting against PID 211
Jul 19 11:25:01 iPhone ReportCrash[212] <Notice>: Formulating crash report for process abcProject-Production[211]
Jul 19 11:25:01 iPhone SpringBoard[43] <Warning>: BSXPCMessage received error for message: Connection invalid
Jul 19 11:25:01 iPhone SpringBoard[43] <Warning>: Unable to get short BSD proc info for 211: No such process
Jul 19 11:25:01 iPhone SpringBoard[43] <Warning>: Unable to get short BSD proc info for 211: No such process
Jul 19 11:25:01 iPhone mediaserverd[37] <Notice>: '' com.abcProject(pid = 211) setting DiscoveryMode = DiscoveryMode_None, currentDiscoveryMode = DiscoveryMode_None
Jul 19 11:25:01 iPhone wifid[69] <Notice>: WiFi:[490600501.266659]: Foreground Network Application exited.
Jul 19 11:25:01 iPhone AppStore[175] <Warning>: [SSMetricsEventController] Direct-access controller is calling through XPC to flush Unreported Events
Jul 19 11:25:01 iPhone wifid[69] <Notice>: WiFi:[490600501.267352]: BG Application: Not Present, BG Daemon: Present. Daemons: apsd itunesstored networkd
Jul 19 11:25:01 iPhone locationd[64] <Notice>: Gesture EnabledForTopCLient: 0, EnabledInDaemonSettings: 0
Jul 19 11:25:01 iPhone com.apple.xpc.launchd[1] (UIKitApplication:com.abcProject[0xb6e0][211]) <Notice>: Service exited due to signal: Abort trap: 6
Jul 19 11:25:01 iPhone com.apple.xpc.launchd[1] (UIKitApplication:com.abcProject[0xb6e0]) <Notice>: Service only ran for 6 seconds. Pushing respawn out by 2147483641 seconds.
Jul 19 11:25:01 iPhone locationd[64] <Notice>: Gesture EnabledForTopCLient: 0, EnabledInDaemonSettings: 0
Jul 19 11:25:01 iPhone SpringBoard[43] <Warning>: Application 'UIKitApplication:com.abcProject[0xb6e0]' crashed.
Jul 19 11:25:01 iPhone assertiond[58] <Warning>: pid_suspend failed for <BKNewProcess: 0x1668b480; com.abcProject; pid: 211; hostpid: -1>: Unknown error: -1, Unknown error: -1
Jul 19 11:25:01 iPhone assertiond[58] <Warning>: Could not set priority of <BKNewProcess: 0x1668b480; com.abcProject; pid: 211; hostpid: -1> to 2, priority: No such process
Jul 19 11:25:01 iPhone assertiond[58] <Warning>: Could not set priority of <BKNewProcess: 0x1668b480; com.abcProject; pid: 211; hostpid: -1> to 4096, priority: No such process
Jul 19 11:25:01 iPhone UserEventAgent[17] <Warning>: id=com.abcProject pid=211, state=0
Jul 19 11:25:01 iPhone ReportCrash[212] <Notice>: Saved report to /var/mobile/Library/Logs/CrashReporter/abcProject-Production_2016-07-19-112501_iPhone.ips
Jul 19 11:25:06 iPhone wifid[69] <Notice>: WiFi:[490600506.681414]: WiFi unquiescing requested by "locationd"
Jul 19 11:25:06 iPhone wifid[69] <Notice>: WiFi:[490600506.686744]: WiFi unquiescing requested by "locationd"
Jul 19 11:25:06 iPhone wifid[69] <Notice>: WiFi:[490600506.743193]: WiFi unquiescing requested by "locationd"
Jul 19 11:25:08 iPhone wifid[69] <Notice>: WiFi:[490600508.843256]: Client itunesstored set type to normal application
Jul 19 11:25:08 iPhone wifid[69] <Notice>: WiFi:[490600508.844080]: __WiFiManagerSetEnableState: state TRUE, manager->enable.setting TRUE, manager->unlockedSinceBoot TRUE
Jul 19 11:25:08 iPhone wifid[69] <Notice>: WiFi:[490600508.845449]: BG Application: Not Present, BG Daemon: Present. Daemons: apsd networkd
Jul 19 11:25:09 iPhone locationd[64] <Notice>: Gesture EnabledForTopCLient: 0, EnabledInDaemonSettings: 0
Jul 19 11:25:12 iPhone aggregated[29] <Warning>: Scheduling parameters: 0 minutes before midnight, 4.0 time(s)/day
Jul 19 11:25:12 iPhone aggregated[29] <Warning>: delay: 595 into interval 21600 => 22195
Jul 19 11:25:12 iPhone aggregated[29] <Warning>: Next ADDaily run scheduled in 06:09:55 at 2016-07-19 12:05:07 +0000
Jul 19 11:25:12 iPhone addaily[213] <Warning>: addaily started
Jul 19 11:25:12 iPhone addaily[213] <Warning>: daily tasks for day 17000
Jul 19 11:25:13 iPhone addaily[213] <Warning>: Filtering only beta sessions
Jul 19 11:25:13 iPhone addaily[213] <Warning>: Saved Sessions as /var/mobile/Library/Logs/CrashReporter/log-sessions-2016-07-19-112513.session
Jul 19 11:25:23 iPhone addaily[213] <Warning>: addaily ended
The error, Can't find model for source store says that when the app tried to migrate the persistent store, it could not find the data model that had been used to create the store. Data migration requires both the old and new data stores. The old one is used to load the data, and the new one is used to update the data for future use.
The reason this works on iOS 9 is that iOS 9 added model caching for use in lightweight migrations of SQLite stores. On iOS 9 you can therefore get a successful migration without the old model, because the old version will be automatically cached. This feature was not available on iOS 8, so if you're still supporting 8 then you still need to include the old version of the model in your app.
Finally I got it resolved by doing a simple change .
Earlier code :-
url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("abcProject1")
Fixed code :-
url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("abcProject1.sqlite")
adding <.sqlite> extension to my url path solved the issue for me.
It is fully tested with all the possible scenarios.
Thank you all for your help.
To avoid the crash I created new database for iOS 8 because I didnt need existing data that much.
I changed my storeURL from
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("abcProject")
to
let url:NSURL
if (OS_VERSION<9.0)
{
url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("abcProject1")
}
else
{
url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("abcProject")
}
This fixed the crash for me.

Can mobilesubstrate hook this?

I want to hook a function called png_handle_IHDR declared locally in the ImageIO framework. I used MobileSafari as the filter. But while calling the original function, mobilesafari crashes. Upon inspection of the NSLog, i get this:
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: dlopen ImageIO success!
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: Zeroing of nlist success!
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: method name successfully assigned!
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: nlist SUCCESS! nlsetting..
Jun 5 17:21:08 unknown MobileSafari[553] <Warning>: nlset success! Hooking..
Jun 5 17:21:09 unknown MobileSafari[553] <Warning>: Png IHDR handle hooking!
Jun 5 17:21:09 unknown UIKitApplication:com.apple.mobilesafari[0x819][553] <Notice>: libpng error: Invalid IHDR chunk
Jun 5 17:21:09 unknown ReportCrash[554] <Notice>: Formulating crash report for process MobileSafari[553]
Jun 5 17:21:09 unknown com.apple.launchd[1] <Warning>: (UIKitApplication:com.apple.mobilesafari[0x819]) Job appears to have crashed: Abort trap: 6
Jun 5 17:21:09 unknown SpringBoard[530] <Warning>: Application 'Safari' exited abnormally with signal 6: Abort trap: 6
I immediately gathered that its very likely that I got the function prototype of the png_handle_IHDR wrong. The following is my code in the tweak:
#import <CoreFoundation/CoreFoundation.h>
#include <substrate.h>
#define ImageIO "/System/Library/Frameworks/ImageIO.framework/ImageIO"
void (*png_handle_IHDR)();
MSHook(void, png_handle_IHDR){
NSLog(#"Png IHDR handle hooking!\n");
_png_handle_IHDR(); //crashed here!!
NSLog(#"Png IHDR handle hooking finished!\n");
}
template <typename Type_>
static void nlset(Type_ &function, struct nlist *nl, size_t index) {
struct nlist &name(nl[index]);
uintptr_t value(name.n_value);
if ((name.n_desc & N_ARM_THUMB_DEF) != 0)
value |= 0x00000001;
function = reinterpret_cast<Type_>(value);
}
MSInitialize {
if (dlopen(ImageIO, RTLD_LAZY | RTLD_NOLOAD)!=NULL)
{
NSLog(#"dlopen ImageIO success!\n");
struct nlist nl[2];
bzero(&nl, sizeof(nl));
NSLog(#"Zeroing of nlist success!\n");
nl[0].n_un.n_name = (char*) "_png_handle_IHDR";
NSLog(#"method name successfully assigned!\n");
nlist(ImageIO,nl);
NSLog(#"nlist SUCCESS! nlsetting..\n");
nlset(png_handle_IHDR, nl, 0);
NSLog(#"nlset success! Hooking..\n");
MSHookFunction(png_handle_IHDR,MSHake(png_handle_IHDR));
}
}
My makefile is as such:
include theos/makefiles/common.mk
TWEAK_NAME = privateFunctionTest
privateFunctionTest_FILES = Tweak.xm
include $(THEOS_MAKE_PATH)/tweak.mk
privateFunctionTest_FRAMEWORKS = UIKit ImageIO CoreGraphics Foundation CoreFoundation
Edit: The question is, is knowing the original function arguments necessary for a successful hook? If yes, is getting the function prototype from the disassembly the only way? There is no definition of this in any of the SDK headers. Thanks.
Ok, I decompiled the function and get the function prototype guessed by the decompiler. As long as the parameters and return type broadly matched e.g. bool : int, unsigned int : int, it still works without killing the execution. So this works:
int *png_handle_IHDR(int a1, int a2, int a3);
MSHook(int, png_handle_IHDR, int a1, int a2, int a3){
NSLog(#"png_handle_IHDR(%d,%d,%d)", a1,a2,a3);
int val = _png_handle_IHDR(a1,a2,a3);
NSLog(#"Png IHDR handle hooking finished, returning %d as result!", val);
return val;
}