123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962 |
- #include "CustomVideoPlayer.h"
- #include "CVTextureCache.h"
- #include "CMVideoSampling.h"
- #include "GlesHelper.h"
- #import <AVFoundation/AVFoundation.h>
- #import <UIKit/UIKit.h>
- #import <Foundation/Foundation.h>
- #import <OpenGLES/ES2/gl.h>
- #import <OpenGLES/ES2/glext.h>
- static void* _ObserveItemStatusContext = (void*)0x1;
- static void* _ObservePlayerItemContext = (void*)0x2;
- @implementation CustomVideoPlayerView
- + (Class)layerClass
- {
- return [AVPlayerLayer class];
- }
- - (AVPlayer*)player
- {
- return [(AVPlayerLayer*)[self layer] player];
- }
- - (void)setPlayer:(AVPlayer*)player
- {
- [(AVPlayerLayer*)[self layer] setPlayer:player];
- }
- - (void)dealloc
- {
- self.player = nil;
- }
- @end
- @implementation CustomVideoPlayer
- {
- AVPlayerItem* _playerItem;
- AVPlayer* _player;
- AVAssetReader* _reader;
- AVAssetReaderTrackOutput* _videoOut;
- AVPlayerItemVideoOutput* videoOutput;
- CMSampleBufferRef _cmSampleBuffer;
- CMSampleBufferRef _cmSampleBuffer2;
- CMVideoSampling _videoSampling;
- CMVideoSampling _videoSamplingDummy;
-
- unsigned int _videoTexture;
- CMTime _duration;
- CMTime _curTime;
- CMTime _curFrameTimestamp;
- CMTime _lastFrameTimestamp;
- CGSize _videoSize;
- BOOL _playerReady;
- intptr_t _textureID;
- // we need to have both because the order of asset/item getting ready is not strict
- BOOL _assetReady;
- BOOL _itemReady;
- BOOL _error;
-
- BOOL _evertoon_was_unloaded;
-
- int _audioTrackId;
- int _audioTrackInfo;
-
- float _fVolume;
- }
- @synthesize delegate;
- - (int)audioTrack { return _audioTrackId; }
- - (int) getAudioTrack { return _audioTrackInfo; }
- - (void)setAudioTrack:(int)id
- {
- if(!_playerReady)
- return;
-
- if(_player == NULL)
- return;
-
- AVMediaSelectionGroup * group = [_player.currentItem.asset mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicAudible];
-
- if(id >= [group.options count])
- return;
-
- AVMediaSelectionOption *option = [group.options objectAtIndex:id];
- [_player.currentItem selectMediaOption:option inMediaSelectionGroup:group];
-
- _audioTrackId = id;
- [self setAudioVolume:[_player volume]];
- }
- - (NSTimeInterval) availableDuration
- {
- if(!_playerReady)
- return 0;
-
- NSArray *loadedTimeRanges = [_playerItem loadedTimeRanges];
- if(loadedTimeRanges != nil &&[loadedTimeRanges count] >0)
- {
- CMTimeRange timeRange = [[loadedTimeRanges objectAtIndex:0] CMTimeRangeValue];
- Float64 startSeconds = CMTimeGetSeconds(timeRange.start);
- Float64 durationSeconds = CMTimeGetSeconds(timeRange.duration);
- NSTimeInterval result = startSeconds + durationSeconds;
-
- return result;
- }
-
- return 0;
-
- //printf("\n%f %f",startSeconds,durationSeconds);
-
-
-
- }
- - (BOOL)readyToPlay { return _playerReady; }
- - (CGSize)videoSize { return _videoSize; }
- - (CMTime)duration { return _duration; }
- - (float)durationSeconds { return CMTIME_IS_VALID(_duration) ? (float)CMTimeGetSeconds(_duration) : 0.0f; }
- - (float)curTimeSeconds { return CMTIME_IS_VALID(_curTime) ? (float)
- CMTimeGetSeconds(_curTime) : 0.0f; }
- // npot textures are supported on gles1 only with ext.
- // so we support only gles2 for the sake of sanity;
- + (BOOL)CanPlayToTexture:(NSURL*)url { return /*IsRunningWithGLES2() && [url isFileURL];*/ true; }
- - (void)reportError:(NSError*)error category:(const char*)category
- {
- ::printf_console("[%s]Error: %s\n", category, [[error localizedDescription] UTF8String]);
- ::printf_console("%s\n", [[error localizedFailureReason] UTF8String]);
- }
- - (void)reportErrorWithString:(const char*)error category:(const char*)category
- {
- ::printf_console("[%s]Error: %s\n", category, error);
- }
- - (id)init
- {
- if( (self = [super init]) )
- {
- _duration = _curTime = kCMTimeZero;
- _curFrameTimestamp = _lastFrameTimestamp = kCMTimeZero;
- _evertoon_was_unloaded = false;
- }
-
- _fVolume= 1.0f;
- return self;
- }
- - (void)cleanCache
- {
- if(_videoSamplingDummy.cvTextureCache)
- {
- CFRelease(_videoSamplingDummy.cvTextureCache);
- _videoSamplingDummy.cvTextureCache = 0;
- }
- }
- - (void)cleanupCVTextureCache
- {
- if(_cmSampleBuffer)
- {
- CFRelease(_cmSampleBuffer);
- _cmSampleBuffer = 0;
- }
-
- if(_cmSampleBuffer2)
- {
- CFRelease(_cmSampleBuffer2);
- _cmSampleBuffer2 = 0;
- }
-
- if(_videoSampling.cvImageBuffer)
- {
- CFRelease(_videoSampling.cvImageBuffer);
- _videoSampling.cvImageBuffer = 0;
- }
- if(_videoSampling.cvTextureCacheTexture)
- {
- CFRelease(_videoSampling.cvTextureCacheTexture);
- _videoSampling.cvTextureCacheTexture = 0;
- }
-
-
-
- if(_videoSampling.cvTextureCache !=0)
- {
- if(_videoSamplingDummy.cvTextureCache)
- {
- CFRelease(_videoSamplingDummy.cvTextureCache);
- _videoSamplingDummy.cvTextureCache = 0;
- }
- _videoSamplingDummy.cvTextureCache = _videoSampling.cvTextureCache;
- _videoSampling.cvTextureCache = 0;
- }
-
- //CMVideoSampling_Uninitialize(&_videoSampling);
- }
- - (void)cleanupAssetReader
- {
- if(_reader)
- [_reader cancelReading];
- _reader = nil;
- _videoOut = nil;
- }
- - (void)cleanupPlayer
- {
- if(_player)
- {
- [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionRouteChangeNotification object:nil];
- [_player.currentItem removeObserver:self forKeyPath:@"status"];
- [_player removeObserver:self forKeyPath:@"currentItem"];
- [_player pause];
- _player = nil;
- }
- if(_playerItem)
- {
- [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
- _playerItem = nil;
- }
- }
- - (void)unloadPlayer
- {
-
- _evertoon_was_unloaded = true;
-
- [self cleanupCVTextureCache];
- [self cleanupAssetReader];
- [self cleanupPlayer];
-
-
- if(videoOutput)
- {
- videoOutput = nil;
- }
-
- if(_videoTexture != 0)
- {
-
- GLuint handle =_videoTexture;
- glDeleteTextures(1, &handle);
- _videoTexture = 0;
- }
- _videoSize = CGSizeMake(0,0);
- _duration = _curTime = kCMTimeZero;
- _curFrameTimestamp = _lastFrameTimestamp = kCMTimeZero;
- self->_playerReady = self->_assetReady = self->_itemReady = NO;
- }
- - (BOOL)loadVideo:(NSURL*)url
- {
- _evertoon_was_unloaded = false;
- _error = false;
- _audioTrackId = 0;
-
- AVURLAsset* asset = [AVURLAsset URLAssetWithURL:url options:nil];
- if(!asset) return NO;
- NSArray* requestedKeys = @[@"tracks", @"playable"];
- [asset loadValuesAsynchronouslyForKeys:requestedKeys completionHandler:
- ^{
- dispatch_async(dispatch_get_main_queue(), ^{ [self prepareAsset:asset withKeys:requestedKeys : url]; });
- }
- ];
-
-
- return YES;
- }
- - (BOOL)_play:(CustomVideoPlayerView*)view
- {
- if(!_playerReady)
- return NO;
- if(view) view.player = _player;
- else [self prepareReader];
- // do not do seekTo and setRate here, it seems that http streaming may hang sometimes if you do so. go figure
- _curFrameTimestamp = _lastFrameTimestamp = kCMTimeZero;
- [_player play];
- [self setAudioVolume:_fVolume];
- return YES;
- }
- - (BOOL)_playloop:(CustomVideoPlayerView*)view
- {
- if(!_playerReady)
- return NO;
-
-
- // do not do seekTo and setRate here, it seems that http streaming may hang sometimes if you do so. go figure
- _curFrameTimestamp = _lastFrameTimestamp = kCMTimeZero;
- [_player play];
-
-
- return YES;
- }
- - (void)setTextureID:(intptr_t)id { _textureID = id;}
- - (BOOL)playToView:(CustomVideoPlayerView*)view { return [self _play:view]; }
- - (BOOL)playToTexture { return [self _play:nil]; }
- - (BOOL)playToTextureloop { return [self _playloop:nil]; }
- - (BOOL)isPlaying { return _playerReady && _player.rate != 0.0f; }
- - (BOOL)getError { return _error;}
- - (void)pause { if(_playerReady && _player.rate != 0.0f) [_player pause]; }
- - (void)resume { if(_playerReady && _player.rate == 0.0f) [_player play]; }
- - (void)rewind { [self seekToTimestamp:kCMTimeZero]; }
- - (void)seekTo:(float)timeSeconds { [self seekToTimestamp:CMTimeMakeWithSeconds(timeSeconds, _player.currentItem.duration.timescale)]; }
- - (void)setSpeed:(float)fSpeed { [_player setRate:fSpeed ]; }
- - (void)seekToTimestamp:(CMTime)time
- {
-
-
- if (!CMTIME_IS_INVALID(time)) {
-
- [_player seekToTime: time
- toleranceBefore: kCMTimeZero
- toleranceAfter: kCMTimeZero
- completionHandler: ^(BOOL finished) {
- //
- }];
- }
-
- [self prepareReaderPos:time];
- _curFrameTimestamp = _lastFrameTimestamp = time;
-
- }
- - (intptr_t)curFrameTexture
- {
- AVURLAsset* asset = (AVURLAsset*)_playerItem.asset;
- if(![asset.URL isFileURL])
- {
- intptr_t curTex = _videoTexture;
- CMTime time = [_player currentTime];
- if(CMTimeCompare(time, _curTime) == 0 )
- return curTex;
-
-
-
-
- if(_AudioRouteWasChanged )
- {
- _AudioRouteWasChanged = false;
- [_player setRate: 1.0f]; // _player.rate = 1.0f;
- }
-
- _curTime = time;
-
- unsigned char* pixelBufferBaseAddress = NULL;
- CVPixelBufferRef pixelBuffer;
-
-
- pixelBuffer = [videoOutput copyPixelBufferForItemTime:_player.currentItem.currentTime itemTimeForDisplay:nil];
-
-
- CVPixelBufferLockBaseAddress(pixelBuffer, 0);
- pixelBufferBaseAddress = (unsigned char*)CVPixelBufferGetBaseAddress(pixelBuffer);
- size_t w = CVPixelBufferGetWidth( pixelBuffer);
- size_t h = CVPixelBufferGetHeight( pixelBuffer);
-
- CGSize size = CGSizeMake(w, h);
-
- if( _videoSize.width != size.width)
- {
- _videoSize = size;
-
- }
-
-
-
- if (NULL != pixelBufferBaseAddress)
- {
-
-
- if(UnitySelectedRenderingAPI() == apiMetal || UnitySelectedRenderingAPI() == apiOpenGLES3 || UnitySelectedRenderingAPI() == apiOpenGLES2)
- {
- if(_videoSampling.cvTextureCacheTexture)
- {
- CFRelease(_videoSampling.cvTextureCacheTexture);
- FlushCVTextureCache(_videoSampling.cvTextureCache);
- }
- _videoSampling.cvTextureCacheTexture = CreateTextureFromCVTextureCache(_videoSampling.cvTextureCache, pixelBuffer, w, h);
- if(_videoSampling.cvTextureCacheTexture)
- curTex = GetTextureFromCVTextureCache(_videoSampling.cvTextureCacheTexture);
-
-
- if(UnitySelectedRenderingAPI() == apiOpenGLES2 || UnitySelectedRenderingAPI() == apiOpenGLES3)
- {
- (glBindTexture(GL_TEXTURE_2D, (GLuint)curTex));
- (glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
- (glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
- (glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
- (glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
- (glBindTexture(GL_TEXTURE_2D, 0));
- }
-
- CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
-
- // curTex = retTex;
- }
- else
- {
- if (0 == _videoTexture) {
-
- GLuint handle;
- glGenTextures(1, &handle);
- glBindTexture(GL_TEXTURE_2D, handle);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glBindTexture(GL_TEXTURE_2D, 0);
-
- _videoTexture = handle;
- }
-
-
-
- glBindTexture(GL_TEXTURE_2D, _videoTexture);
- const size_t bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer);
-
- if (bytesPerRow / 4 == (GLsizei)w) {
-
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) w, (GLsizei) h, 0, GL_BGRA, GL_UNSIGNED_BYTE, pixelBufferBaseAddress);
- }
- else {
-
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei) w, (GLsizei) h, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
-
-
- for (int i = 0; i < _videoSize.height; ++i) {
- GLubyte* line = pixelBufferBaseAddress + i * bytesPerRow;
- glTexSubImage2D(GL_TEXTURE_2D, 0, 0, i, (GLsizei) w, 1, GL_BGRA, GL_UNSIGNED_BYTE, line);
- }
- }
-
-
- glBindTexture(GL_TEXTURE_2D, 0);
-
-
- CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
-
- curTex = _videoTexture;
- }
-
-
- }
-
- if (pixelBuffer) {
- CFRelease(pixelBuffer);
- }
-
- return curTex;
-
- }
- else
- {
- if(!_reader)
- return 0;
-
-
-
- intptr_t curTex = CMVideoSampling_LastSampledTexture(&_videoSampling);
-
- CMTime time = [_player currentTime];
- if(CMTimeCompare(time, _curTime) == 0 || _reader.status != AVAssetReaderStatusReading)
- return curTex;
-
-
-
- // if we have changed audio route and due to current category apple decided to pause playback - resume automatically
- if(_AudioRouteWasChanged )
- {
- _AudioRouteWasChanged = false;
- [_player setRate: 1.0f]; // _player.rate = 1.0f;
- }
-
-
- _curTime = time;
- while(_reader.status == AVAssetReaderStatusReading && CMTimeCompare(_curFrameTimestamp, _curTime) <= 0)
- {
- if(_cmSampleBuffer2)
- CFRelease(_cmSampleBuffer2);
-
- _cmSampleBuffer2 = _cmSampleBuffer;
-
- // TODO: properly handle ending
-
- _cmSampleBuffer = [_videoOut copyNextSampleBuffer];
- if(_cmSampleBuffer == 0)
- {
- //[self cleanupCVTextureCache];
- return 0;
- }
-
- _curFrameTimestamp = CMSampleBufferGetPresentationTimeStamp(_cmSampleBuffer);
- }
-
- if(CMTimeCompare(_lastFrameTimestamp, _curFrameTimestamp) < 0)
- {
- _lastFrameTimestamp = _curFrameTimestamp;
- size_t w, h;
- if(_cmSampleBuffer)
- curTex = CMVideoSampling_SampleBuffer(&_videoSampling, _cmSampleBuffer, &w, &h);
- _videoSize = CGSizeMake(w, h);
- }
-
- return curTex;
-
- }
-
-
- return 0;
- }
- - (BOOL)setAudioVolume:(float)volume
- {
- if(!_playerReady)
- return NO;
-
-
- if(_player != NULL)
- [_player setVolume:volume];
-
- _fVolume = volume;
-
- NSArray* arrayTracks = [_playerItem.asset tracksWithMediaType:AVMediaTypeAudio];
- NSMutableArray* params = [NSMutableArray array];
-
- for (int i=0; i < [arrayTracks count]; i++)
- {
- AVAssetTrack* assetTrackAudio = arrayTracks[i];
-
- AVMutableAudioMixInputParameters* inputParams = [AVMutableAudioMixInputParameters audioMixInputParameters];
- float trackVolume = (i ==_audioTrackId) ? volume : 0.0f;
- [inputParams setVolume:trackVolume atTime:kCMTimeZero];
- [inputParams setTrackID:[assetTrackAudio trackID]];
- [params addObject:inputParams];
- }
- AVMutableAudioMix* audioMix = [AVMutableAudioMix audioMix];
- [audioMix setInputParameters:params];
- [_playerItem setAudioMix:audioMix];
- return YES;
- }
- - (void)playerItemDidReachEnd:(NSNotification*)notification
- {
- [delegate onPlayerDidFinishPlayingVideo];
- }
- static bool _AudioRouteWasChanged = false;
- - (void)audioRouteChanged:(NSNotification*)notification
- {
- _AudioRouteWasChanged = true;
- }
- - (void)observeValueForKeyPath:(NSString*)path ofObject:(id)object change:(NSDictionary*)change context:(void*)context
- {
- BOOL reportPlayerReady = NO;
- if(context == _ObserveItemStatusContext)
- {
- AVPlayerStatus status = (AVPlayerStatus)[[change objectForKey:NSKeyValueChangeNewKey] integerValue];
- switch(status)
- {
- case AVPlayerStatusUnknown:
- break;
- case AVPlayerStatusReadyToPlay:
- {
- NSArray* video = [_playerItem.asset tracksWithMediaType:AVMediaTypeVideo];
- if([video count])
- _videoSize = [(AVAssetTrack*)[video objectAtIndex:0] naturalSize];
-
-
- _duration = [_playerItem duration];
- _assetReady = YES;
- reportPlayerReady = _itemReady;
- }
- break;
- case AVPlayerStatusFailed:
- {
- AVPlayerItem *playerItem = (AVPlayerItem*)object;
- [self reportError:playerItem.error category:"prepareAsset"];
- _error = true;
- }
- break;
- }
- }
- else if(context == _ObservePlayerItemContext)
- {
- if( [change objectForKey:NSKeyValueChangeNewKey] != (id)[NSNull null] )
- {
- _itemReady = YES;
- reportPlayerReady = _assetReady;
- }
- }
- else
- {
- [super observeValueForKeyPath:path ofObject:object change:change context:context];
- }
- if(reportPlayerReady)
- {
- _playerReady = YES;
- [delegate onPlayerReady];
- }
- }
- - (void)prepareAsset:(AVAsset*)asset withKeys:(NSArray*)requestedKeys : (NSURL *)url
- {
- if (_evertoon_was_unloaded) {
- NSLog(@"### Video already unloaded - ignoring.");
- return;
- }
-
- for(NSString* key in requestedKeys)
- {
- NSError* error = nil;
- AVKeyValueStatus keyStatus = [asset statusOfValueForKey:key error:&error];
- if(keyStatus == AVKeyValueStatusFailed)
- {
- [self reportError:error category:"prepareAsset"];
- _error = true;
- return;
- }
- }
- if(!asset.playable)
- {
-
- [self reportErrorWithString:"Item cannot be played" category:"prepareAsset"];
- _error = true;
- return;
- }
- if(_playerItem)
- {
-
- [_playerItem removeObserver:self forKeyPath:@"status"];
- [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
- _playerItem = nil;
- }
-
-
-
- _playerItem = [AVPlayerItem playerItemWithAsset:asset];
-
- [_playerItem addObserver:self forKeyPath:@"status"
- options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
- context:_ObserveItemStatusContext
- ];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:)
- name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem
- ];
- if(!_player)
- {
-
- _player = [AVPlayer playerWithPlayerItem:_playerItem];
- [_player addObserver:self forKeyPath:@"currentItem"
- options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
- context:_ObservePlayerItemContext
- ];
- [_player setAllowsExternalPlayback:NO];
- // we want to subscribe to route change notifications, for that we need audio session active
- // and in case FMOD wasnt used up to this point it is still not active
- [[AVAudioSession sharedInstance] setActive:YES error:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChanged:)
- name:AVAudioSessionRouteChangeNotification object:nil
- ];
- }
- if(_player.currentItem != _playerItem)
- [_player replaceCurrentItemWithPlayerItem:_playerItem];
- else
- [_player seekToTime:kCMTimeZero];
-
-
-
-
- }
- - (BOOL)prepareReader
- {
- if(!_playerReady)
- return NO;
- [self cleanupAssetReader];
- AVURLAsset* asset = (AVURLAsset*)_playerItem.asset;
-
- if(![asset.URL isFileURL])
- {
-
-
-
- NSDictionary *settings = @{(id) kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA)};
-
- //AVPlayerItemVideoOutput *output = [[[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:settings] autorelease];
- AVPlayerItemVideoOutput *output = [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:settings];
- videoOutput = output;
-
-
- //NSArray *videoTracks = [asset tracksWithMediaType:AVMediaTypeVideo];
- if( [_playerItem tracks] == NULL)
- {
- [self reportErrorWithString:"_playerItem tracks == null" category:"prepareReader"];
- _error = true;
- return NO;
- }
-
- if( [[_playerItem tracks] count] <= 0)
- {
- [self reportErrorWithString:"tracks count == 0" category:"prepareReader"];
- _error = true;
- return NO;
- }
-
- AVAssetTrack *videoTrack = [[[_playerItem tracks] objectAtIndex:0] assetTrack];;
- _videoSize = videoTrack.naturalSize;
- printf("\nprepareReader %d %d", (GLsizei)_videoSize.width, (GLsizei)_videoSize.height);
- _duration = [asset duration];
-
-
- NSArray * arrayTracks = [asset tracksWithMediaType:AVMediaTypeAudio];
- NSMutableArray* params = [NSMutableArray array];
-
-
- _audioTrackInfo = [arrayTracks count];
- for (int i=0; i < [arrayTracks count]; i++)
- {
- AVAssetTrack* assetTrackAudio = arrayTracks[i];
-
- AVMutableAudioMixInputParameters* inputParams = [AVMutableAudioMixInputParameters audioMixInputParameters];
- float trackVolume = i ==_audioTrackId ? 1.0f : 0.0f;
- [inputParams setVolume:trackVolume atTime:kCMTimeZero];
- [inputParams setTrackID:[assetTrackAudio trackID]];
- [params addObject:inputParams];
-
- }
-
- AVMutableAudioMix* audioMix = [AVMutableAudioMix audioMix];
- [audioMix setInputParameters:params];
-
- AVPlayerItem* item = [_player currentItem];
- [item setAudioMix:audioMix];
-
- [item addOutput:videoOutput];
-
- }
- else
- {
-
- NSError* error = nil;
- _reader = [AVAssetReader assetReaderWithAsset:_playerItem.asset error:&error];
- if(error)
- [self reportError:error category:"prepareReader"];
-
- _reader.timeRange = CMTimeRangeMake(kCMTimeZero, _duration);
- AVAssetTrack* videoTrack = [[_playerItem.asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
-
- NSDictionary* options = @{ (NSString*)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA) };
- _videoOut = [[AVAssetReaderTrackOutput alloc] initWithTrack:videoTrack outputSettings:options];
- _videoOut.alwaysCopiesSampleData = NO;
-
-
- NSArray * arrayTracks = [_playerItem.asset tracksWithMediaType:AVMediaTypeAudio];
- NSMutableArray* params = [NSMutableArray array];
-
-
- _audioTrackInfo = [arrayTracks count];
- for (int i=0; i < [arrayTracks count]; i++)
- {
- AVAssetTrack* assetTrackAudio = arrayTracks[i];
-
- AVMutableAudioMixInputParameters* inputParams = [AVMutableAudioMixInputParameters audioMixInputParameters];
- float trackVolume = i ==_audioTrackId ? 1.0f : 0.0f;
- [inputParams setVolume:trackVolume atTime:kCMTimeZero];
- [inputParams setTrackID:[assetTrackAudio trackID]];
- [params addObject:inputParams];
-
- }
-
-
- if(![_reader canAddOutput:_videoOut])
- {
- [self reportErrorWithString:"canAddOutput returned false" category:"prepareReader"];
- _error = true;
- return NO;
- }
- [_reader addOutput:_videoOut];
-
- if(![_reader startReading])
- {
- [self reportError:[_reader error] category:"prepareReader"];
- _error = true;
- return NO;
- }
-
- }
-
-
-
- [self cleanupCVTextureCache];
- CMVideoSampling_Initialize(&_videoSampling);
- return NO;
- }
- - (BOOL)prepareReaderPos : (CMTime)time
- {
- if(!_playerReady)
- return NO;
-
- [self cleanupAssetReader];
-
- AVURLAsset* asset = (AVURLAsset*)_playerItem.asset;
- if(![asset.URL isFileURL])
- {
- //[self reportErrorWithString:"non-file url. no video to texture." category:"prepareReader"];
- //return NO;
- /* NSDictionary *settings = @{(id) kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA)};
- //AVPlayerItemVideoOutput *output = [[[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:settings] autorelease];
- AVPlayerItemVideoOutput *output = [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:settings];
- videoOutput = output;
-
-
- NSArray *videoTracks = [asset tracksWithMediaType:AVMediaTypeVideo];
- // AVAssetTrack *videoTrack = videoTracks[0];
- AVAssetTrack *videoTrack = [[[_playerItem tracks] objectAtIndex:0] assetTrack];
- _videoSize = videoTrack.naturalSize;
-
- _duration = [asset duration];
-
-
-
- // ===== Audio =====
- // Get the first audio track
- NSArray * arrayTracks = [asset tracksWithMediaType:AVMediaTypeAudio];
- if (0 < [arrayTracks count]) {
-
- AVAssetTrack* assetTrackAudio = arrayTracks[0];
-
- AVMutableAudioMixInputParameters* audioInputParams = [AVMutableAudioMixInputParameters audioMixInputParameters];
- [audioInputParams setVolume:1.0f atTime:time];
- [audioInputParams setTrackID:[assetTrackAudio trackID]];
-
- NSArray* audioParams = @[audioInputParams];
- AVMutableAudioMix* audioMix = [AVMutableAudioMix audioMix];
- [audioMix setInputParameters:audioParams];
-
- AVPlayerItem* item = [_player currentItem];
- [item setAudioMix:audioMix];
-
- }
-
- [[_player currentItem] addOutput:videoOutput];*/
-
-
- }
- else
- {
- NSError* error = nil;
- _reader = [AVAssetReader assetReaderWithAsset:_playerItem.asset error:&error];
- if(error){
- [self reportError:error category:"prepareReader"];
- _error = true;
- }
-
- _reader.timeRange = CMTimeRangeMake(time, _duration);
-
-
-
- AVAssetTrack* videoTrack = [[_playerItem.asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
-
- NSDictionary* options = @{ (NSString*)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA) };
- _videoOut = [[AVAssetReaderTrackOutput alloc] initWithTrack:videoTrack outputSettings:options];
- _videoOut.alwaysCopiesSampleData = NO;
-
- if(![_reader canAddOutput:_videoOut])
- {
- [self reportErrorWithString:"canAddOutput returned false" category:"prepareReader"];
- _error = true;
- return NO;
- }
- [_reader addOutput:_videoOut];
-
- if(![_reader startReading])
- {
- [self reportError:[_reader error] category:"prepareReader"];
- _error = true;
- return NO;
- }
-
-
- }
-
-
- //[self cleanupCVTextureCache];
- //CustomCMVideoSampling_Initialize(&_videoSampling);
- return NO;
- }
- @end
|