首页 文章 精选 留言 我的

精选列表

搜索[硬件],共10002篇文章
优秀的个人博客,低调大师

转载: iOS音视频实时采集硬件编码

原文地址:https://blog.csdn.net/u011518723/article/details/49248467 我的demo地址:https://github.com/weiman152/LiveRecordDemo。 其中的swift版的viewcontroller是视频采集部分,供参考。 OC部分包括了音视频的采集以及编码。 感谢作者的分享,下面是原文内容: 使用 AVCaptureSession进行实时采集音视频 通过AVCaptureVideoDataOutputSampleBufferDelegate获取到音视频buffer数据 分别对音视频原始数据进行编码 传输 // // ViewController.h // H264AACEncode // // Created by ZhangWen on 15/10/14. // Copyright © 2015年 Zhangwen. All rights reserved. // #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import "AACEncoder.h" #import "H264Encoder.h" @interface ViewController : UIViewController <AVCaptureVideoDataOutputSampleBufferDelegate,AVCaptureAudioDataOutputSampleBufferDelegate,H264EncoderDelegate> @end // // ViewController.m // H264AACEncode // // Created by ZhangWen on 15/10/14. // Copyright © 2015年 Zhangwen. All rights reserved. // #import "ViewController.h" #define CAPTURE_FRAMES_PER_SECOND 20 #define SAMPLE_RATE 44100 #define VideoWidth 480 #define VideoHeight 640 @interface ViewController () { UIButton *startBtn; bool startCalled; H264Encoder *h264Encoder; AACEncoder *aacEncoder; AVCaptureSession *captureSession; dispatch_queue_t _audioQueue; AVCaptureConnection* _audioConnection; AVCaptureConnection* _videoConnection; NSMutableData *_data; NSString *h264File; NSFileHandle *fileHandle; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. startCalled = true; _data = [[NSMutableData alloc] init]; captureSession = [[AVCaptureSession alloc] init]; [self initStartBtn]; } #pragma mark #pragma mark - 设置音频 capture - (void) setupAudioCapture { aacEncoder = [[AACEncoder alloc] init]; // create capture device with video input /* * Create audio connection */ AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; NSError *error = nil; AVCaptureDeviceInput *audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioDevice error:&error]; if (error) { NSLog(@"Error getting audio input device: %@", error.description); } if ([captureSession canAddInput:audioInput]) { [captureSession addInput:audioInput]; } _audioQueue = dispatch_queue_create("Audio Capture Queue", DISPATCH_QUEUE_SERIAL); AVCaptureAudioDataOutput* audioOutput = [[AVCaptureAudioDataOutput alloc] init]; [audioOutput setSampleBufferDelegate:self queue:_audioQueue]; if ([captureSession canAddOutput:audioOutput]) { [captureSession addOutput:audioOutput]; } _audioConnection = [audioOutput connectionWithMediaType:AVMediaTypeAudio]; } - (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position { NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; for ( AVCaptureDevice *device in devices ) if ( device.position == position ) return device; return nil; } #pragma mark #pragma mark - 设置视频 capture - (void) setupVideoCaprure { h264Encoder = [H264Encoder alloc]; [h264Encoder initWithConfiguration]; NSError *deviceError; AVCaptureDevice *cameraDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; // cameraDevice = [self cameraWithPosition:AVCaptureDevicePositionBack]; // cameraDevice.position = AVCaptureDevicePositionBack; AVCaptureDeviceInput *inputDevice = [AVCaptureDeviceInput deviceInputWithDevice:cameraDevice error:&deviceError]; // make output device AVCaptureVideoDataOutput *outputDevice = [[AVCaptureVideoDataOutput alloc] init]; NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey; NSNumber* val = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_420YpCbCr8BiPlanarFullRange]; NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:val forKey:key]; NSError *error; [cameraDevice lockForConfiguration:&error]; if (error == nil) { NSLog(@"cameraDevice.activeFormat.videoSupportedFrameRateRanges IS %@",[cameraDevice.activeFormat.videoSupportedFrameRateRanges objectAtIndex:0]); if (cameraDevice.activeFormat.videoSupportedFrameRateRanges){ [cameraDevice setActiveVideoMinFrameDuration:CMTimeMake(1, CAPTURE_FRAMES_PER_SECOND)]; [cameraDevice setActiveVideoMaxFrameDuration:CMTimeMake(1, CAPTURE_FRAMES_PER_SECOND)]; } }else{ // handle error2 } [cameraDevice unlockForConfiguration]; // Start the session running to start the flow of data outputDevice.videoSettings = videoSettings; [outputDevice setSampleBufferDelegate:self queue:dispatch_get_main_queue()]; // initialize capture session if ([captureSession canAddInput:inputDevice]) { [captureSession addInput:inputDevice]; } if ([captureSession canAddOutput:outputDevice]) { [captureSession addOutput:outputDevice]; } // begin configuration for the AVCaptureSession [captureSession beginConfiguration]; // picture resolution [captureSession setSessionPreset:[NSString stringWithString:AVCaptureSessionPreset640x480]]; _videoConnection = [outputDevice connectionWithMediaType:AVMediaTypeVideo]; //Set landscape (if required) if ([_videoConnection isVideoOrientationSupported]) { AVCaptureVideoOrientation orientation = AVCaptureVideoOrientationLandscapeRight; //<<<<<SET VIDEO ORIENTATION IF LANDSCAPE [_videoConnection setVideoOrientation:orientation]; } // make preview layer and add so that camera is view is displayed on screen NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; h264File = [documentsDirectory stringByAppendingPathComponent:@"test.h264"]; [fileManager removeItemAtPath:h264File error:nil]; [fileManager createFileAtPath:h264File contents:nil attributes:nil]; // Open the file using POSIX as this is anyway a test application //fd = open([h264File UTF8String], O_RDWR); fileHandle = [NSFileHandle fileHandleForWritingAtPath:h264File]; [h264Encoder initEncode:VideoWidth height:VideoHeight]; h264Encoder.delegate = self; } #pragma mark #pragma mark - sampleBuffer 数据 -(void) captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection { CMTime pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer); double dPTS = (double)(pts.value) / pts.timescale; // NSLog(@"DPTS is %f",dPTS); if (connection == _videoConnection) { [h264Encoder encode:sampleBuffer]; } else if (connection == _audioConnection) { [aacEncoder encodeSampleBuffer:sampleBuffer completionBlock:^(NSData *encodedData, NSError *error) { if (encodedData) { NSLog(@"Audio data (%lu): %@", (unsigned long)encodedData.length, encodedData.description); #pragma mark #pragma mark - 音频数据(encodedData) [_data appendData:encodedData]; } else { NSLog(@"Error encoding AAC: %@", error); } }]; } } #pragma mark #pragma mark - 视频 sps 和 pps - (void)gotSpsPps:(NSData*)sps pps:(NSData*)pps { const char bytes[] = "\x00\x00\x00\x01"; size_t length = (sizeof bytes) - 1; //string literals have implicit trailing '\0' NSData *ByteHeader = [NSData dataWithBytes:bytes length:length]; [fileHandle writeData:ByteHeader]; [fileHandle writeData:sps]; [fileHandle writeData:ByteHeader]; [fileHandle writeData:pps]; } #pragma mark #pragma mark - 视频数据回调 - (void)gotEncodedData:(NSData*)data isKeyFrame:(BOOL)isKeyFrame { NSLog(@"Video data (%lu): %@", (unsigned long)data.length, data.description); if (fileHandle != NULL) { const char bytes[] = "\x00\x00\x00\x01"; size_t length = (sizeof bytes) - 1; //string literals have implicit trailing '\0' NSData *ByteHeader = [NSData dataWithBytes:bytes length:length]; #pragma mark #pragma mark - 视频数据(data) [fileHandle writeData:ByteHeader]; //[fileHandle writeData:UnitHeader]; [fileHandle writeData:data]; } } #pragma mark #pragma mark - 录制 - (void)startBtnClicked { if (startCalled) { [self startCamera]; startCalled = false; [startBtn setTitle:@"Stop" forState:UIControlStateNormal]; } else { [startBtn setTitle:@"Start" forState:UIControlStateNormal]; startCalled = true; [self stopCarmera]; } } - (void) startCamera { [self setupAudioCapture]; [self setupVideoCaprure]; [captureSession commitConfiguration]; [captureSession startRunning]; } - (void) stopCarmera { [h264Encoder End]; [captureSession stopRunning]; //close(fd); [fileHandle closeFile]; fileHandle = NULL; // 获取程序Documents目录路径 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSMutableString * path = [[NSMutableString alloc]initWithString:documentsDirectory]; [path appendString:@"/AACFile"]; [_data writeToFile:path atomically:YES]; } - (void)initStartBtn { startBtn = [UIButton buttonWithType:UIButtonTypeCustom]; startBtn.frame = CGRectMake(0, 0, 100, 30); startBtn.center = self.view.center; [startBtn addTarget:self action:@selector(startBtnClicked) forControlEvents:UIControlEventTouchUpInside]; [startBtn setTitle:@"Start" forState:UIControlStateNormal]; [startBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.view addSubview:startBtn]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end // // AACEncoder.h // H264AACEncode // // Created by ZhangWen on 15/10/14. // Copyright © 2015年 Zhangwen. All rights reserved. // #import <Foundation/Foundation.h> #import <AVFoundation/AVFoundation.h> #import <AudioToolbox/AudioToolbox.h> @interface AACEncoder : NSObject @property (nonatomic) dispatch_queue_t encoderQueue; @property (nonatomic) dispatch_queue_t callbackQueue; - (void) encodeSampleBuffer:(CMSampleBufferRef)sampleBuffer completionBlock:(void (^)(NSData *encodedData, NSError* error))completionBlock; @end // // AACEncoder.m // H264AACEncode // // Created by ZhangWen on 15/10/14. // Copyright © 2015年 Zhangwen. All rights reserved. // #import "AACEncoder.h" @interface AACEncoder() @property (nonatomic) AudioConverterRef audioConverter; @property (nonatomic) uint8_t *aacBuffer; @property (nonatomic) NSUInteger aacBufferSize; @property (nonatomic) char *pcmBuffer; @property (nonatomic) size_t pcmBufferSize; @end @implementation AACEncoder - (void) dealloc { AudioConverterDispose(_audioConverter); free(_aacBuffer); } - (id) init { if (self = [super init]) { _encoderQueue = dispatch_queue_create("AAC Encoder Queue", DISPATCH_QUEUE_SERIAL); _callbackQueue = dispatch_queue_create("AAC Encoder Callback Queue", DISPATCH_QUEUE_SERIAL); _audioConverter = NULL; _pcmBufferSize = 0; _pcmBuffer = NULL; _aacBufferSize = 1024; _aacBuffer = malloc(_aacBufferSize * sizeof(uint8_t)); memset(_aacBuffer, 0, _aacBufferSize); } return self; } - (void) setupEncoderFromSampleBuffer:(CMSampleBufferRef)sampleBuffer { AudioStreamBasicDescription inAudioStreamBasicDescription = *CMAudioFormatDescriptionGetStreamBasicDescription((CMAudioFormatDescriptionRef)CMSampleBufferGetFormatDescription(sampleBuffer)); AudioStreamBasicDescription outAudioStreamBasicDescription = {0}; // Always initialize the fields of a new audio stream basic description structure to zero, as shown here: ... outAudioStreamBasicDescription.mSampleRate = inAudioStreamBasicDescription.mSampleRate; // The number of frames per second of the data in the stream, when the stream is played at normal speed. For compressed formats, this field indicates the number of frames per second of equivalent decompressed data. The mSampleRate field must be nonzero, except when this structure is used in a listing of supported formats (see “kAudioStreamAnyRate”). outAudioStreamBasicDescription.mFormatID = kAudioFormatMPEG4AAC; // kAudioFormatMPEG4AAC_HE does not work. Can't find `AudioClassDescription`. `mFormatFlags` is set to 0.' outAudioStreamBasicDescription.mFormatFlags = kMPEG4Object_AAC_LC; // Format-specific flags to specify details of the format. Set to 0 to indicate no format flags. See “Audio Data Format Identifiers” for the flags that apply to each format. outAudioStreamBasicDescription.mBytesPerPacket = 0; // The number of bytes in a packet of audio data. To indicate variable packet size, set this field to 0. For a format that uses variable packet size, specify the size of each packet using an AudioStreamPacketDescription structure. outAudioStreamBasicDescription.mFramesPerPacket = 1024; // The number of frames in a packet of audio data. For uncompressed audio, the value is 1. For variable bit-rate formats, the value is a larger fixed number, such as 1024 for AAC. For formats with a variable number of frames per packet, such as Ogg Vorbis, set this field to 0. outAudioStreamBasicDescription.mBytesPerFrame = 0; // The number of bytes from the start of one frame to the start of the next frame in an audio buffer. Set this field to 0 for compressed formats. ... outAudioStreamBasicDescription.mChannelsPerFrame = 1; // The number of channels in each frame of audio data. This value must be nonzero. outAudioStreamBasicDescription.mBitsPerChannel = 0; // ... Set this field to 0 for compressed formats. outAudioStreamBasicDescription.mReserved = 0; // Pads the structure out to force an even 8-byte alignment. Must be set to 0. AudioClassDescription *description = [self getAudioClassDescriptionWithType:kAudioFormatMPEG4AAC fromManufacturer:kAppleSoftwareAudioCodecManufacturer]; OSStatus status = AudioConverterNewSpecific(&inAudioStreamBasicDescription, &outAudioStreamBasicDescription, 1, description, &_audioConverter); if (status != 0) { NSLog(@"setup converter: %d", (int)status); } } - (AudioClassDescription *)getAudioClassDescriptionWithType:(UInt32)type fromManufacturer:(UInt32)manufacturer { static AudioClassDescription desc; UInt32 encoderSpecifier = type; OSStatus st; UInt32 size; st = AudioFormatGetPropertyInfo(kAudioFormatProperty_Encoders, sizeof(encoderSpecifier), &encoderSpecifier, &size); if (st) { NSLog(@"error getting audio format propery info: %d", (int)(st)); return nil; } unsigned int count = size / sizeof(AudioClassDescription); AudioClassDescription descriptions[count]; st = AudioFormatGetProperty(kAudioFormatProperty_Encoders, sizeof(encoderSpecifier), &encoderSpecifier, &size, descriptions); if (st) { NSLog(@"error getting audio format propery: %d", (int)(st)); return nil; } for (unsigned int i = 0; i < count; i++) { if ((type == descriptions[i].mSubType) && (manufacturer == descriptions[i].mManufacturer)) { memcpy(&desc, &(descriptions[i]), sizeof(desc)); return &desc; } } return nil; } static OSStatus inInputDataProc(AudioConverterRef inAudioConverter, UInt32 *ioNumberDataPackets, AudioBufferList *ioData, AudioStreamPacketDescription **outDataPacketDescription, void *inUserData) { AACEncoder *encoder = (__bridge AACEncoder *)(inUserData); UInt32 requestedPackets = *ioNumberDataPackets; //NSLog(@"Number of packets requested: %d", (unsigned int)requestedPackets); size_t copiedSamples = [encoder copyPCMSamplesIntoBuffer:ioData]; if (copiedSamples < requestedPackets) { //NSLog(@"PCM buffer isn't full enough!"); *ioNumberDataPackets = 0; return -1; } *ioNumberDataPackets = 1; //NSLog(@"Copied %zu samples into ioData", copiedSamples); return noErr; } - (size_t) copyPCMSamplesIntoBuffer:(AudioBufferList*)ioData { size_t originalBufferSize = _pcmBufferSize; if (!originalBufferSize) { return 0; } ioData->mBuffers[0].mData = _pcmBuffer; ioData->mBuffers[0].mDataByteSize = _pcmBufferSize; _pcmBuffer = NULL; _pcmBufferSize = 0; return originalBufferSize; } - (void) encodeSampleBuffer:(CMSampleBufferRef)sampleBuffer completionBlock:(void (^)(NSData * encodedData, NSError* error))completionBlock { CFRetain(sampleBuffer); dispatch_async(_encoderQueue, ^{ if (!_audioConverter) { [self setupEncoderFromSampleBuffer:sampleBuffer]; } CMBlockBufferRef blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer); CFRetain(blockBuffer); OSStatus status = CMBlockBufferGetDataPointer(blockBuffer, 0, NULL, &_pcmBufferSize, &_pcmBuffer); NSError *error = nil; if (status != kCMBlockBufferNoErr) { error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil]; } //NSLog(@"PCM Buffer Size: %zu", _pcmBufferSize); memset(_aacBuffer, 0, _aacBufferSize); AudioBufferList outAudioBufferList = {0}; outAudioBufferList.mNumberBuffers = 1; outAudioBufferList.mBuffers[0].mNumberChannels = 1; outAudioBufferList.mBuffers[0].mDataByteSize = _aacBufferSize; outAudioBufferList.mBuffers[0].mData = _aacBuffer; AudioStreamPacketDescription *outPacketDescription = NULL; UInt32 ioOutputDataPacketSize = 1; status = AudioConverterFillComplexBuffer(_audioConverter, inInputDataProc, (__bridge void *)(self), &ioOutputDataPacketSize, &outAudioBufferList, outPacketDescription); //NSLog(@"ioOutputDataPacketSize: %d", (unsigned int)ioOutputDataPacketSize); NSData *data = nil; if (status == 0) { NSData *rawAAC = [NSData dataWithBytes:outAudioBufferList.mBuffers[0].mData length:outAudioBufferList.mBuffers[0].mDataByteSize]; NSData *adtsHeader = [self adtsDataForPacketLength:rawAAC.length]; NSMutableData *fullData = [NSMutableData dataWithData:adtsHeader]; [fullData appendData:rawAAC]; data = fullData; } else { error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil]; } if (completionBlock) { dispatch_async(_callbackQueue, ^{ completionBlock(data, error); }); } CFRelease(sampleBuffer); CFRelease(blockBuffer); }); } /** * Add ADTS header at the beginning of each and every AAC packet. * This is needed as MediaCodec encoder generates a packet of raw * AAC data. * * Note the packetLen must count in the ADTS header itself. * See: http://wiki.multimedia.cx/index.php?title=ADTS * Also: http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Channel_Configurations **/ - (NSData*) adtsDataForPacketLength:(NSUInteger)packetLength { int adtsLength = 7; char *packet = malloc(sizeof(char) * adtsLength); // Variables Recycled by addADTStoPacket int profile = 2; //AAC LC //39=MediaCodecInfo.CodecProfileLevel.AACObjectELD; int freqIdx = 4; //44.1KHz int chanCfg = 1; //MPEG-4 Audio Channel Configuration. 1 Channel front-center NSUInteger fullLength = adtsLength + packetLength; // fill in ADTS data packet[0] = (char)0xFF; // 11111111 = syncword packet[1] = (char)0xF9; // 1111 1 00 1 = syncword MPEG-2 Layer CRC packet[2] = (char)(((profile-1)<<6) + (freqIdx<<2) +(chanCfg>>2)); packet[3] = (char)(((chanCfg&3)<<6) + (fullLength>>11)); packet[4] = (char)((fullLength&0x7FF) >> 3); packet[5] = (char)(((fullLength&7)<<5) + 0x1F); packet[6] = (char)0xFC; NSData *data = [NSData dataWithBytesNoCopy:packet length:adtsLength freeWhenDone:YES]; return data; } @end // // H264Encoder.h // H264AACEncode // // Created by ZhangWen on 15/10/14. // Copyright © 2015年 Zhangwen. All rights reserved. // #import <Foundation/Foundation.h> #import <AVFoundation/AVFoundation.h> #import <VideoToolbox/VideoToolbox.h> @protocol H264EncoderDelegate <NSObject> - (void)gotSpsPps:(NSData*)sps pps:(NSData*)pps; - (void)gotEncodedData:(NSData*)data isKeyFrame:(BOOL)isKeyFrame; @end @interface H264Encoder : NSObject - (void) initWithConfiguration; - (void) start:(int)width height:(int)height; - (void) initEncode:(int)width height:(int)height; - (void) encode:(CMSampleBufferRef )sampleBuffer; - (void) End; @property (weak, nonatomic) NSString *error; @property (weak, nonatomic) id<H264EncoderDelegate> delegate; @end // // H264Encoder.m // H264AACEncode // // Created by ZhangWen on 15/10/14. // Copyright © 2015年 Zhangwen. All rights reserved. // #import "H264Encoder.h" @implementation H264Encoder { NSString * yuvFile; VTCompressionSessionRef EncodingSession; dispatch_queue_t aQueue; CMFormatDescriptionRef format; CMSampleTimingInfo * timingInfo; BOOL initialized; int frameCount; NSData *sps; NSData *pps; } @synthesize error; - (void) initWithConfiguration { EncodingSession = nil; initialized = true; aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); frameCount = 0; sps = NULL; pps = NULL; } void didCompressH264(void *outputCallbackRefCon, void *sourceFrameRefCon, OSStatus status, VTEncodeInfoFlags infoFlags, CMSampleBufferRef sampleBuffer ) { // NSLog(@"didCompressH264 called with status %d infoFlags %d", (int)status, (int)infoFlags); if (status != 0) return; if (!CMSampleBufferDataIsReady(sampleBuffer)) { NSLog(@"didCompressH264 data is not ready "); return; } H264Encoder* encoder = (__bridge H264Encoder*)outputCallbackRefCon; // Check if we have got a key frame first bool keyframe = !CFDictionaryContainsKey( (CFArrayGetValueAtIndex(CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, true), 0)), kCMSampleAttachmentKey_NotSync); if (keyframe) { CMFormatDescriptionRef format = CMSampleBufferGetFormatDescription(sampleBuffer); // CFDictionaryRef extensionDict = CMFormatDescriptionGetExtensions(format); // Get the extensions // From the extensions get the dictionary with key "SampleDescriptionExtensionAtoms" // From the dict, get the value for the key "avcC" size_t sparameterSetSize, sparameterSetCount; const uint8_t *sparameterSet; OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 0, &sparameterSet, &sparameterSetSize, &sparameterSetCount, 0 ); if (statusCode == noErr) { // Found sps and now check for pps size_t pparameterSetSize, pparameterSetCount; const uint8_t *pparameterSet; OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 1, &pparameterSet, &pparameterSetSize, &pparameterSetCount, 0 ); if (statusCode == noErr) { // Found pps encoder->sps = [NSData dataWithBytes:sparameterSet length:sparameterSetSize]; encoder->pps = [NSData dataWithBytes:pparameterSet length:pparameterSetSize]; if (encoder->_delegate) { [encoder->_delegate gotSpsPps:encoder->sps pps:encoder->pps]; } } } } CMBlockBufferRef dataBuffer = CMSampleBufferGetDataBuffer(sampleBuffer); size_t length, totalLength; char *dataPointer; OSStatus statusCodeRet = CMBlockBufferGetDataPointer(dataBuffer, 0, &length, &totalLength, &dataPointer); if (statusCodeRet == noErr) { size_t bufferOffset = 0; static const int AVCCHeaderLength = 4; while (bufferOffset < totalLength - AVCCHeaderLength) { // Read the NAL unit length uint32_t NALUnitLength = 0; memcpy(&NALUnitLength, dataPointer + bufferOffset, AVCCHeaderLength); // Convert the length value from Big-endian to Little-endian NALUnitLength = CFSwapInt32BigToHost(NALUnitLength); NSData* data = [[NSData alloc] initWithBytes:(dataPointer + bufferOffset + AVCCHeaderLength) length:NALUnitLength]; [encoder->_delegate gotEncodedData:data isKeyFrame:keyframe]; // Move to the next NAL unit in the block buffer bufferOffset += AVCCHeaderLength + NALUnitLength; } } } - (void) start:(int)width height:(int)height { int frameSize = (width * height * 1.5); if (!initialized) { NSLog(@"H264: Not initialized"); error = @"H264: Not initialized"; return; } dispatch_sync(aQueue, ^{ // For testing out the logic, lets read from a file and then send it to encoder to create h264 stream // Create the compression session OSStatus status = VTCompressionSessionCreate(NULL, width, height, kCMVideoCodecType_H264, NULL, NULL, NULL, didCompressH264, (__bridge void *)(self), &EncodingSession); NSLog(@"H264: VTCompressionSessionCreate %d", (int)status); if (status != 0) { NSLog(@"H264: Unable to create a H264 session"); error = @"H264: Unable to create a H264 session"; return ; } // Set the properties VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue); VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse); VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, 240); VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_High_AutoLevel); // Tell the encoder to start encoding VTCompressionSessionPrepareToEncodeFrames(EncodingSession); // Start reading from the file and copy it to the buffer // Open the file using POSIX as this is anyway a test application int fd = open([yuvFile UTF8String], O_RDONLY); if (fd == -1) { NSLog(@"H264: Unable to open the file"); error = @"H264: Unable to open the file"; return ; } NSMutableData* theData = [[NSMutableData alloc] initWithLength:frameSize] ; NSUInteger actualBytes = frameSize; while (actualBytes > 0) { void* buffer = [theData mutableBytes]; NSUInteger bufferSize = [theData length]; actualBytes = read(fd, buffer, bufferSize); if (actualBytes < frameSize) [theData setLength:actualBytes]; frameCount++; // Create a CM Block buffer out of this data CMBlockBufferRef BlockBuffer = NULL; OSStatus status = CMBlockBufferCreateWithMemoryBlock(NULL, buffer, actualBytes,kCFAllocatorNull, NULL, 0, actualBytes, kCMBlockBufferAlwaysCopyDataFlag, &BlockBuffer); // Check for error if (status != noErr) { NSLog(@"H264: CMBlockBufferCreateWithMemoryBlock failed with %d", (int)status); error = @"H264: CMBlockBufferCreateWithMemoryBlock failed "; return ; } // Create a CM Sample Buffer CMSampleBufferRef sampleBuffer = NULL; CMFormatDescriptionRef formatDescription; CMFormatDescriptionCreate ( kCFAllocatorDefault, // Allocator kCMMediaType_Video, 'I420', NULL, &formatDescription ); CMSampleTimingInfo sampleTimingInfo = {CMTimeMake(1, 300)}; OSStatus statusCode = CMSampleBufferCreate(kCFAllocatorDefault, BlockBuffer, YES, NULL, NULL, formatDescription, 1, 1, &sampleTimingInfo, 0, NULL, &sampleBuffer); // Check for error if (statusCode != noErr) { NSLog(@"H264: CMSampleBufferCreate failed with %d", (int)statusCode); error = @"H264: CMSampleBufferCreate failed "; return; } CFRelease(BlockBuffer); BlockBuffer = NULL; // Get the CV Image buffer CVImageBufferRef imageBuffer = (CVImageBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer); // Create properties CMTime presentationTimeStamp = CMTimeMake(frameCount, 300); //CMTime duration = CMTimeMake(1, DURATION); VTEncodeInfoFlags flags; // Pass it to the encoder statusCode = VTCompressionSessionEncodeFrame(EncodingSession, imageBuffer, presentationTimeStamp, kCMTimeInvalid, NULL, NULL, &flags); // Check for error if (statusCode != noErr) { NSLog(@"H264: VTCompressionSessionEncodeFrame failed with %d", (int)statusCode); error = @"H264: VTCompressionSessionEncodeFrame failed "; // End the session VTCompressionSessionInvalidate(EncodingSession); CFRelease(EncodingSession); EncodingSession = NULL; error = NULL; return; } // NSLog(@"H264: VTCompressionSessionEncodeFrame Success"); } // Mark the completion VTCompressionSessionCompleteFrames(EncodingSession, kCMTimeInvalid); // End the session VTCompressionSessionInvalidate(EncodingSession); CFRelease(EncodingSession); EncodingSession = NULL; error = NULL; close(fd); }); } - (void) initEncode:(int)width height:(int)height { dispatch_sync(aQueue, ^{ // For testing out the logic, lets read from a file and then send it to encoder to create h264 stream // Create the compression session OSStatus status = VTCompressionSessionCreate(NULL, width, height, kCMVideoCodecType_H264, NULL, NULL, NULL, didCompressH264, (__bridge void *)(self), &EncodingSession); NSLog(@"H264: VTCompressionSessionCreate %d", (int)status); if (status != 0) { NSLog(@"H264: Unable to create a H264 session"); error = @"H264: Unable to create a H264 session"; return ; } // Set the properties VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue); VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_Main_AutoLevel); // Tell the encoder to start encoding VTCompressionSessionPrepareToEncodeFrames(EncodingSession); }); } - (void) encode:(CMSampleBufferRef )sampleBuffer { dispatch_sync(aQueue, ^{ frameCount++; // Get the CV Image buffer CVImageBufferRef imageBuffer = (CVImageBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer); // Create properties CMTime presentationTimeStamp = CMTimeMake(frameCount, 1000); //CMTime duration = CMTimeMake(1, DURATION); VTEncodeInfoFlags flags; // Pass it to the encoder OSStatus statusCode = VTCompressionSessionEncodeFrame(EncodingSession, imageBuffer, presentationTimeStamp, kCMTimeInvalid, NULL, NULL, &flags); // Check for error if (statusCode != noErr) { NSLog(@"H264: VTCompressionSessionEncodeFrame failed with %d", (int)statusCode); error = @"H264: VTCompressionSessionEncodeFrame failed "; // End the session VTCompressionSessionInvalidate(EncodingSession); CFRelease(EncodingSession); EncodingSession = NULL; error = NULL; return; } // NSLog(@"H264: VTCompressionSessionEncodeFrame Success"); }); } - (void) End { // Mark the completion VTCompressionSessionCompleteFrames(EncodingSession, kCMTimeInvalid); // End the session VTCompressionSessionInvalidate(EncodingSession); CFRelease(EncodingSession); EncodingSession = NULL; error = NULL; } @end

优秀的个人博客,低调大师

Openstack安装部署指南翻译系列 之 硬件需求

1.1.1.1.控制节点 控制器节点运行身份服务,镜像服务,计算的管理部分,网络的管理部分,各种网络代理和仪表板。它还包括支持服务,如SQL数据库,消息队列和NTP。 可选地,控制节点运行块存储,对象存储,编排和计量服务的部分。 控制器节点至少需要两个网络接口。 1.1.1.2.计算节点 计算节点运行虚拟机实例的Compute的管理程序部分。默认情况下,Compute使用KVM虚拟机管理程序。计算节点还运行网络服务代理,将实例连接到虚拟网络,并通过安全组向实例提供防火墙服务。 可以部署多个计算节点。每个节点至少需要两个网络接口。 1.1.1.3.块存储节点 可选的Block Storage节点包含块存储和共享文件系统为实例提供服务的磁盘。 为了简单起见,计算节点和此节点之间的服务流量使用管理网络。生产环境应实施单独的存储网络,以提高性能和安全性。我们的生产环境是通过划分VLAN使用单独的存储网络。 可以部署多个块存储节点,我们该项目使用1个块存储节点。每个节点至少需要一个网络接口。 1.1.1.4. 共享存储 可选的共享存储节点包含共享存储服务,用于提供共享存储。 我们的生产环境使用单独的存储网络,以提高性能和安全性。 此服务需要两个节点。每个节点至少需要一个网络接口。 本文转自yuweibing51CTO博客,原文链接:http://blog.51cto.com/yuweibing/1981166,如需转载请自行联系原作者

优秀的个人博客,低调大师

硬件变革前瞻 SSD和内存的前沿分析

如果未来SSD的速度足够快,内存是不是就会消失? 这问题首先要从计算机体系架构讲起,目前我们所使用的各种计算机,基本上都是冯诺依曼架构,多级存储架构。CPU在运行过程中都要从存储系统中读取指令,读 写数据。最高的一级是 CPU内的寄存器,速度等同于CPU。然后是多级Cach,每一级速度略慢。接着就是内存。以上统称为一级存储,通常断电后数据丢失。 再往下就是硬盘。也就是二级存储,我们的数据大都放在这里,断电也不会丢。而内存和硬盘的区别既是ROM和RAM之分。 从 上面我们可以知道,CPU的运行速度远远大于硬盘的读写速度。早期的电脑是没有内存的存在,所以经常造成CPU空闲等待状况,为了改善这个问题,人们发现 了局部性原理:程序运行过程中,CPU对内存的访问在一段时间内常常集中在一小块连续区域内。只要这一小块数据的访问时间足够快,CPU就不太会碰到空等 的情况。于是,内存就应势而生。 那么SSD速度足够快,就必须达到CPU速度。当前主流是SATA 3.0接口,速度是 6Gbps,按8b/10b编码后就是600MB/s,还有其它的损耗等。拿影驰高端品牌的名人堂HOF 256GB来说,连续读取达到520MB/S, 已经达到SATA 3.0,传输极限。但是跟CPU的速度比起来,还是鸿沟般的差距。 所 以在速度上,PCIE + NVME接口的SSD已成为SSD重要新生力量,可视为新一代产品方向。假如硬盘像现在的内存一样快,还断电不丢数据的话。理 论上是可以把内存去掉程序直接在硬盘上运行!一方面省去的程序和数据载入内存的时间,另外一方面,待机时就不需要耗电来维持内存刷新了,待机时间也会大大 延长。 同时,因为内存的易失性,硬盘起到了一个掉电保存计算机运算结果和保存已经录入计算机的程序的作用。 如果硬盘足够快,如果是能做到byte级别操作的话,那么这个就是拥有速度快、非易失性特点的内存模块。硬盘这个部件将会从此消失,替代品就是非易失的内存模块。这个模块就会有容量大、寿命长的特点。 也就是内存和硬盘合二为一。 总而言之,当硬盘有了内存一样的速度时,内存将会消失。但是应该是以物理的形式消亡。在计算机结构体系内,肯定还会有充当内存的中转桥梁的部分,充当缓冲地带。除非有革命性的全新存储技术被开发出来,否则这种状态在很长一段时间内会持续下去。 ====================================分割线================================ 本文转自d1net(转载)

优秀的个人博客,低调大师

大型硬件厂商如何应对存储市场的蚕食?

近年来,我们似乎一直从传统大型存储设备制造商那里听到相同的抱怨:业绩季季下滑、业务年年萎缩。 Dell、HP、IBM和NetApp似乎都在为保持他们存储业务的盈利而苦不堪言。这是市场的短暂调整,还是其他因素在起作用呢?这对IT行业又意味着什么?你是否应该改变购买习惯呢?作为IT行业评论员,我们通常有意避开这些财务数据。但是,从现在的情况来看,一些技术层面根本性的改变正在影响这些大型存储制造商的财务收入。并且,近两年来,这种趋势不减反增。 从许多方面来讲,这种趋势过于明显。你倾向于选择更有效的存储,而这将削弱存储的销售。举个例子来说,每当你将10 TB的数据存放到Amazon S3上时,对于EMC或者IBM来说,他们就将损失数TB的存储销售收益。当你在主要存储环境中部署了自动精简配置,它将为你节省30%的空间,同时,你对大型存储制造商的需求又进一步降低了。 让我们假设你使用Scality或者Cleversafe提供的对象存储技术,搭建了一个新的1 PB的环境。你将把成千上万的数据从NetApp的系统迁移到商用存储上。这将使得你每GB的成本降低5倍,但是NetApp的收益将受损。如果你将价格高昂的Tier 1应用容灾设备更换成Azure的虚拟化架构,预计将节省75%的成本,同时Dell和Symantec将受到打击。每当你在VNX中加入2 TB的固态硬盘,并且得到应用系统性能6倍的提高时,你已经抛弃了短行程(short-stroking)硬盘,收回了200 TB 硬盘容量——EMC的收益将受损。现在VMware可以精确识别每台虚机正在使用哪些资源,因而使你可以更好的对每个业务部门计费。业务部门也将更加仔细的按需申请资源,浪费将降低3倍,但是HP的收益将受到影响。 现在你应该看清楚了。虚拟化、去重、压缩、闪存、云存储、自动精简技术、对象存储,这些技术已经日趋成熟,你将毫不犹豫的使用它们。结果很明显,业务部门将十分高兴的看到,有史以来第一次,IT将根据他们的要求为客户提供服务。 但是亦有另一种相反的势力在作用。数据量如同野草一般疯涨,而你的业务部门需要你根据买家的行为作出实时的分析。由于监管或者内部分析的需要,我们必须保留所有的数据。多样化的大数据问题对Hadoop架构的集群产生了越来越大的压力。 如果深入分析,从短期来看,发展趋势是传统大型存储设备制造商将受到进一步的压制,而小型创新型公司可以更多的获益。全闪存阵列制造商如Pure、SolidFire、Violin Memory;混合阵列制造商如Gridstore、Nimble、Tegile、Tintri;对象云存储提供商如Scality、Cleversafe等小公司的利润都在增长。Nurtanix和SimpliVity则致力于将所有的IT设备通过一个超聚合的解决方案放进一台机器里。而Scale Computing则从根本上改变着中小型公司的IT购买方式。Actifio、Veeam、Zerto和其他一些数据保护公司因为提供了新的更有效的数据保护产品而利率大增。Permabit最近发布了一款在线数据去重和压缩的应用SANblox,它通过提高阵列的性能和容量,可以将数年的数据塞进一个阵列里。是的,存储行业的创新仍在不断进行,你追我赶。 传统存储厂商面临尴尬处境 那么,传统厂商能够做什么呢?他们开始提供软件定义存储产品,即便这必然在短时间内不会有好的收益。HP的StoreVirtual VSA和EMC的ViPR可以归为这类产品。而Dell也与Nutanix达成了OEM合作。每个传统大型厂商都在推出混合阵列、缓存软件以及其他高效的产品,以期能够将小公司踢出市场。但是这么做,大型厂商需要处理一个小公司不用考虑的问题:如何保证公司收益?如何不使华尔街失望?现在的真相是所有的大型厂商都面临两难。是迎合客户而损失收益?还是继续我行我素而损失客户? 每个厂商都会经历各自不同的战斗,并且很可能这场战斗在未来的两年内将持续。难题在于IT如何面对自身根本性的改变?我认为可以从三个方面考虑这个问题: · 新兴的创新型小公司层出不穷,你应该比从前投入更多精力来关注他们。 · 询问你的战略合作伙伴对未来的打算。如果他们还在提供15年前的架构,那是时候考虑更换他们了。 · 未雨绸缪。你希望三到五年之后,你的IT架构是怎样的?现在就开始适时投资。 这种创造性的破坏正在我们眼前发生着。五年后,我们可能不相信自己曾经活在如此孤立的构架下。大型厂商很脆弱,在可以预见的未来,他们的利润将进一下降。精明的厂商已经意识到那个属于昂贵的、专用的设备的时代已经一去不回,他们开始在内部进行资源调整。他们正在开始准备在未来低利率的市场上生存,并推出适应新时代的商品。当然,从短期来看,他们不会有任何收益。这些厂商之所以现在还生存着,正是由于他们过去作出的明智决定。但是,市场的转变远比他们的想象更强,厂商们必须进行调整。这场IT的变革终将发生。 本文转自d1net(转载)

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册