Код ниже содержит:
Камеру (
SetupCaptureSession
).Функцию обработки изображений, которая выводит картинку в виде шума на экран. (
-(void)setPicture
)Счетчик кадров в виде строки.
При отключении функции обработки изображений(
-(void)setPicture
) , средняя скорость снятая со счетчика кадров = 25 кадров в секунду. При включении функции обработки изображений, средняя скорость (по счётчику) падает до 15-17 кадров в секунду.
ViewController.m
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@implementation ViewController
@synthesize myImage; //UIImage
@synthesize imageView; //ImageView
@synthesize rect; //CGRect
@synthesize session; //AvCaptureSession
- (void)viewDidLoad {
[super viewDidLoad];
[self setupCaptureSession]; //создание сессии
}
//метод создающий сессию съемки
- (void)setupCaptureSession
{
NSError *error = nil;
session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetMedium;
AVCaptureDevice *device = [AVCaptureDevice
defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
}
[session addInput:input];
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
dispatch_queue_t queue = dispatch_queue_create("myQueue", NULL);
[output setSampleBufferDelegate:self queue:queue];// create Sample buffer
[session addOutput:output];
[session startRunning];
}
//функция вызывается при приходе нового кадра в камеру
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
fromConnection:(AVCaptureConnection *)connection
{
NSString *text = [NSString stringWithFormat: @"N = %d", N]; //создается строка в глобальной переменной "N"
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI
self.Label.text = text; //перезапись строки (подсчёт кадров)
[self setPicture]; //привязка отрисовки картинки к камере
});
NSLog(text); //print same string in console
N++; //здесь реализован счетчик кадров, которые пришли с начала сессии
}
//метод отвечающий за отрисовку шума и вывод его на экран.
-(void)setPicture {
NSLog(@"SetPicture was calling");
if(imageView!=NULL)
{//Дополнительное гашение imageView
[imageView removeFromSuperview];
imageView = NULL; //Убрать"!
}
int width = 352; //размеры
int height = 288;
size_t bufferLength = width * height * 4; //
uint8_t* pixels = (uint8_t*)malloc(bufferLength); //unsigned char
for (int i = 0; i < bufferLength/2; i++) {
pixels[i] = rand() % 255;
}
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(pixels, width, height, 8, width * 4, space, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast); // указатель void * __nullable data
CGImageRef toCGImage = CGBitmapContextCreateImage(ctx);
UIImage * uiimage = [[UIImage alloc] initWithCGImage:toCGImage];
CGImageRelease(toCGImage);
CGColorSpaceRelease(space);
CGContextRelease(ctx);
free(pixels);
myImage = uiimage;
//
rect = self.view.bounds; //Вынесли в член класса
if(imageView == NULL)
{
imageView = [[UIImageView alloc] initWithFrame:rect];
imageView.image = myImage;
[self.view addSubview:imageView];
NSLog(@"NULL");
} else
{
[imageView setNeedsDisplay];
NSLog(@"Dewnull");
}
}
@end
ViewController.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreMedia/CoreMedia.h>
#import <AVFoundation/AVFoundation.h>
int N = 0; //глобальная переменная для подсчета кадров.
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *Label; //строка для
@property AVCaptureSession *session;
@property UIImage* myImage;
@property UIImageView *imageView;
@property CGRect rect; //прямоугольное графическое пространство
- (void)setupCaptureSession;
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
fromConnection:(AVCaptureConnection *)connection;
-(void)setPicture; //Функция отрисовки шума
@end
Мне трудно понять с чем связано падение скорости кадров. Толи аппарат слабенький (512 мб оперативы). То ли ImageView
отрисовка->гашение пожирает память. То ли многопоточность страдает.
Вопрос:
Что нужно изменить в коде, чтобы при вызове функции setPicture
скорость кадров не падала?