PCSBaseViewController.m 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870
  1. //
  2. // PCSBaseViewController.m
  3. // PanoramicCameraSDK
  4. //
  5. // Created by 王昭威 on 2023/1/14.
  6. //
  7. #import "PCSBaseViewController.h"
  8. #import <AVFoundation/AVFoundation.h>
  9. #import "Masonry.h"
  10. #import "CameraManager.h"
  11. #import "AVCapturePhotoOutput+VersionAdaptor.h"
  12. #import "PCSRoundButton.h"
  13. #import "PCSModeList.h"
  14. #import "UIImage+ext.h"
  15. #import "PCSTools.h"
  16. #import "OperationNodeProtocol.h"
  17. #import "OperationNodeSingle.h"
  18. #import "OperationNodeMultiple.h"
  19. #import "OperationNodePanorama.h"
  20. #import "QuitMultipleModeAlertViewController.h"
  21. #import <CoreMotion/CoreMotion.h>
  22. #import "OperationNodeMovie.h"
  23. #import "SDKParameters.h"
  24. #import "PhotoListViewController.h"
  25. #import "CustomModalViewTransition.h"
  26. #import "MovieListViewController.h"
  27. #import "TimerLabel.h"
  28. #import "MoviePlayerViewController.h"
  29. #import "PanoramaOrientationView.h"
  30. #import "PanoramaGuideView.h"
  31. #import "Renderer.h"
  32. #import "CameraTextureRenderPass.h"
  33. #import "LenzSDKConstant.h"
  34. #import "TensorFlowWrapper.h"
  35. #import "DBManager.h"
  36. #import <Photos/Photos.h>
  37. #import "BaseViewTapGestureDelegate.h"
  38. #import "MovieListCellModel.h"
  39. #import "PreviewSingleViewController.h"
  40. #import "OperationNodeAIPanorama.h"
  41. #import "PhotoAlbumListViewController.h"
  42. #import "PhotoAlbumModel.h"
  43. //#import "LenStitcher.h"
  44. //#import <LenzStitchSDK/LenzStitchSDK.h>
  45. #import "LenzDataManager.h"
  46. #import "LenzHeader.h"
  47. #import "LenzCachedResourceModel.h"
  48. #import "LenzDataManager.h"
  49. #import "PCSPreviewViewController.h"
  50. #import "SVProgressHUD.h"
  51. #import "PCSAutherView.h"
  52. #import <LenzTensorFlowSDK/LenzTensorFlow.h>
  53. #define MODE_LIST_INDEX_2_MODE_ENUM(x) ((x))
  54. // PCS means panoramic camera sdk
  55. @interface PCSBaseViewController ()<AVCapturePhotoCaptureDelegate,
  56. AVCaptureFileOutputRecordingDelegate,
  57. AVCaptureAudioDataOutputSampleBufferDelegate,
  58. UIViewControllerTransitioningDelegate,
  59. AVCaptureVideoDataOutputSampleBufferDelegate,
  60. PhotoListViewControllerDelegate,
  61. PanoramaOrientationViewDelegate>
  62. @property (nonatomic, assign) CGFloat accX;
  63. @property (nonatomic, nullable, readonly) AVCaptureDevice* currentCamera;
  64. @property (nonatomic, nullable, readonly) AVCaptureDeviceInput* currentCameraInput;
  65. @property (nonatomic, strong) AVCaptureSession* captureSession;
  66. @property (nonatomic, strong) AVCaptureVideoDataOutput* videoDataOutput;
  67. @property (nonatomic, strong) AVCaptureMovieFileOutput* movieFileOutput;
  68. @property (nonatomic, strong) AVCapturePhotoOutput* photoOutput;
  69. @property (nonatomic, strong) AVCapturePhotoSettings* outputSettings;
  70. @property (nonatomic, copy) dispatch_queue_t videoDataQueue;
  71. @property (nonatomic, strong) AVAssetWriter* videoWriter;
  72. @property (nonatomic, strong) AVAssetWriterInput* videoWriterInput;
  73. @property (nonatomic, assign) BOOL cameraPrepared;
  74. @property (nonatomic, assign) BOOL flag;
  75. @property (nonatomic, assign) BOOL hasCache;
  76. @property (nonatomic, strong) UIView* focusView;
  77. @property (nonatomic, strong, nullable) NSTimer* recordTimer;
  78. @property (nonatomic) dispatch_source_t touchSourceTimer;
  79. @property (nonatomic) CGFloat touchTime;
  80. @property (nonatomic, strong, nullable) NSTimer* motionTimer;
  81. @property (nonatomic, strong) BaseViewTapGestureDelegate* tapDelegate;
  82. /**
  83. key: PhotographModeEnum
  84. value: subclass of OperationNodeProtocol
  85. */
  86. @property (nonatomic, strong) NSDictionary<NSNumber*, id<OperationNodeProtocol>>* operationNodes;
  87. @property (nonatomic, strong) NSArray<id<OperationNodeProtocol>>* operationNodesArray;
  88. @property (nonatomic) dispatch_semaphore_t videoStitchSemaphore;
  89. @property (nonatomic) LenzCachedResourceModel *resourceModel;
  90. @property (nonatomic) UIView *stitchView;
  91. @property (nonatomic) UIImageView *stitchImageView;
  92. @property (nonatomic) UILabel *stitchLabel;
  93. @property (nonatomic) CABasicAnimation *loadingAnimation;
  94. @property (nonatomic) BOOL isStitchBigImage;
  95. @property (nonatomic) CGFloat brightnessValue;
  96. @property (nonatomic) CMMotionManager *motionManager;
  97. @property (nonatomic) BOOL isTakePhoto;
  98. @property (nonatomic) NSLock *stitchkLock;
  99. @property (nonatomic) LenVideoStitchResult stitchResult;
  100. @property (nonatomic) NSNumber *startPitchX;
  101. @property (nonatomic) NSNumber *startRollY;
  102. @property (nonatomic) LenzTensorFlow *tensorFlow;
  103. @property (nonatomic) BOOL isContainSingleInReatinMode;
  104. @property (nonatomic) UILabel *aiPanPromtLabel;
  105. @property (nonatomic) PCSAutherView *authView;
  106. @end
  107. @implementation PCSBaseViewController
  108. #pragma mark - Life Circle
  109. - (void)dealloc{
  110. [self stopAllSensors];
  111. [[NSNotificationCenter defaultCenter] removeObserver:self];
  112. [[LenzDBManager shared] close];
  113. }
  114. - (void)awakeFromNib{
  115. [super awakeFromNib];
  116. [self setup];
  117. }
  118. - (void)viewDidLoad {
  119. [super viewDidLoad];
  120. // Do any additional setup after loading the view.
  121. [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
  122. [SVProgressHUD setMinimumDismissTimeInterval:1.5];
  123. [SVProgressHUD setMaximumDismissTimeInterval:3];
  124. [SVProgressHUD setFont:[UIFont systemFontOfSize:14]];
  125. self.tensorFlow = [[LenzTensorFlow alloc]initWithFileName:@"moire_mobilenetv2_79"];
  126. self.stitchkLock = [[NSLock alloc]init];
  127. self.totalArray = [[NSMutableArray alloc]init];
  128. self.cachesArray = [[NSMutableArray alloc]init];
  129. self.typeArray = [[NSMutableArray alloc]init];
  130. self.isContainSingleInReatinMode = NO;
  131. self.resourceModel = [[LenzCachedResourceModel alloc]init];
  132. self.motionManager = [[CMMotionManager alloc]init];
  133. self.motionManager.deviceMotionUpdateInterval = 1/5;
  134. [self.view addSubview:self.panoramaGuideView];
  135. [self panoramaOrientationViewslt:(PanoramaOrientationViewLeft)];
  136. self.panoramaGuideView.hidden = YES;
  137. [self.view addSubview:self.aiPanPromtLabel];
  138. [self.aiPanPromtLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  139. make.centerX.mas_equalTo(self.view);
  140. make.top.mas_equalTo(self.modeLabel.mas_bottom).mas_offset(20);
  141. make.width.mas_offset(240);
  142. make.height.mas_offset(20);
  143. }];
  144. [self.view addSubview:self.authView];
  145. [self.authView mas_makeConstraints:^(MASConstraintMaker *make) {
  146. make.edges.mas_offset(0);
  147. }];
  148. if (!JK_IS_IPHONE_X) {
  149. self.safeBottom.constant = 25;
  150. self.safeTop.constant = 15;
  151. }else{
  152. self.safeBottom.constant = 0;
  153. }
  154. [self.timerLabel updateWith:100];
  155. self.albumButton.layer.cornerRadius = 6;
  156. self.albumButton.clipsToBounds = YES;
  157. [self updateFlashButton];
  158. [PCSMotionManager shared];
  159. __weak typeof(self) weakself = self;
  160. [self.modeList reloadWith:self.operationNodesArray];
  161. self.modeList.indexChangedHandler = ^BOOL(NSUInteger newMode, NSUInteger oldMode, NSUInteger newIndex) {
  162. __strong typeof(weakself) strongSelf = weakself;
  163. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_CLEAR) {
  164. BOOL needAlert = NO;
  165. switch (self.mode) {
  166. case SDK_CAPTURE_MODE_CONTINUOUS:
  167. needAlert = self.resourceModel.continousArray.count;
  168. break;
  169. case SDK_CAPTURE_MODE_SINGLE:
  170. needAlert = self.resourceModel.singleArray.count;
  171. break;
  172. case SDK_CAPTURE_MODE_MOVIE:
  173. needAlert = self.resourceModel.movieArray.count;
  174. break;
  175. case SDK_CAPTURE_MODE_PANORAMA:
  176. needAlert = self.resourceModel.panoramArray.count;
  177. break;
  178. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  179. needAlert = self.resourceModel.aiPanoramArray.count;
  180. break;
  181. default:
  182. break;
  183. }
  184. if (needAlert) {
  185. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"切换模式会清除已拍摄数据,请确认" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  186. [alertController dismissViewControllerAnimated:NO completion:^{}];
  187. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  188. switch (self.mode) {
  189. case SDK_CAPTURE_MODE_CONTINUOUS: {
  190. [self.resourceModel.continousArray removeAllObjects];
  191. [self updateViewStatus];
  192. }
  193. break;
  194. case SDK_CAPTURE_MODE_SINGLE: {
  195. [self.resourceModel.singleArray removeAllObjects];
  196. [self updateViewStatus];
  197. }
  198. break;
  199. case SDK_CAPTURE_MODE_MOVIE:
  200. {
  201. [self.resourceModel.movieArray removeAllObjects];
  202. [self updateViewStatus];
  203. }
  204. break;
  205. case SDK_CAPTURE_MODE_PANORAMA:
  206. {
  207. [self.resourceModel.panoramArray removeAllObjects];
  208. [self updateViewStatus];
  209. }
  210. break;
  211. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  212. {
  213. [self.resourceModel.aiPanoramArray removeAllObjects];
  214. [self updateViewStatus];
  215. }
  216. break;
  217. default:
  218. break;
  219. }
  220. self.modeList.index = newIndex;
  221. [self.modeList updateItemsConstraints];
  222. [strongSelf modeWillChange:newMode oldIndex:oldMode];
  223. id<OperationNodeProtocol> oldModelNode = strongSelf.currentOperationNode;
  224. PhotographModeEnum mode = (PhotographModeEnum)MODE_LIST_INDEX_2_MODE_ENUM(newMode);
  225. strongSelf.mode = mode;
  226. // self.ai_fullView.hidden = !(mode == SDK_CAPTURE_MODE_PANORAMA);
  227. self.ai_fullView.hidden = YES;
  228. [strongSelf modeDidChange:newMode oldIndex:oldMode];
  229. [strongSelf updateCaptureSessionWith:oldMode];
  230. if([oldModelNode respondsToSelector:@selector(didQuit)]){
  231. [oldModelNode didQuit];
  232. }
  233. [alertController dismissViewControllerAnimated:NO completion:^{}];
  234. }];
  235. return NO;
  236. }
  237. }
  238. [strongSelf modeWillChange:newMode oldIndex:oldMode];
  239. id<OperationNodeProtocol> oldModelNode = strongSelf.currentOperationNode;
  240. PhotographModeEnum mode = (PhotographModeEnum)MODE_LIST_INDEX_2_MODE_ENUM(newMode);
  241. strongSelf.mode = mode;
  242. // self.ai_fullView.hidden = !(mode == SDK_CAPTURE_MODE_PANORAMA);
  243. self.ai_fullView.hidden = YES;
  244. [strongSelf modeDidChange:newMode oldIndex:oldMode];
  245. [strongSelf updateCaptureSessionWith:oldMode];
  246. if([oldModelNode respondsToSelector:@selector(didQuit)]){
  247. [oldModelNode didQuit];
  248. }
  249. return YES;
  250. };
  251. [self modeWillChange:[SDKParameters shared].modeIndex oldIndex:0lu];
  252. self.modeList.mode = [SDKParameters shared].modeIndex;
  253. self.mode = [SDKParameters shared].modeIndex;
  254. [self modeDidChange:[SDKParameters shared].modeIndex oldIndex:0lu];
  255. UIVisualEffectView* effectView = [[UIVisualEffectView alloc] initWithEffect: [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
  256. effectView.alpha = 0.8;
  257. effectView.effect = nil;
  258. self.effectView = effectView;
  259. [self.view insertSubview:self.effectView belowSubview:self.backButton];
  260. [self.effectView mas_makeConstraints:^(MASConstraintMaker *make) {
  261. make.edges.equalTo(self.view);
  262. }];
  263. if(!self.cameraPrepared){
  264. [self prepareCamera];
  265. }
  266. [self modeDidChange:[SDKParameters shared].modeIndex oldIndex:0lu];
  267. [self updateCaptureSessionWith:0];
  268. self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];
  269. [self.view addGestureRecognizer:self.panGesture];
  270. UIImageView* loadingImageView = [[UIImageView alloc] initWithImage:[UIImage sdkImageNamed:@"loading"]];
  271. self.loadingIndicator = loadingImageView;
  272. self.loadingIndicator.hidden = YES;
  273. [self.view addSubview:self.loadingIndicator];
  274. [loadingImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
  275. make.center.equalTo(self.view);
  276. }];
  277. self.savePhotoButton.titleLabel.textColor = [UIColor whiteColor];
  278. self.discardPhotoButton.titleLabel.textColor = [UIColor whiteColor];
  279. // [self.takePhotoButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  280. // make.centerX.equalTo(self.view);
  281. // make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
  282. // }];
  283. [self updateUIByMode];
  284. self.panoramOrientationGuideView.delegate = self;
  285. self.ablumImageView = [[UIImageView alloc]init];
  286. [self.view addSubview:self.ablumImageView];
  287. self.ablumImageView.layer.cornerRadius = 6;
  288. self.ablumImageView.layer.masksToBounds = YES;
  289. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showPreview:)];
  290. [self.ablumImageView addGestureRecognizer:tap];
  291. self.ablumImageView.userInteractionEnabled = YES;
  292. self.ablumImageView.hidden = YES;
  293. // self.ablumImageView.backgroundColor = [UIColor redColor];
  294. self.ablumImageView.contentMode = UIViewContentModeScaleAspectFill;
  295. [self.ablumImageView mas_makeConstraints:^(MASConstraintMaker *make) {
  296. make.centerY.mas_equalTo(self.takePhotoButton);
  297. make.left.mas_equalTo(20);
  298. make.width.height.mas_equalTo(60);
  299. // make.top.left.mas_equalTo(50);
  300. // make.width.height.mas_equalTo(300);
  301. }];
  302. UILongPressGestureRecognizer *ges = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressGes:)];
  303. // ges.numberOfTapsRequired = 1;
  304. ges.minimumPressDuration = 1;
  305. [self.takePhotoButton addGestureRecognizer:ges];
  306. self.timerLabel.layer.cornerRadius = 6;
  307. self.timerLabel.layer.masksToBounds = YES;
  308. [self.ai_fullView addTarget:self action:@selector(alFullViewAction:) forControlEvents:UIControlEventTouchUpInside];
  309. [self.view addSubview:self.stitchView];
  310. [self.stitchView mas_makeConstraints:^(MASConstraintMaker *make) {
  311. make.centerY.mas_equalTo(self.view);
  312. make.centerX.mas_equalTo(self.view);
  313. make.width.mas_offset(200);
  314. make.height.mas_offset(200);
  315. }];
  316. }
  317. - (PCSAutherView *)authView {
  318. if (!_authView) {
  319. _authView = [[PCSAutherView alloc]init];
  320. _authView.hidden = YES;
  321. }
  322. return _authView;
  323. }
  324. - (void)viewWillAppear:(BOOL)animated{
  325. [super viewWillAppear:animated];
  326. self.panGesture.enabled = YES;
  327. if([self.currentOperationNode respondsToSelector:@selector(updateUI)])
  328. [self.currentOperationNode updateUI];
  329. }
  330. - (void)viewDidAppear:(BOOL)animated{
  331. [super viewDidAppear:animated];
  332. if(self.cameraPrepared){
  333. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) {
  334. case AVAuthorizationStatusAuthorized:
  335. [self startCaptureSession];
  336. [[PCSMotionManager shared] startAccelerometerUpdates];
  337. break;
  338. case AVAuthorizationStatusNotDetermined:{
  339. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  340. if(granted){
  341. [self startCaptureSession];
  342. [[PCSMotionManager shared] startAccelerometerUpdates];
  343. }
  344. else{
  345. [[NSNotificationCenter defaultCenter] postNotificationName:CameraNotificationNotPermission object:self];
  346. }
  347. }];
  348. break;
  349. }
  350. case AVAuthorizationStatusDenied:{
  351. [[NSNotificationCenter defaultCenter] postNotificationName:CameraNotificationNotPermission object:self];
  352. break;
  353. }
  354. case AVAuthorizationStatusRestricted:
  355. break;
  356. default:
  357. break;
  358. }
  359. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
  360. case AVAuthorizationStatusAuthorized:
  361. [self setupMicrophone];
  362. break;
  363. case AVAuthorizationStatusNotDetermined:{
  364. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
  365. if(granted){
  366. [self setupMicrophone];
  367. }
  368. else{
  369. [[NSNotificationCenter defaultCenter] postNotificationName:MicrophoneNotificationNotPermission object:self];
  370. }
  371. }];
  372. break;
  373. }
  374. case AVAuthorizationStatusDenied:{
  375. [[NSNotificationCenter defaultCenter] postNotificationName:MicrophoneNotificationNotPermission object:self];
  376. break;
  377. }
  378. case AVAuthorizationStatusRestricted:
  379. break;
  380. default:
  381. break;
  382. }
  383. }
  384. if (![self showAuthBoth]) {
  385. if (![self showAuthorCamerIfNeed]) {
  386. [self showAudioCamerIfNeed];
  387. }
  388. }
  389. }
  390. - (void)viewWillDisappear:(BOOL)animated{
  391. [super viewWillDisappear:animated];
  392. [self stopCaptureSession];
  393. [[PCSMotionManager shared] stopAccelerometerUpdates];
  394. }
  395. - (void)updateFlashButton {
  396. __block SDKFlashModeIndex flashModel = SDK_FLASH_MODE_AUTO;
  397. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  398. if (obj.model == self.mode) {
  399. flashModel = obj.flashMode;
  400. }
  401. }];
  402. switch (flashModel) {
  403. case SDK_FLASH_MODE_AUTO:{
  404. self.outputSettings.flashMode = AVCaptureFlashModeAuto;
  405. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-auto-btn"] forState:UIControlStateNormal];
  406. break;
  407. }
  408. case SDK_FLASH_MODE_ON:{
  409. self.outputSettings.flashMode = AVCaptureFlashModeOn;
  410. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-btn"] forState:UIControlStateNormal];
  411. break;
  412. }
  413. case SDK_FLASH_MODE_OFF:{
  414. self.outputSettings.flashMode = AVCaptureFlashModeOff;
  415. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-disable-btn"] forState:UIControlStateNormal];
  416. break;
  417. }
  418. default:
  419. break;
  420. }
  421. }
  422. - (UIView *)stitchView {
  423. if (!_stitchView) {
  424. _stitchView = [[UIView alloc]init];
  425. [_stitchView addSubview:self.stitchImageView];
  426. [self.stitchImageView mas_makeConstraints:^(MASConstraintMaker *make) {
  427. make.centerX.mas_equalTo(_stitchView);
  428. make.top.mas_equalTo(0);
  429. make.width.height.mas_equalTo(68);
  430. }];
  431. [_stitchView addSubview:self.stitchLabel];
  432. [self.stitchLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  433. make.top.mas_equalTo(self.stitchImageView.mas_bottom).mas_offset(20);
  434. make.centerX.mas_equalTo(self.stitchImageView);
  435. }];
  436. _stitchView.hidden = YES;
  437. }
  438. return _stitchView;
  439. }
  440. - (UIImageView *)stitchImageView {
  441. if (!_stitchImageView) {
  442. _stitchImageView = [[UIImageView alloc]init];
  443. _stitchImageView.image = [UIImage loadNamed:@"loading"];
  444. }
  445. return _stitchImageView;
  446. }
  447. - (CABasicAnimation *)loadingAnimation {
  448. if (!_loadingAnimation) {
  449. _loadingAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
  450. _loadingAnimation.fromValue = [NSNumber numberWithFloat:0.f];
  451. _loadingAnimation.toValue = [NSNumber numberWithFloat: M_PI *2];
  452. _loadingAnimation.duration = 3;
  453. _loadingAnimation.autoreverses = NO;
  454. _loadingAnimation.fillMode = kCAFillModeForwards;
  455. _loadingAnimation.repeatCount = MAXFLOAT;
  456. }
  457. return _loadingAnimation;
  458. }
  459. - (UILabel *)aiPanPromtLabel {
  460. if (!_aiPanPromtLabel) {
  461. _aiPanPromtLabel = [[UILabel alloc]init];
  462. _aiPanPromtLabel.backgroundColor = [UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:.2];
  463. _aiPanPromtLabel.layer.cornerRadius = 6;
  464. _aiPanPromtLabel.layer.masksToBounds = YES;
  465. _aiPanPromtLabel.textColor = [UIColor whiteColor];
  466. _aiPanPromtLabel.font = [UIFont systemFontOfSize:14];
  467. _aiPanPromtLabel.text = @"请保持手机与拍摄物平行,匀速拍摄";
  468. _aiPanPromtLabel.hidden = YES;
  469. _aiPanPromtLabel.textAlignment = NSTextAlignmentCenter;
  470. }
  471. return _aiPanPromtLabel;
  472. }
  473. - (UILabel *)stitchLabel {
  474. if (!_stitchLabel) {
  475. _stitchLabel = [[UILabel alloc]init];
  476. _stitchLabel.text = @"正在拼接中,请稍等";
  477. _stitchLabel.font = [UIFont systemFontOfSize:12];
  478. _stitchLabel.textColor = [UIColor whiteColor];
  479. }
  480. return _stitchLabel;
  481. }
  482. #pragma mark - Private Method
  483. - (void)alFullViewAction:(UIButton *)button {
  484. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  485. OperationNodePanorama *pan = nil;
  486. if ([self.currentOperationNode isKindOfClass:[OperationNodePanorama class]]) {
  487. pan = self.currentOperationNode;
  488. pan.needHiddenDir = !pan.needHiddenDir;
  489. }
  490. self.panoramOrientationGuideView.hidden = pan.needHiddenDir;
  491. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  492. OperationNodeAIPanorama *aiPan = nil;
  493. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  494. aiPan = self.currentOperationNode;
  495. aiPan.needHiddenDir = !aiPan.needHiddenDir;
  496. }
  497. self.panoramOrientationGuideView.hidden = aiPan.needHiddenDir;
  498. }
  499. }
  500. - (void)showPreview:(UITapGestureRecognizer *)tap {
  501. if (self.ablumImageView.hidden) {
  502. return;
  503. }
  504. if(self.mode != SDK_CAPTURE_MODE_SINGLE) {
  505. PCSPreviewViewController *vc = [[PCSPreviewViewController alloc]init];
  506. vc.model = self.resourceModel;
  507. vc.selectIndex = self.mode;
  508. vc.dataChangeBlock = ^{
  509. [self updateViewStatus];
  510. };
  511. [self presentViewController:vc animated:YES completion:nil];
  512. } else {
  513. PreviewSingleViewController* dst = [[PreviewSingleViewController alloc]init];
  514. dst.singleModeNode = self.currentOperationNode;
  515. if (self.resourceModel.singleArray.count > 0) {
  516. LenzResourceItemModel *model = self.resourceModel.singleArray.firstObject;
  517. dst.image = model.image;
  518. }
  519. [self presentViewController:dst animated:YES completion:nil];
  520. }
  521. }
  522. + (instancetype)initWithParams:(NSDictionary *)params complete:(PCSBaseVCCompleteBLock)complete {
  523. [self parser:params];
  524. UIStoryboard* sb = [UIStoryboard storyboardWithName:[PCSTools shared].mainStoryboardName bundle:[PCSTools sdkBundle]];
  525. PCSBaseViewController *vc = (PCSBaseViewController *)[sb instantiateViewControllerWithIdentifier:@"sample"];
  526. vc.completeBlock = complete;
  527. return vc;
  528. }
  529. #pragma mark - Config param
  530. + (void)parser: (NSDictionary*)params{
  531. SDKParameters* sdkParams = [SDKParameters shared];
  532. NSString* retainedMode = params[@"dataRetainedMode"];
  533. if(retainedMode != nil){
  534. if([retainedMode isEqual:@"retain"]){
  535. sdkParams.retainedMode = SDK_DATA_RETAINED_RETAIN;
  536. }
  537. else if([retainedMode isEqual:@"clear"]){
  538. sdkParams.retainedMode = SDK_DATA_RETAINED_CLEAR;
  539. }
  540. }
  541. NSArray* arr = params[@"cameraMode"];
  542. NSDictionary<NSString*, NSNumber*>* table = @{
  543. @"continuous": @(SDK_CAPTURE_MODE_CONTINUOUS),
  544. @"single" : @(SDK_CAPTURE_MODE_SINGLE),
  545. @"video" : @(SDK_CAPTURE_MODE_MOVIE),
  546. @"panorama" : @(SDK_CAPTURE_MODE_PANORAMA),
  547. @"panoramaPlus" : @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)
  548. };
  549. NSMutableArray<NSNumber*>* modeIndiciesTable = [NSMutableArray array];
  550. NSMutableArray *mutabArray = [NSMutableArray array];
  551. [arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  552. if ([obj isKindOfClass:[NSDictionary class]]) {
  553. NSDictionary *dict = (NSDictionary *)obj;
  554. NSString *mode = dict[@"mode"];
  555. if (!table[mode]) {
  556. return;
  557. }
  558. if (idx == 0) {
  559. sdkParams.modeIndex = (SDKCaptureModeIndex)table[mode].integerValue;
  560. }
  561. [modeIndiciesTable addObject:table[mode]];
  562. SDKParametersItem *item = [[SDKParametersItem alloc]init];
  563. NSString* cameraPosition = dict[@"type"];
  564. item.model = (SDKCaptureModeIndex)table[mode].integerValue;
  565. if(cameraPosition != nil){
  566. if([cameraPosition isEqual:@"back"]){
  567. item.cameraPosition = SDK_CAMERA_PISITION_BACK;
  568. item.cameraPositionString = cameraPosition;
  569. }
  570. else if([cameraPosition isEqual:@"front"]){
  571. item.cameraPosition = SDK_CAMERA_PISITION_FRONT;
  572. item.cameraPositionString = cameraPosition;
  573. }
  574. }
  575. NSNumber* recTime = dict[@"recTime"];
  576. if(recTime != nil){
  577. item.limitRecordTime = [recTime integerValue];
  578. }
  579. item.keyFrame = dict[@"keyframe"];
  580. item.isRemake = [dict[@"isRemake"] boolValue];
  581. NSNumber *quantity = dict[@"quantity"];
  582. if (quantity) {
  583. item.quantity = [quantity integerValue];
  584. }
  585. NSNumber *quality = dict[@"quality"];
  586. if (quality) {
  587. item.quality = [quality floatValue];
  588. }
  589. NSString* flashMode = dict[@"flashMode"];
  590. if(flashMode != nil){
  591. item.flashModeString = flashMode;
  592. if([flashMode isEqualToString:@"auto"]){
  593. item.flashMode = SDK_FLASH_MODE_AUTO;
  594. }
  595. else if([flashMode isEqualToString:@"on"]){
  596. item.flashMode = SDK_FLASH_MODE_ON;
  597. }
  598. else if([flashMode isEqualToString:@"off"]){
  599. item.flashMode = SDK_FLASH_MODE_OFF;
  600. }
  601. }
  602. NSNumber* videoQualityNum = dict[@"videoQuality"];
  603. if(videoQualityNum != nil){
  604. NSInteger videoQuality = [videoQualityNum integerValue];
  605. if(videoQuality == 480){
  606. item.videoQuality = SDK_VIDEO_QUALITY_480;
  607. }
  608. else if(videoQuality == 720){
  609. item.videoQuality = SDK_VIDEO_QUALITY_720;
  610. }
  611. else if(videoQuality == 1080){
  612. item.videoQuality = SDK_VIDEO_QUALITY_1080;
  613. }
  614. else if(videoQuality == 2160){
  615. item.videoQuality = SDK_VIDEO_QUALITY_2160;
  616. }
  617. }
  618. NSNumber* showPreviewForPanorama = dict[@"showPreview"];
  619. if(showPreviewForPanorama != nil){
  620. item.showPreviewForPanorama = [showPreviewForPanorama boolValue];
  621. }
  622. [mutabArray addObject:item];
  623. }
  624. }];
  625. sdkParams.modeIndices = [modeIndiciesTable copy];
  626. [SDKParameters shared].items = mutabArray;
  627. }
  628. // 拍照界面
  629. - (void)showPreviewView: (BOOL)show{
  630. self.previewLayer.hidden = !show;
  631. self.takePhotoButton.enabled = show;
  632. self.resultImageView.hidden = show;
  633. self.backButton.hidden = !show;
  634. self.flashButton.hidden = !show;
  635. self.switchButton.hidden = !show;
  636. self.discardPhotoButton.hidden = show;
  637. self.savePhotoButton.hidden = show;
  638. }
  639. - (void)setup{
  640. // 打开数据库
  641. [[LenzDBManager shared] openSqlDataBase];
  642. [LenzDataManager creatDirectory];
  643. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  644. [[PCSTools shared] cleanDiskCache];
  645. });
  646. _mode = SDK_CAPTURE_MODE_CONTINUOUS;
  647. _captureSession = [[AVCaptureSession alloc] init];
  648. _captureSession.sessionPreset = AVCaptureSessionPresetInputPriority;
  649. _movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
  650. // _movieFileOutput.maxRecordedDuration = CMTimeMake(self.parameters.limitRecordTime, 1);
  651. // setup video data output for panoramic
  652. _videoDataQueue = dispatch_queue_create("video data", DISPATCH_QUEUE_SERIAL);
  653. _videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
  654. _videoDataOutput.alwaysDiscardsLateVideoFrames = YES;
  655. _videoDataOutput.videoSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
  656. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  657. _photoOutput = [[AVCapturePhotoOutput alloc] init];
  658. NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
  659. _outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
  660. [_photoOutput setPhotoSettingsForSceneMonitoring:_outputSettings];
  661. _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
  662. _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  663. NSMutableArray* nodesArr = [NSMutableArray array];
  664. NSMutableDictionary* nodesDic = [NSMutableDictionary dictionary];
  665. __block SDKCaptureModeIndex defaultModeIndex = SDK_CAPTURE_MODE_CONTINUOUS;
  666. NSDictionary<NSNumber*, Class>* nodeClsTable = @{
  667. @(SDK_CAPTURE_MODE_CONTINUOUS): [OperationNodeMultiple class],
  668. @(SDK_CAPTURE_MODE_SINGLE): [OperationNodeSingle class],
  669. @(SDK_CAPTURE_MODE_MOVIE): [OperationNodeMovie class],
  670. @(SDK_CAPTURE_MODE_PANORAMA): [OperationNodePanorama class],
  671. @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA): [OperationNodeAIPanorama class],
  672. };
  673. [[SDKParameters shared].modeIndices enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  674. if (idx == 0) {
  675. defaultModeIndex = (SDKCaptureModeIndex)obj.integerValue;
  676. }
  677. if(nodeClsTable[obj] != nil){
  678. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_RETAIN && obj.intValue == SDK_CAPTURE_MODE_SINGLE) {
  679. self.isContainSingleInReatinMode = YES;
  680. return;
  681. } else {
  682. id node = [[nodeClsTable[obj] alloc] initWithController: self];
  683. if ([node isKindOfClass:[OperationNodeVideoBase class]]) {
  684. OperationNodeVideoBase *base = (OperationNodeVideoBase *)node;
  685. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  686. if (obj.model == self.mode) {
  687. base.recTime = obj.limitRecordTime;
  688. }
  689. }];
  690. }
  691. [nodesArr addObject: node];
  692. nodesDic[obj] = node;
  693. }
  694. }
  695. }];
  696. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_RETAIN && nodesArr.count == 0 && self.isContainSingleInReatinMode) {
  697. // reatin模式下只有single
  698. id node = [[OperationNodeSingle alloc] initWithController: self];
  699. [nodesArr addObject: node];
  700. nodesDic[@(SDK_CAPTURE_MODE_SINGLE)] = node;
  701. defaultModeIndex = SDK_CAPTURE_MODE_SINGLE;
  702. }
  703. [SDKParameters shared].modeIndex = defaultModeIndex;
  704. _operationNodesArray = [nodesArr copy];
  705. _operationNodes = [nodesDic copy];
  706. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
  707. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
  708. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationWillChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
  709. }
  710. - (void)startMotion {
  711. if (self.motionManager.deviceMotionAvailable) {
  712. __weak typeof(self)wearSelf = self;
  713. [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
  714. if (!self.startPitchX && !self.startRollY) {
  715. self.startPitchX = @(motion.attitude.pitch * 100);
  716. self.startRollY = @(motion.attitude.roll *100);
  717. }
  718. double x = self.startPitchX.doubleValue - motion.attitude.pitch * 100;
  719. double y = self.startRollY.doubleValue - motion.attitude.roll * 100;
  720. LenVideoStitchDirction dir = (LenVideoStitchDirction)wearSelf.panoramOrientationGuideView.selectedItemIndex;
  721. if (dir == LenVideoStitchDirctionLeft || dir == LenVideoStitchDirctionRight) {
  722. if (fabs(x) < 3) {
  723. // NSLog(@"~~~~~~~~~~水平");
  724. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  725. } else {
  726. if (x > 0) {
  727. // NSLog(@"~~~~~~~~~~向下");
  728. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirDown dir:dir];
  729. } else {
  730. // NSLog(@"~~~~~~~~~~向上");
  731. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirUp dir:dir];
  732. }
  733. }
  734. } else if (dir == LenVideoStitchDirctionUp || dir == LenVideoStitchDirctionDown) {
  735. if (fabs(y) < 3) {
  736. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  737. } else {
  738. if (y > 0) {
  739. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirLeft dir:dir];
  740. } else {
  741. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirRight dir:dir];
  742. }
  743. }
  744. }
  745. }];
  746. }
  747. }
  748. - (void)stopMotion {
  749. [self.motionManager stopDeviceMotionUpdates];
  750. self.startPitchX = nil;
  751. self.startRollY = nil;
  752. LenVideoStitchDirction dir = (LenVideoStitchDirction)self.panoramOrientationGuideView.selectedItemIndex;
  753. [self.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  754. }
  755. #pragma mark - Lazy Load
  756. - (BaseViewTapGestureDelegate *)tapDelegate{
  757. if(_tapDelegate == nil){
  758. _tapDelegate = [[BaseViewTapGestureDelegate alloc] init];
  759. _tapDelegate.controller = self;
  760. }
  761. return _tapDelegate;
  762. }
  763. - (AVCaptureDevice *)currentCamera{
  764. __block AVCaptureDevice* camera = nil;
  765. [self.captureSession.inputs enumerateObjectsUsingBlock:^(__kindof AVCaptureInput * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  766. AVCaptureDeviceInput* inputDevice = obj;
  767. if([inputDevice.device hasMediaType:AVMediaTypeVideo]){
  768. camera = inputDevice.device;
  769. *stop = YES;
  770. }
  771. }];
  772. return self.currentCameraInput.device;
  773. }
  774. - (AVCaptureDeviceInput*)currentCameraInput{
  775. __block AVCaptureDeviceInput* cameraInput = nil;
  776. [self.captureSession.inputs enumerateObjectsUsingBlock:^(__kindof AVCaptureInput * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  777. AVCaptureDeviceInput* inputDevice = obj;
  778. if([inputDevice.device hasMediaType:AVMediaTypeVideo]){
  779. cameraInput = inputDevice;
  780. *stop = YES;
  781. }
  782. }];
  783. return cameraInput;
  784. }
  785. - (SDKParameters *)parameters{
  786. return [SDKParameters shared];
  787. }
  788. #pragma mark - Action
  789. - (void)focusOn: (CGPoint)point{
  790. CGPoint pt = [self.previewLayer captureDevicePointOfInterestForPoint:point];
  791. AVCaptureDevice* curr = self.currentCamera;
  792. [[CameraManager shared] focusOn:pt device:curr];
  793. [self showFocusViewAt:point];
  794. }
  795. - (void)showFocusViewAt: (CGPoint)point{
  796. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideFocusView) object:nil];
  797. if(self.focusView == nil){
  798. UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 42, 42)];
  799. imgView.image = [UIImage sdkImageNamed:@"focus"];
  800. imgView.contentMode = UIViewContentModeScaleAspectFit;
  801. self.focusView = imgView;
  802. [self.view addSubview:self.focusView];
  803. }
  804. self.focusView.hidden = NO;
  805. CABasicAnimation* flash = [CABasicAnimation animationWithKeyPath:@"opacity"];
  806. flash.duration = 0.2;
  807. flash.fromValue = @(1);
  808. flash.toValue = @(0.1);
  809. flash.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  810. flash.autoreverses = YES;
  811. flash.repeatCount = 3;
  812. [self.focusView.layer removeAnimationForKey:@"flash"];
  813. [self.focusView.layer addAnimation:flash forKey:@"flash"];
  814. self.focusView.frame = CGRectMake(point.x - 21, point.y - 21, 42, 42);
  815. [self performSelector:@selector(hideFocusView) withObject:nil afterDelay:3];
  816. }
  817. - (void)hideFocusView{
  818. [self.focusView.layer removeAnimationForKey:@"flash"];
  819. self.focusView.hidden = YES;
  820. }
  821. - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
  822. if(error != nil){
  823. return;
  824. }
  825. if(self.mode == SDK_CAPTURE_MODE_SINGLE){
  826. [self dismissViewControllerAnimated:YES completion:^{}];
  827. }
  828. else{
  829. [self startCaptureSession];
  830. [self showPreviewView:YES];
  831. }
  832. }
  833. - (AVCaptureVideoOrientation)videoOrientation{
  834. UIDeviceOrientation curr = UIDeviceOrientationUnknown;
  835. return [self videoOrientation:&curr];
  836. }
  837. - (AVCaptureVideoOrientation)videoOrientation:(UIDeviceOrientation*)currentDeviceOrientation{
  838. return [[PCSMotionManager shared] videoOrientation:currentDeviceOrientation];;
  839. }
  840. - (void)takeStillPhoto:(AVCaptureVideoPreviewLayer*)previewLayer {
  841. if (![self showAuthBoth]) {
  842. if ([self showAuthorCamerIfNeed] || [self showAudioCamerIfNeed]) {
  843. return;
  844. }
  845. } else {
  846. return;
  847. }
  848. AVCaptureConnection *connection = [self.photoOutput connectionWithMediaType:AVMediaTypeVideo];
  849. if(connection == nil){
  850. // [self showAlertForAuthorization];
  851. return;
  852. }
  853. if (connection.supportsVideoOrientation) {
  854. // 根据motion设置照片方向
  855. AVCaptureVideoOrientation videoOrientation = [self videoOrientation];
  856. connection.videoMirrored = self.currentCamera == [CameraManager shared].front;
  857. connection.videoOrientation = videoOrientation;
  858. }
  859. // 创建 AVCapturePhotoSettings
  860. AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettings];
  861. if ([self.photoOutput.availablePhotoCodecTypes containsObject:AVVideoCodecTypeJPEG]) {
  862. NSDictionary *format = @{AVVideoCodecKey: AVVideoCodecTypeJPEG};
  863. photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:format];
  864. // NSLog(@"-----:%ld",(long)self.currentCameraInput.device.position);
  865. if (self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  866. photoSettings.flashMode = self.outputSettings.flashMode;
  867. }
  868. photoSettings.previewPhotoFormat = @{
  869. (NSString*)kCVPixelBufferPixelFormatTypeKey : photoSettings.availablePreviewPhotoPixelFormatTypes.firstObject,
  870. (NSString*)kCVPixelBufferWidthKey: @(160),
  871. (NSString*)kCVPixelBufferHeightKey: @(160),
  872. };
  873. }
  874. photoSettings.autoStillImageStabilizationEnabled = YES;
  875. // 拍照
  876. [self.photoOutput capturePhotoWithSettings:photoSettings delegate:self];
  877. }
  878. #pragma mark - Notification
  879. - (void)orientationWillChange: (NSNotification*)noti{
  880. NSLog(@"orientationWillChange");
  881. }
  882. - (void)willEnterForeground: (NSNotification*)noti{
  883. // if(self.broken){
  884. // [self.player play];
  885. // self.broken = NO;
  886. // }
  887. }
  888. //UIBackgroundTaskIdentifier _bgTaskToken;
  889. - (void)willEnterBackground: (NSNotification*)noti{
  890. if([self.currentOperationNode conformsToProtocol:@protocol(OperationNodeBackgroundProtocol)]){
  891. id<OperationNodeBackgroundProtocol> obj = self.currentOperationNode;
  892. if ([obj respondsToSelector:@selector(willEnterBackground:)]) {
  893. [obj willEnterBackground:noti];
  894. }
  895. }
  896. }
  897. - (void)orientationDidChange: (NSNotification*)noti{
  898. NSLog(@"orientationDidChange");
  899. if([self.currentOperationNode respondsToSelector:@selector(stop)])
  900. [self.currentOperationNode stop];
  901. }
  902. #pragma mark - alert
  903. - (void)showAlertForAuthorizationWithText: (NSString*)text{
  904. [QuitMultipleModeAlertViewController show:self title:@"" text:text leftBtnTitle:@"取消" rightBtnTitle:@"确认" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  905. [alertController dismissViewControllerAnimated:YES completion:^{
  906. // [self dismissViewControllerAnimated:YES completion:^{
  907. //
  908. // }];
  909. }];
  910. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  911. [alertController dismissViewControllerAnimated:YES completion:^{
  912. NSURL* url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  913. if(url != nil){
  914. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
  915. // NSLog(succ)
  916. }];
  917. }
  918. }];
  919. }];
  920. }
  921. - (void)showAlertForAuthorization{
  922. [self showAlertForAuthorizationWithText:@"请在系统设置里打开摄像机访问权限后重试"];
  923. }
  924. - (BOOL)showAuthBoth {
  925. __block BOOL showVideoAlert = NO;
  926. AVAuthorizationStatus staus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  927. switch (staus) {
  928. case AVAuthorizationStatusDenied:{
  929. showVideoAlert = YES;
  930. break;
  931. }
  932. default:
  933. showVideoAlert = NO;
  934. break;
  935. }
  936. __block BOOL showAlert = NO;
  937. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
  938. case AVAuthorizationStatusDenied:{
  939. showAlert = YES;
  940. break;
  941. }
  942. default:
  943. showAlert = NO;
  944. break;
  945. }
  946. if (showVideoAlert && showAlert) {
  947. [self.authView showAutherWith:PCSAuthPhoneAndMir];
  948. return YES;
  949. }
  950. return NO;
  951. }
  952. - (BOOL)showAuthorCamerIfNeed {
  953. __block BOOL showAlert = NO;
  954. AVAuthorizationStatus staus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  955. switch (staus) {
  956. case AVAuthorizationStatusDenied:{
  957. [self.authView showAutherWith:PCSAuthPhone];
  958. // [self showAlertForAuthorizationWithText:@"请在系统设置里打开摄像机访问权限后重试"];
  959. showAlert = YES;
  960. break;
  961. }
  962. default:
  963. showAlert = NO;
  964. break;
  965. }
  966. return showAlert;
  967. }
  968. - (BOOL)showAudioCamerIfNeed {
  969. __block BOOL showAlert = NO;
  970. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
  971. case AVAuthorizationStatusDenied:{
  972. [self.authView showAutherWith:PCSAuthMir];
  973. // [self showAlertForAuthorizationWithText:@"请在系统设置里打开麦克风访问权限后重试"];
  974. showAlert = YES;
  975. break;
  976. }
  977. default:
  978. showAlert = NO;
  979. break;
  980. }
  981. return showAlert;
  982. }
  983. #pragma mark - Capture
  984. - (void)takeStillPhoto{
  985. [self takeStillPhoto:self.previewLayer];
  986. }
  987. - (BOOL)startRecording{
  988. if (![self showAuthBoth]) {
  989. if ([self showAuthorCamerIfNeed] || [self showAudioCamerIfNeed]) {
  990. return NO;
  991. }
  992. } else {
  993. return NO;
  994. }
  995. if(self.movieFileOutput.isRecording){
  996. return NO;
  997. }
  998. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  999. if (obj.model == self.mode) {
  1000. self.movieFileOutput.maxRecordedDuration = CMTimeMake(obj.limitRecordTime, 1);
  1001. }
  1002. }];
  1003. [self.recordTimer invalidate];
  1004. dispatch_async(dispatch_get_main_queue(), ^{
  1005. self.recordTimer = [NSTimer timerWithTimeInterval:0.2 repeats:YES block:^(NSTimer * _Nonnull timer) {
  1006. [self.timerLabel updateWith:self.movieFileOutput.recordedDuration.value / self.movieFileOutput.recordedDuration.timescale];
  1007. }];
  1008. [[NSRunLoop currentRunLoop] addTimer:self.recordTimer forMode:NSDefaultRunLoopMode];
  1009. });
  1010. NSURL* tmpMovieFileUrl = [NSURL fileURLWithPath:[LenzDataManager moviePath]];
  1011. AVCaptureConnection* connection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
  1012. if(connection == nil){
  1013. // [self showAlertForAuthorization];
  1014. return NO;
  1015. }
  1016. UIDeviceOrientation currOrientation = UIDeviceOrientationUnknown;
  1017. connection.videoOrientation = [self videoOrientation:&currOrientation];
  1018. AVCaptureDevice* camera = self.currentCamera;
  1019. [camera lockForConfiguration:nil];
  1020. if ([camera hasFlash] && self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  1021. if (self.outputSettings.flashMode == AVCaptureFlashModeOff) {
  1022. [camera setTorchMode:AVCaptureTorchModeOff];
  1023. } else if (self.outputSettings.flashMode == AVCaptureFlashModeOn) {
  1024. [camera setTorchMode:AVCaptureTorchModeOn];
  1025. } else {
  1026. [camera setTorchMode:AVCaptureTorchModeAuto];
  1027. }
  1028. }
  1029. [camera unlockForConfiguration];
  1030. self.thumbnailOritaionByCurrentVideoOrientation = [UIImage imageOrientationByDeviceOrientation:currOrientation isFrontCamera:camera == [CameraManager shared].front];
  1031. [self.movieFileOutput startRecordingToOutputFileURL: tmpMovieFileUrl recordingDelegate:self];
  1032. return YES;
  1033. }
  1034. - (void)stopRecording{
  1035. [self.movieFileOutput stopRecording];
  1036. AVCaptureDevice* camera = self.currentCamera;
  1037. [camera lockForConfiguration:nil];
  1038. if ([camera hasFlash] && self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  1039. [camera setTorchMode:AVCaptureTorchModeOff];
  1040. }
  1041. [camera unlockForConfiguration];
  1042. [self.recordTimer invalidate];
  1043. self.recordTimer = nil;
  1044. }
  1045. - (BOOL)startVideoDataOutputing{
  1046. [[NSNotificationCenter defaultCenter] removeObserver:self name:PCS_NotificationNameOrientationDidChange object:nil];
  1047. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:PCS_NotificationNameOrientationDidChange object:nil];
  1048. UIDeviceOrientation deviceOrientation = UIDeviceOrientationPortrait;
  1049. AVCaptureVideoOrientation orientation = [self videoOrientation:&deviceOrientation];
  1050. CGFloat degree = 0;
  1051. AVCaptureDevice* camera = self.currentCamera;
  1052. CameraManager* cameraMgr = [CameraManager shared];
  1053. BOOL isFront = camera == cameraMgr.front;
  1054. BOOL isLandscape = NO;
  1055. // 前摄像头需要镜像一下
  1056. switch (deviceOrientation) {
  1057. case UIDeviceOrientationPortrait:
  1058. degree = 0;
  1059. break;
  1060. case UIDeviceOrientationLandscapeRight:
  1061. degree = isFront ? 90 : -90;
  1062. isLandscape = YES;
  1063. break;
  1064. case UIDeviceOrientationPortraitUpsideDown:
  1065. degree = 180;
  1066. break;
  1067. case UIDeviceOrientationLandscapeLeft:
  1068. degree = isFront ? -90 : 90;
  1069. isLandscape = YES;
  1070. break;
  1071. default:
  1072. break;
  1073. }
  1074. __block BOOL ret = NO;
  1075. dispatch_sync(self.videoDataQueue, ^{
  1076. if(self.videoDataOutput.sampleBufferDelegate != nil){
  1077. return;
  1078. }
  1079. if([self configureVideoWritter]){
  1080. AVCaptureConnection *connection = [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo];
  1081. if(connection == nil){
  1082. // [self showAlertForAuthorization];
  1083. return;
  1084. }
  1085. [connection setVideoOrientation:orientation];
  1086. CGFloat aspect = isFront ? cameraMgr.frontAspect : cameraMgr.backAspect;
  1087. aspect = isLandscape ? 1.0 / aspect : aspect;
  1088. [self.videoDataOutput setSampleBufferDelegate:self queue:self.videoDataQueue];
  1089. ret = YES;
  1090. }
  1091. });
  1092. return ret;
  1093. }
  1094. - (PanoramaGuideView *)panoramaGuideView{
  1095. if (_panoramaGuideView == nil) {
  1096. _panoramaGuideView = [[PanoramaGuideView alloc]init];
  1097. _panoramaGuideView.hidden = YES;
  1098. }
  1099. return _panoramaGuideView;;
  1100. }
  1101. - (void)stopVideoDataOutputing{
  1102. [self.motionTimer invalidate];
  1103. self.motionTimer = nil;
  1104. [[NSNotificationCenter defaultCenter] removeObserver:self name:PCS_NotificationNameOrientationDidChange object:nil];
  1105. dispatch_async(self.videoDataQueue, ^{
  1106. [self.videoDataOutput setSampleBufferDelegate:nil queue:nil];
  1107. [Renderer shared].cameraPass.texture = nil;
  1108. });
  1109. [self stopMotion];
  1110. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  1111. [self updateViewStatus];
  1112. }
  1113. - (void)updateViewStatusWhenStitchSave:(BOOL)isSaveIng {
  1114. dispatch_async(dispatch_get_main_queue(), ^{
  1115. self.stitchView.hidden = !isSaveIng;
  1116. if (self.stitchView.hidden) {
  1117. [self.stitchImageView.layer removeAnimationForKey:@"loadingAnimation"];
  1118. } else {
  1119. [self.stitchImageView.layer addAnimation:self.loadingAnimation forKey:@"loadingAnimation"];
  1120. }
  1121. self.flashButton.hidden = isSaveIng;
  1122. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1123. self.panoramOrientationGuideView.hidden = YES;
  1124. self.ai_fullView.hidden = YES;
  1125. self.panoramaGuideView.hidden = YES;
  1126. } else {
  1127. self.panoramOrientationGuideView.hidden = isSaveIng;
  1128. // self.ai_fullView.hidden = isSaveIng;
  1129. self.ai_fullView.hidden = YES;
  1130. self.panoramaGuideView.hidden = isSaveIng;
  1131. }
  1132. self.modeList.hidden = isSaveIng;
  1133. self.savePhotoButton.hidden = isSaveIng;
  1134. self.takePhotoButton.hidden = isSaveIng;
  1135. // self.switchButton.hidden = isSaveIng;
  1136. self.discardPhotoButton.hidden = isSaveIng;
  1137. self.backButton.hidden = !isSaveIng;
  1138. self.ablumImageView.hidden = isSaveIng;
  1139. // self.timerLabel.hidden = isSaveIng;
  1140. });
  1141. }
  1142. - (void)updateViewStatusWhenStitchFail {
  1143. dispatch_async(dispatch_get_main_queue(), ^{
  1144. self.stitchView.hidden = YES;
  1145. self.flashButton.hidden = NO;
  1146. self.modeList.hidden = NO;
  1147. self.savePhotoButton.hidden = NO;
  1148. self.takePhotoButton.hidden = NO;
  1149. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1150. self.ai_fullView.hidden = YES;
  1151. self.panoramOrientationGuideView.hidden = YES;
  1152. self.panoramaGuideView.hidden = YES;
  1153. } else {
  1154. // self.ai_fullView.hidden = NO;
  1155. self.ai_fullView.hidden = YES;
  1156. self.panoramOrientationGuideView.hidden = NO;
  1157. self.panoramaGuideView.hidden = NO;
  1158. }
  1159. // self.switchButton.hidden = isSaveIng;
  1160. self.discardPhotoButton.hidden = NO;
  1161. self.backButton.hidden = YES;
  1162. self.ablumImageView.hidden = NO;
  1163. [self.takePhotoButton setImage:[UIImage loadNamed:@"take-photo-btn"] forState:UIControlStateNormal];
  1164. // self.timerLabel.hidden = isSaveIng;
  1165. });
  1166. }
  1167. - (BOOL)getStitchBigImageIfNeed {
  1168. BOOL isSuccess = NO;
  1169. NSString *s = [LenStitcher getCurrentPanoramaShow];
  1170. if (s.length) {
  1171. isSuccess = YES;
  1172. }
  1173. return isSuccess;
  1174. }
  1175. - (BOOL)configureVideoWritter{
  1176. // setup asset writter for the video data output
  1177. NSURL* tmpMovieFileUrl = [NSURL fileURLWithPath:[[PCSTools shared].tmpPath stringByAppendingPathComponent:@"video-data-tmp-file.mov"] isDirectory:NO];
  1178. NSError* err = nil;
  1179. [[NSFileManager defaultManager] removeItemAtURL:tmpMovieFileUrl error:nil];
  1180. self.videoWriter = [[AVAssetWriter alloc] initWithURL:tmpMovieFileUrl fileType:AVFileTypeQuickTimeMovie error:&err];
  1181. if(err != nil){
  1182. NSLog(@"%@", err);
  1183. self.videoWriter = nil;
  1184. return NO;
  1185. }
  1186. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1187. if (obj.model == self.mode) {
  1188. NSDictionary* settings = [NSDictionary dictionaryWithObjectsAndKeys:
  1189. AVVideoCodecTypeH264, AVVideoCodecKey,
  1190. [NSNumber numberWithInteger: obj.resolution.width], AVVideoWidthKey,
  1191. [NSNumber numberWithInteger: obj.resolution.height], AVVideoHeightKey,
  1192. nil];
  1193. self.videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:settings];
  1194. }
  1195. }];
  1196. self.videoWriterInput.expectsMediaDataInRealTime = YES;
  1197. [self.videoWriter addInput:self.videoWriterInput];
  1198. return YES;
  1199. }
  1200. - (void)prepareCamera{
  1201. if (self.cameraPrepared) {
  1202. return;
  1203. }
  1204. __block AVCaptureDevice* device = nil;
  1205. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1206. if (obj.model == self.mode) {
  1207. device = obj.cameraPosition == SDK_CAMERA_PISITION_BACK ? [CameraManager shared].back : [CameraManager shared].front;
  1208. }
  1209. }];
  1210. if (device == nil) {
  1211. self.cameraPrepared = false;
  1212. return;
  1213. }
  1214. NSError* error;
  1215. AVCaptureDeviceInput* input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
  1216. if(error != nil){
  1217. self.cameraPrepared = false;
  1218. return;
  1219. }
  1220. [self.captureSession beginConfiguration];
  1221. if([self.captureSession canAddInput:input]){
  1222. [self.captureSession addInput:input];
  1223. }
  1224. else{
  1225. return;
  1226. }
  1227. self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
  1228. self.previewLayer.frame = self.view.layer.bounds;
  1229. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  1230. [self.view.layer insertSublayer:self.previewLayer atIndex:0u];
  1231. if([self.captureSession canAddOutput:self.photoOutput]){
  1232. [self.captureSession addOutput:self.photoOutput];
  1233. }
  1234. if([self.captureSession canAddOutput:self.movieFileOutput]){
  1235. [self.captureSession addOutput:self.movieFileOutput];
  1236. }
  1237. [self.captureSession commitConfiguration];
  1238. self.cameraPrepared = YES;
  1239. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1240. if (obj.model == self.mode) {
  1241. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:obj.resolution.height];
  1242. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:obj.resolution.height];
  1243. }
  1244. }];
  1245. [self updatePreViewLayer];
  1246. }
  1247. #pragma mark - Gesture
  1248. - (void)tapGestureHandler: (UITapGestureRecognizer*)gesture{
  1249. switch(gesture.state){
  1250. case UIGestureRecognizerStateBegan:{
  1251. break;
  1252. }
  1253. case UIGestureRecognizerStateChanged:{
  1254. break;
  1255. }
  1256. case UIGestureRecognizerStateEnded:{
  1257. CGPoint pt = [gesture locationInView:self.view];
  1258. [self focusOn:pt];
  1259. break;
  1260. }
  1261. case UIGestureRecognizerStateCancelled:{
  1262. break;
  1263. }
  1264. default:
  1265. break;
  1266. }
  1267. }
  1268. - (void)panGestureHandler: (UIPanGestureRecognizer*)gesture{
  1269. switch(gesture.state){
  1270. case UIGestureRecognizerStateBegan:{
  1271. break;
  1272. }
  1273. case UIGestureRecognizerStateChanged:{
  1274. if(self.flag){
  1275. return;
  1276. }
  1277. self.flag = YES;
  1278. CGPoint translation = [gesture translationInView:self.view];
  1279. [self.modeList updateIndexByTanslation:translation];
  1280. break;
  1281. }
  1282. case UIGestureRecognizerStateEnded:{
  1283. self.flag = NO;
  1284. break;
  1285. }
  1286. case UIGestureRecognizerStateCancelled:{
  1287. self.flag = NO;
  1288. break;
  1289. }
  1290. default:
  1291. self.flag = NO;
  1292. break;
  1293. }
  1294. }
  1295. #pragma mark - orientation
  1296. - (UIInterfaceOrientationMask)supportedInterfaceOrientations{
  1297. return UIInterfaceOrientationMaskPortrait;
  1298. }
  1299. - (void)updateUIByMode{
  1300. self.albumButton.hidden = YES;
  1301. self.numberOfImagesLabel.hidden = YES;
  1302. self.modeLabel.text = self.currentOperationNode.modeTitleString;
  1303. // self.ai_fullView.hidden = !(self.mode == SDK_CAPTURE_MODE_PANORAMA);
  1304. self.ai_fullView.hidden = YES;
  1305. self.panGesture.enabled = YES;
  1306. // self.controller.savePhotoButton.hidden = !self.hasCache;
  1307. // self.controller.discardPhotoButton.hidden = !self.hasCache;
  1308. //
  1309. // self.controller.albumButton.hidden = !self.hasCache;
  1310. // self.controller.backButton.hidden = self.hasCache;
  1311. if([self.currentOperationNode respondsToSelector:@selector(updateUI)]){
  1312. [self.currentOperationNode updateUI];
  1313. }
  1314. [self updatePreViewLayer];
  1315. }
  1316. - (void)updatePreViewLayer {
  1317. CGFloat width = [UIScreen mainScreen].bounds.size.width;
  1318. CGFloat height = [UIScreen mainScreen].bounds.size.height;
  1319. switch (self.mode) {
  1320. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1321. self.switchButton.hidden = NO;
  1322. self.panoramaGuideView.hidden = YES;
  1323. self.panoramOrientationGuideView.hidden = YES;
  1324. self.previewLayer.frame = CGRectMake(0, (height - width*4/3)/2, width, width*4/3);
  1325. }
  1326. break;
  1327. case SDK_CAPTURE_MODE_SINGLE: {
  1328. self.switchButton.hidden = NO;
  1329. self.panoramaGuideView.hidden = YES;
  1330. self.panoramOrientationGuideView.hidden = YES;
  1331. self.previewLayer.frame = CGRectMake(0, (height - width*4/3)/2, width, width*4/3);
  1332. }
  1333. break;
  1334. case SDK_CAPTURE_MODE_MOVIE: {
  1335. self.switchButton.hidden = NO;
  1336. self.panoramaGuideView.hidden = YES;
  1337. self.panoramOrientationGuideView.hidden = YES;
  1338. self.previewLayer.frame = self.view.layer.bounds;
  1339. }
  1340. break;
  1341. case SDK_CAPTURE_MODE_PANORAMA: {
  1342. self.switchButton.hidden = YES;
  1343. self.panoramaGuideView.hidden = NO;
  1344. self.panoramOrientationGuideView.hidden = NO;
  1345. self.previewLayer.frame = self.view.layer.bounds;
  1346. }
  1347. break;
  1348. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  1349. self.switchButton.hidden = YES;
  1350. self.panoramaGuideView.hidden = YES;
  1351. self.panoramOrientationGuideView.hidden = YES;
  1352. self.previewLayer.frame = self.view.layer.bounds;
  1353. }
  1354. break;
  1355. default:
  1356. break;
  1357. }
  1358. }
  1359. - (void)modeWillChange: (NSUInteger)newIndex oldIndex: (NSUInteger)oldIndex{
  1360. if(newIndex >= INT_MAX){
  1361. return;
  1362. }
  1363. [self.currentOperationNode willQuitOnCompletion:^() {}];
  1364. }
  1365. - (void)modeDidChange: (NSUInteger)newIndex oldIndex: (NSUInteger)oldIndex{
  1366. if(newIndex >= INT_MAX){
  1367. return;
  1368. }
  1369. // self.modeList.userInteractionEnabled = NO;
  1370. // [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]
  1371. if(self.effectView.superview != nil){
  1372. // self.effectView.effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
  1373. [UIView animateWithDuration:0.5 animations:^{
  1374. self.effectView.effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
  1375. }];
  1376. }
  1377. // dispatch_async(dispatch_get_global_queue(0, 0), ^{
  1378. if(newIndex == SDK_CAPTURE_MODE_SINGLE || newIndex == SDK_CAPTURE_MODE_CONTINUOUS){
  1379. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1380. if (obj.model == self.mode) {
  1381. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:obj.resolution.height];
  1382. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:obj.resolution.height];
  1383. }
  1384. }];
  1385. }
  1386. else{
  1387. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1388. if (obj.model == self.mode) {
  1389. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:obj.videoResolution.height];
  1390. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:obj.videoResolution.height];
  1391. }
  1392. }];
  1393. }
  1394. // dispatch_sync(dispatch_get_main_queue(), ^{
  1395. // self.modeList.userInteractionEnabled = YES;
  1396. self.effectView.effect = nil;
  1397. // });
  1398. // });
  1399. [self updateUIByMode];
  1400. [self switchDevicePositionBack];
  1401. [self updateNumberLabel];
  1402. }
  1403. - (void)updateCaptureSessionWith:(NSInteger)oldIndex {
  1404. PhotographModeEnum oldModeEnum = (PhotographModeEnum)(oldIndex);
  1405. if((self.mode == SDK_CAPTURE_MODE_PANORAMA || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)
  1406. && oldModeEnum != SDK_CAPTURE_MODE_PANORAMA
  1407. && oldModeEnum != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA){
  1408. if([self.captureSession canAddOutput:self.videoDataOutput]){
  1409. [self.captureSession addOutput:self.videoDataOutput];
  1410. [self.captureSession removeOutput:self.movieFileOutput];
  1411. }
  1412. }
  1413. else if((self.mode == SDK_CAPTURE_MODE_MOVIE)
  1414. && (oldModeEnum == SDK_CAPTURE_MODE_PANORAMA
  1415. || oldModeEnum == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)){
  1416. if([self.captureSession canAddOutput:self.movieFileOutput]){
  1417. [self.captureSession addOutput:self.movieFileOutput];
  1418. [self.captureSession removeOutput:self.videoDataOutput];
  1419. }
  1420. }
  1421. }
  1422. - (void)setupMicrophone{
  1423. NSError* audioError = nil;
  1424. AVCaptureDevice* audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
  1425. AVCaptureDeviceInput* audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&audioError];
  1426. if(audioError == nil){
  1427. AVCaptureAudioDataOutput* audioOutput = [[AVCaptureAudioDataOutput alloc] init];
  1428. [audioOutput setSampleBufferDelegate:self queue:dispatch_get_global_queue(0, 0)];
  1429. if([self.captureSession canAddInput:audioInput]){
  1430. [self.captureSession addInput:audioInput];
  1431. }
  1432. if([self.captureSession canAddOutput:audioOutput]){
  1433. [self.captureSession addOutput:audioOutput];
  1434. }
  1435. }
  1436. }
  1437. - (UIStatusBarStyle)preferredStatusBarStyle{
  1438. return UIStatusBarStyleLightContent;
  1439. }
  1440. #pragma mark 方向调用的代理
  1441. - (void)panoramaOrientationViewslt:(PanoramaOrientationViewDirectionEnum)direction{
  1442. // NSLog(@"方向%ld",direction);
  1443. self.panoramaGuideView.hidden = NO;
  1444. // self.ai_fullView.hidden = NO;
  1445. // [LenStitcher videoResetPath];
  1446. [UIView animateWithDuration:0.25 animations:^{
  1447. [self.panoramaGuideView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1448. switch (direction) {
  1449. case PanoramaOrientationViewLeft:
  1450. case PanoramaOrientationViewRight:
  1451. {
  1452. make.left.right.offset(0);
  1453. make.centerY.mas_equalTo(self.view);
  1454. make.height.mas_equalTo(PanoramaGuideViewWOrH);
  1455. }
  1456. break;
  1457. case PanoramaOrientationViewUp:
  1458. case PanoramaOrientationViewDown:
  1459. {
  1460. make.centerX.mas_equalTo(self.view);
  1461. make.width.mas_equalTo(PanoramaGuideViewWOrH);
  1462. make.bottom.mas_equalTo(self.panoramOrientationGuideView.mas_top).offset(-25);
  1463. make.top.mas_equalTo(self.timerLabel.mas_bottom).offset(15);
  1464. }
  1465. break;
  1466. case PanoramaOrientationViewAny: {
  1467. self.panoramaGuideView.hidden = YES;
  1468. // self.ai_fullView.hidden = YES;
  1469. }
  1470. break;
  1471. default:
  1472. break;
  1473. }
  1474. }];
  1475. if (self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1476. [self.panoramaGuideView setNeedsLayout];
  1477. [self.panoramaGuideView layoutIfNeeded];
  1478. }
  1479. } completion:^(BOOL finished) {
  1480. [self.panoramaGuideView direction:direction];
  1481. }];
  1482. }
  1483. - (void)stopAllSensors{
  1484. [self.captureSession stopRunning];
  1485. [[PCSMotionManager shared] stopAccelerometerUpdates];
  1486. }
  1487. #pragma mark - session
  1488. - (void)turnTorchOff{
  1489. AVCaptureDevice* currentDevice = self.currentCamera;
  1490. if(currentDevice == nil || !currentDevice.hasTorch){
  1491. return;
  1492. }
  1493. NSError* error;
  1494. if(error == nil){
  1495. [currentDevice lockForConfiguration:&error];
  1496. currentDevice.torchMode = AVCaptureTorchModeOff;
  1497. [currentDevice unlockForConfiguration];
  1498. }
  1499. }
  1500. - (void)stopCaptureSession{
  1501. [self turnTorchOff];
  1502. if (self.captureSession.isRunning) {
  1503. [self.captureSession stopRunning];
  1504. }
  1505. }
  1506. - (void)startCaptureSession{
  1507. if (!self.cameraPrepared) {
  1508. [self prepareCamera];
  1509. }
  1510. if (self.cameraPrepared && (!self.captureSession.isRunning)) {
  1511. [self.captureSession startRunning];
  1512. }
  1513. }
  1514. #pragma mark - Btn call back
  1515. -(IBAction)switchCameraTapped:(id)sender
  1516. {
  1517. if(self.captureSession == nil){
  1518. return;
  1519. }
  1520. AVCaptureDeviceInput* currInput = self.currentCameraInput;
  1521. if(currInput == nil){
  1522. return;
  1523. }
  1524. AVCaptureDevice* currentDevice = currInput.device;
  1525. AVCaptureDevice *newCamera = nil;
  1526. if(currentDevice.position == AVCaptureDevicePositionBack){
  1527. newCamera = [CameraManager shared].front;
  1528. }
  1529. else if(currentDevice.position == AVCaptureDevicePositionFront){
  1530. newCamera = [CameraManager shared].back;
  1531. }
  1532. else{
  1533. return;
  1534. }
  1535. [self.captureSession beginConfiguration];
  1536. if(currentDevice.hasTorch){
  1537. NSError* error;
  1538. [currentDevice lockForConfiguration:&error];
  1539. currentDevice.torchMode = AVCaptureTorchModeOff;
  1540. [currentDevice unlockForConfiguration];
  1541. }
  1542. [self.captureSession removeInput:currInput];
  1543. self.flashButton.hidden = !newCamera.hasFlash;
  1544. NSError *err = nil;
  1545. AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
  1546. if(newVideoInput == nil || err != nil){
  1547. NSLog(@"Error creating capture device input: %@", err.localizedDescription);
  1548. }
  1549. else if([self.captureSession canAddInput:newVideoInput]){
  1550. [self.captureSession addInput:newVideoInput];
  1551. }
  1552. [self.captureSession commitConfiguration];
  1553. }
  1554. - (void)switchDevicePositionBack {
  1555. if(self.captureSession == nil ||
  1556. (self.mode != SDK_CAPTURE_MODE_PANORAMA && self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)){
  1557. return;
  1558. }
  1559. AVCaptureDeviceInput* currInput = self.currentCameraInput;
  1560. if(currInput == nil){
  1561. return;
  1562. }
  1563. AVCaptureDevice* currentDevice = currInput.device;
  1564. AVCaptureDevice *newCamera = nil;
  1565. if(currentDevice.position == AVCaptureDevicePositionBack){
  1566. return;
  1567. }
  1568. if(currentDevice.position == AVCaptureDevicePositionFront){
  1569. newCamera = [CameraManager shared].back;
  1570. }
  1571. [self.captureSession beginConfiguration];
  1572. if(currentDevice.hasTorch){
  1573. NSError* error;
  1574. [currentDevice lockForConfiguration:&error];
  1575. currentDevice.torchMode = AVCaptureTorchModeOff;
  1576. [currentDevice unlockForConfiguration];
  1577. }
  1578. [self.captureSession removeInput:currInput];
  1579. NSError *err = nil;
  1580. AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
  1581. if(newVideoInput == nil || err != nil){
  1582. NSLog(@"Error creating capture device input: %@", err.localizedDescription);
  1583. } else if([self.captureSession canAddInput:newVideoInput]){
  1584. [self.captureSession addInput:newVideoInput];
  1585. }
  1586. [self.captureSession commitConfiguration];
  1587. }
  1588. - (void)takePhotoButtonTouchUpInside:(id)sender{
  1589. self.takePhotoButton.enabled = NO;
  1590. if (self.outputSettings.flashMode == AVCaptureFlashModeOn && (self.mode == SDK_CAPTURE_MODE_SINGLE || self.mode == SDK_CAPTURE_MODE_CONTINUOUS || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)) {
  1591. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1592. self.takePhotoButton.enabled = YES;
  1593. });
  1594. } else {
  1595. dispatch_async(dispatch_get_main_queue(), ^{
  1596. self.takePhotoButton.enabled = YES;
  1597. });
  1598. }
  1599. if(![self.currentOperationNode respondsToSelector:@selector(enable)] || self.currentOperationNode.enable){
  1600. if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  1601. __block SDKParametersItem *videoItems = nil;
  1602. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1603. if (obj.model == self.mode) {
  1604. videoItems = obj;
  1605. }
  1606. }];
  1607. if (videoItems.quantity > 0 && self.resourceModel.movieArray.count >= videoItems.quantity) {
  1608. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"最多录制%ld条视频", videoItems.quantity]];
  1609. return;
  1610. }
  1611. }
  1612. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1613. OperationNodeAIPanorama *aiPan = nil;
  1614. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  1615. aiPan = self.currentOperationNode;
  1616. if (!aiPan.isRecording) {
  1617. aiPan.AIType = OperationAITypeTap;
  1618. }
  1619. }
  1620. }
  1621. [self.currentOperationNode takePhotoButtonTouched];
  1622. if (self.mode == SDK_CAPTURE_MODE_PANORAMA && !self.isVideoStitchStopedWhenRecording) {
  1623. [LenStitcher videoResetPath];
  1624. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1625. [self.resourceModel.panoramArray addObject:itemModel];
  1626. [self startMotion];
  1627. }
  1628. }
  1629. }
  1630. - (void)longPressGes:(UILongPressGestureRecognizer *)ges {
  1631. switch (ges.state) {
  1632. case UIGestureRecognizerStateBegan:
  1633. {
  1634. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1635. OperationNodeAIPanorama *aiPan = nil;
  1636. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  1637. // self.videoStitchSemaphore = dispatch_semaphore_create(1);
  1638. [LenStitcher videoResetPath];
  1639. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1640. [self.resourceModel.aiPanoramArray addObject:itemModel];
  1641. [self startMotion];
  1642. aiPan = self.currentOperationNode;
  1643. // self.touchTime = 0;
  1644. aiPan.AIType = OperationAITypeLongPress;
  1645. [self.currentOperationNode takePhotoButtonTouched];
  1646. }
  1647. }
  1648. }
  1649. break;
  1650. case UIGestureRecognizerStateEnded:
  1651. break;
  1652. default:
  1653. break;
  1654. }
  1655. }
  1656. - (void)takePhotoButtonTouchDownInside:(id)sender{
  1657. }
  1658. - (void)flashButtonTouchUpInside:(id)sender{
  1659. AVCaptureDevice* currentDevice = self.currentCamera;
  1660. if(currentDevice == nil || !currentDevice.hasFlash){
  1661. return;
  1662. }
  1663. NSError* error = nil;
  1664. [currentDevice lockForConfiguration:&error];
  1665. if(error != nil){
  1666. return;
  1667. }
  1668. if(self.outputSettings.flashMode == AVCaptureFlashModeOn){
  1669. self.outputSettings.flashMode = AVCaptureFlashModeAuto;
  1670. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-auto-btn"] forState:UIControlStateNormal];
  1671. }
  1672. else if(self.outputSettings.flashMode == AVCaptureFlashModeAuto){
  1673. self.outputSettings.flashMode = AVCaptureFlashModeOff;
  1674. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-disable-btn"] forState:UIControlStateNormal];
  1675. }
  1676. else{
  1677. self.outputSettings.flashMode = AVCaptureFlashModeOn;
  1678. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-btn"] forState:UIControlStateNormal];
  1679. }
  1680. [currentDevice unlockForConfiguration];
  1681. }
  1682. - (void)backButtonTouchUpInside:(id)sender{
  1683. if (!self.stitchView.hidden) {
  1684. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"图片拼接中,返回会清空正在拼接的数据" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1685. [alertController dismissViewControllerAnimated:NO completion:^{}];
  1686. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1687. [self updateViewStatusWhenStitchSave:NO];
  1688. [alertController dismissViewControllerAnimated:NO completion:^{
  1689. // [self dismissViewControllerAnimated:YES completion:^{}];
  1690. }];
  1691. }];
  1692. } else {
  1693. [self dismissViewControllerAnimated:YES completion:^{}];
  1694. }
  1695. }
  1696. - (void)makeResData:(NSMutableArray <LenzResourceItemModel *> *)array {
  1697. [array enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1698. }];
  1699. }
  1700. - (void)savePhotoButtonTouchUpInside:(id)sender{
  1701. //待优化
  1702. NSMutableArray *res = [NSMutableArray array];
  1703. __block NSInteger idIndex = 1;
  1704. [self.resourceModel.singleArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1705. idIndex += idx;
  1706. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1707. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1708. dict[@"path"] = obj.path;
  1709. dict[@"cameraMode"] = obj.cameraMode;
  1710. dict[@"cameraType"] = obj.cameraType;
  1711. dict[@"isRemake"] = @(obj.isRemake);
  1712. [res addObject:dict];
  1713. }];
  1714. [self.resourceModel.continousArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1715. idIndex += idx;
  1716. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1717. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1718. dict[@"path"] = obj.path;
  1719. dict[@"cameraMode"] = obj.cameraMode;
  1720. dict[@"cameraType"] = obj.cameraType;
  1721. dict[@"isRemake"] = @(obj.isRemake);
  1722. [res addObject:dict];
  1723. }];
  1724. [self.resourceModel.movieArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1725. idIndex += idx;
  1726. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1727. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1728. dict[@"path"] = obj.path;
  1729. dict[@"cameraMode"] = obj.cameraMode;
  1730. dict[@"cameraType"] = obj.cameraType;
  1731. dict[@"isRemake"] = @(obj.isRemake);
  1732. [res addObject:dict];
  1733. }];
  1734. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1735. if (obj.path.length) {
  1736. idIndex += idx;
  1737. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1738. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1739. dict[@"path"] = obj.path;
  1740. dict[@"cameraMode"] = obj.cameraMode;
  1741. dict[@"cameraType"] = obj.cameraType;
  1742. dict[@"isRemake"] = @(obj.isRemake);
  1743. NSMutableArray *keyFrame = [NSMutableArray array];
  1744. [obj.keyFrame enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1745. [keyFrame addObject:obj];
  1746. }];
  1747. dict[@"keyFrame"] = keyFrame;
  1748. [res addObject:dict];
  1749. }
  1750. }];
  1751. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1752. if (obj.path.length) {
  1753. idIndex += idx;
  1754. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1755. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1756. dict[@"path"] = obj.path;
  1757. dict[@"cameraMode"] = obj.cameraMode;
  1758. dict[@"cameraType"] = obj.cameraType;
  1759. dict[@"isRemake"] = @(obj.isRemake);
  1760. NSMutableArray *keyFrame = [NSMutableArray array];
  1761. [obj.keyFrame enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1762. [keyFrame addObject:obj];
  1763. }];
  1764. dict[@"keyFrame"] = keyFrame;
  1765. [res addObject:dict];
  1766. }
  1767. }];
  1768. if (self.completeBlock) {
  1769. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1770. dict[@"code"] = @(200);
  1771. dict[@"message"] = @"成功";
  1772. dict[@"data"] = res;
  1773. self.completeBlock(dict);
  1774. [self dismissViewControllerAnimated:YES completion:^{
  1775. }];
  1776. }
  1777. // self.panGesture.enabled = YES;
  1778. // // Access has not been determined.
  1779. // [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  1780. //
  1781. // dispatch_async(dispatch_get_main_queue(), ^{
  1782. // if (status == PHAuthorizationStatusAuthorized) {
  1783. // // Access has been granted.
  1784. // [self.currentOperationNode save];
  1785. // }
  1786. // else {
  1787. // // Access has been denied.
  1788. // [self showAlertForAuthorizationWithText:@"请设置相册权限后重试"];
  1789. // }
  1790. // });
  1791. // }];
  1792. }
  1793. - (void)discardPhotoResultButtonTouchUpInside:(id)sender{
  1794. self.panGesture.enabled = YES;
  1795. // if([self.currentOperationNode respondsToSelector:@selector(discardPhotoResultButtonTouchUpInside)]){
  1796. // [self.currentOperationNode discardPhotoResultButtonTouchUpInside];
  1797. // }
  1798. NSString *title = @"返回会清空已拍摄数据,请确认!";
  1799. // if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  1800. // title = @"返回会清空已拍摄视频,请确认!";
  1801. // } else if (self.mode == SDK_CAPTURE_MODE_PANORAMA || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1802. // title = @"返回会清空已拼接图片,请确认!";
  1803. // }
  1804. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:title leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1805. [alertController dismissViewControllerAnimated:NO completion:^{}];
  1806. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1807. // if (self.mode == SDK_CAPTURE_MODE_CONTINUOUS) {
  1808. [self.resourceModel.continousArray removeAllObjects];
  1809. // } else if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  1810. [self.resourceModel.movieArray removeAllObjects];
  1811. // } else if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  1812. [self.resourceModel.panoramArray removeAllObjects];
  1813. // } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1814. [self.resourceModel.aiPanoramArray removeAllObjects];
  1815. // }
  1816. [self updateViewStatus];
  1817. [alertController dismissViewControllerAnimated:NO completion:^{
  1818. }];
  1819. }];
  1820. }
  1821. - (void)albumButtonTouchUpInside:(id)sender{
  1822. [self performSegueWithIdentifier:@"show-photoalbum" sender:nil];
  1823. // if([self.currentOperationNode respondsToSelector:@selector(segueForAlbum)]){
  1824. // [self performSegueWithIdentifier:self.currentOperationNode.segueForAlbum sender:nil];
  1825. // }
  1826. }
  1827. - (__kindof id<OperationNodeProtocol>)currentOperationNode{
  1828. // NSLog(@"======:%u",self.mode);
  1829. // NSLog(@"------:%@",self.operationNodes);
  1830. return self.operationNodes[@(self.mode)];
  1831. }
  1832. - (void)updateNumberLabel {
  1833. self.aiPanPromtLabel.hidden = YES;
  1834. switch (self.mode) {
  1835. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1836. if (self.resourceModel.continousArray.count > 0) {
  1837. self.numberOfImagesLabel.hidden = NO;
  1838. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已连拍%ld张", self.resourceModel.continousArray.count];
  1839. } else {
  1840. self.numberOfImagesLabel.hidden = YES;
  1841. }
  1842. }
  1843. break;
  1844. case SDK_CAPTURE_MODE_MOVIE:{
  1845. if (self.resourceModel.movieArray.count > 0) {
  1846. self.numberOfImagesLabel.hidden = NO;
  1847. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍视频%ld条", self.resourceModel.movieArray.count];
  1848. } else {
  1849. self.numberOfImagesLabel.hidden = YES;
  1850. }
  1851. }
  1852. break;
  1853. case SDK_CAPTURE_MODE_PANORAMA:
  1854. {
  1855. if (self.resourceModel.panoramArray.count > 0) {
  1856. self.numberOfImagesLabel.hidden = NO;
  1857. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拼接%ld张", self.resourceModel.panoramArray.count];
  1858. } else {
  1859. self.numberOfImagesLabel.hidden = YES;
  1860. }
  1861. }
  1862. break;
  1863. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  1864. {
  1865. self.aiPanPromtLabel.hidden = NO;
  1866. if (self.resourceModel.aiPanoramArray.count > 0) {
  1867. self.numberOfImagesLabel.hidden = NO;
  1868. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍摄%ld张", self.resourceModel.aiPanoramArray.count];
  1869. } else {
  1870. self.numberOfImagesLabel.text = @"轻点拍照,长按录制";
  1871. self.numberOfImagesLabel.hidden = NO;
  1872. }
  1873. }
  1874. break;
  1875. default:
  1876. self.numberOfImagesLabel.hidden = YES;
  1877. break;
  1878. }
  1879. }
  1880. - (void)savePhotoWith:(NSData *)data isRemake:(BOOL)isRemake{
  1881. UIImage *image = [[UIImage alloc] initWithData:data];
  1882. NSString *path = [LenzDataManager saveImageWith:data mode:self.mode];
  1883. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1884. itemModel.path = path;
  1885. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1886. if (obj.model == self.mode) {
  1887. itemModel.cameraType = obj.cameraPositionString;
  1888. }
  1889. }];
  1890. itemModel.mode = self.mode;
  1891. itemModel.image = image;
  1892. itemModel.isRemake = isRemake;
  1893. switch (self.mode) {
  1894. case SDK_CAPTURE_MODE_CONTINUOUS:{
  1895. [self.resourceModel.continousArray addObject:itemModel];
  1896. }
  1897. break;
  1898. case SDK_CAPTURE_MODE_SINGLE: {
  1899. [self.resourceModel.singleArray addObject:itemModel];
  1900. }
  1901. break;
  1902. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  1903. [self.resourceModel.aiPanoramArray addObject:itemModel];
  1904. }
  1905. break;
  1906. default:
  1907. break;
  1908. }
  1909. self.resourceModel.lastIndex = self.mode;
  1910. [self updateViewStatus];
  1911. // [self.cachesArray addObject:image];
  1912. //
  1913. // [self.typeArray addObject:@"photo"];
  1914. //
  1915. // [self.totalArray addObject:image];
  1916. //
  1917. // self.capturedImage = image;
  1918. [self.currentOperationNode triggered];
  1919. if(self.mode == SDK_CAPTURE_MODE_SINGLE){
  1920. // self.panGesture.enabled = NO;
  1921. [self stopCaptureSession];
  1922. [self performSegueWithIdentifier:@"preview_single" sender:nil];
  1923. // [self showPreviewView:NO];
  1924. }
  1925. else if(self.mode == SDK_CAPTURE_MODE_CONTINUOUS){
  1926. self.discardPhotoButton.hidden = NO;
  1927. self.savePhotoButton.hidden = NO;
  1928. }
  1929. self.resultImageView.image = image;
  1930. }
  1931. #pragma mark 相机单拍,和连拍的代理
  1932. - (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
  1933. NSData* imageData = [photo fileDataRepresentation];
  1934. if (imageData == nil){
  1935. NSLog(@"%s", "unable to create image data");
  1936. return;
  1937. }
  1938. UIImage *image = [[UIImage alloc] initWithData:imageData];
  1939. BOOL isRemake = [self.tensorFlow remake:image];
  1940. __block BOOL needCheckRemake = NO;
  1941. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1942. if (obj.model == self.mode) {
  1943. needCheckRemake = obj.isRemake;
  1944. }
  1945. }];
  1946. if (isRemake && needCheckRemake) {
  1947. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"检测到该图片为翻拍,是否继续使用?" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1948. [alertController dismissViewControllerAnimated:YES completion:nil];
  1949. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1950. [alertController dismissViewControllerAnimated:YES completion:nil];
  1951. [self savePhotoWith:imageData isRemake:isRemake];
  1952. }];
  1953. } else {
  1954. [self savePhotoWith:imageData isRemake:isRemake];
  1955. }
  1956. }
  1957. - (void)updateViewStatus {
  1958. dispatch_async(dispatch_get_main_queue(), ^{
  1959. UIImage *image = nil;
  1960. NSMutableArray *continousMutArray = [NSMutableArray array];
  1961. [self.resourceModel.continousArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1962. if (obj.path && obj.image) {
  1963. [continousMutArray addObject:obj];
  1964. }
  1965. }];
  1966. self.resourceModel.continousArray = continousMutArray;
  1967. NSMutableArray *singleMutArray = [NSMutableArray array];
  1968. [self.resourceModel.singleArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1969. if (obj.path && obj.image) {
  1970. [singleMutArray addObject:obj];
  1971. }
  1972. }];
  1973. self.resourceModel.singleArray = singleMutArray;
  1974. NSMutableArray *movieMutArray = [NSMutableArray array];
  1975. [self.resourceModel.movieArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1976. if (obj.path && obj.image) {
  1977. [movieMutArray addObject:obj];
  1978. }
  1979. }];
  1980. self.resourceModel.movieArray = movieMutArray;
  1981. NSMutableArray *panoramMutArray = [NSMutableArray array];
  1982. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1983. if (obj.path && obj.image) {
  1984. [panoramMutArray addObject:obj];
  1985. }
  1986. }];
  1987. self.resourceModel.panoramArray = panoramMutArray;
  1988. NSMutableArray *aiPanoramMutArray = [NSMutableArray array];
  1989. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1990. if (obj.path && obj.image) {
  1991. [aiPanoramMutArray addObject:obj];
  1992. }
  1993. }];
  1994. self.resourceModel.aiPanoramArray = aiPanoramMutArray;
  1995. switch (self.resourceModel.lastIndex) {
  1996. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1997. if (self.resourceModel.continousArray.count > 0) {
  1998. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1999. image = model.image;
  2000. } else {
  2001. if (self.resourceModel.singleArray.count > 0) {
  2002. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2003. image = model.image;
  2004. } else if (self.resourceModel.movieArray.count > 0) {
  2005. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2006. image = model.image;
  2007. } else if (self.resourceModel.panoramArray.count > 0) {
  2008. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2009. image = model.image;
  2010. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2011. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2012. image = model.image;
  2013. }
  2014. }
  2015. }
  2016. break;
  2017. case SDK_CAPTURE_MODE_SINGLE:{
  2018. if (self.resourceModel.singleArray.count > 0) {
  2019. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2020. image = model.image;
  2021. } else {
  2022. if (self.resourceModel.continousArray.count > 0) {
  2023. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2024. image = model.image;
  2025. } else if (self.resourceModel.movieArray.count > 0) {
  2026. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2027. image = model.image;
  2028. } else if (self.resourceModel.panoramArray.count > 0) {
  2029. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2030. image = model.image;
  2031. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2032. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2033. image = model.image;
  2034. }
  2035. }
  2036. }
  2037. break;
  2038. case SDK_CAPTURE_MODE_MOVIE:{
  2039. if (self.resourceModel.movieArray.count > 0) {
  2040. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2041. image = model.image;
  2042. } else {
  2043. if (self.resourceModel.singleArray.count > 0) {
  2044. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2045. image = model.image;
  2046. } else if (self.resourceModel.continousArray.count > 0) {
  2047. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2048. image = model.image;
  2049. } else if (self.resourceModel.panoramArray.count > 0) {
  2050. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2051. image = model.image;
  2052. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2053. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2054. image = model.image;
  2055. }
  2056. }
  2057. }
  2058. break;
  2059. case SDK_CAPTURE_MODE_PANORAMA:{
  2060. if (self.resourceModel.panoramArray.count > 0) {
  2061. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2062. image = model.image;
  2063. } else {
  2064. if (self.resourceModel.singleArray.count > 0) {
  2065. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2066. image = model.image;
  2067. } else if (self.resourceModel.movieArray.count > 0) {
  2068. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2069. image = model.image;
  2070. } else if (self.resourceModel.continousArray.count > 0) {
  2071. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2072. image = model.image;
  2073. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2074. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2075. image = model.image;
  2076. }
  2077. }
  2078. }
  2079. break;
  2080. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:{
  2081. if (self.resourceModel.aiPanoramArray.count > 0) {
  2082. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2083. image = model.image;
  2084. } else {
  2085. if (self.resourceModel.singleArray.count > 0) {
  2086. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2087. image = model.image;
  2088. } else if (self.resourceModel.movieArray.count > 0) {
  2089. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2090. image = model.image;
  2091. } else if (self.resourceModel.panoramArray.count > 0) {
  2092. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2093. image = model.image;
  2094. } else if (self.resourceModel.continousArray.count > 0) {
  2095. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2096. image = model.image;
  2097. }
  2098. }
  2099. }
  2100. break;
  2101. default:
  2102. break;
  2103. }
  2104. if (image) {
  2105. self.ablumImageView.image = image;
  2106. self.ablumImageView.hidden = NO;
  2107. self.discardPhotoButton.hidden = NO;
  2108. self.savePhotoButton.hidden = NO;
  2109. self.backButton.hidden = YES;
  2110. } else {
  2111. self.ablumImageView.image = nil;
  2112. self.ablumImageView.hidden = YES;
  2113. self.discardPhotoButton.hidden = YES;
  2114. self.savePhotoButton.hidden = YES;
  2115. self.backButton.hidden = NO;
  2116. }
  2117. [self updateNumberLabel];
  2118. });
  2119. }
  2120. #pragma mark - AVCaptureFileOutputRecordingDelegate
  2121. - (void)captureOutput:(AVCaptureFileOutput *)output didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections error:(NSError *)error{
  2122. //视频录制
  2123. BOOL recordedSuccessfully = YES;
  2124. // A problem occurred: Find out if the recording was successful.
  2125. if(error.code == AVErrorMaximumDurationReached){
  2126. NSLog(@"%@", [error localizedDescription]);
  2127. }
  2128. else if (error.code == AVErrorDiskFull){
  2129. NSLog(@"%@", [error localizedDescription]);
  2130. dispatch_async(dispatch_get_main_queue(), ^{
  2131. [[NSNotificationCenter defaultCenter] postNotificationName:LenzSDKNotificationDiskIsFull object:error];
  2132. });
  2133. }
  2134. else if (error.code == AVErrorSessionWasInterrupted){
  2135. NSLog(@"%@", [error localizedDescription]);
  2136. }
  2137. id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
  2138. if (value) {
  2139. recordedSuccessfully = [value boolValue];
  2140. [self.recordTimer invalidate];
  2141. self.recordTimer = nil;
  2142. }
  2143. if(!recordedSuccessfully){
  2144. return;
  2145. }
  2146. OperationNodeMovie *node = nil;
  2147. if ([self.currentOperationNode isKindOfClass:[OperationNodeMovie class]]) {
  2148. node = (OperationNodeMovie *)self.currentOperationNode;
  2149. if (node.isRecording) {
  2150. [self.currentOperationNode takePhotoButtonTouched];
  2151. }
  2152. }
  2153. // NSString *path = [LenzDataManager saveVideoUrl:outputFileURL model:self.mode];
  2154. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  2155. itemModel.path = outputFileURL.absoluteString;
  2156. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2157. if (obj.model == self.mode) {
  2158. itemModel.cameraType = obj.cameraPositionString;
  2159. }
  2160. }];
  2161. itemModel.mode = self.mode;
  2162. itemModel.image = [self videoFrameImageWith:outputFileURL];
  2163. [self.resourceModel.movieArray addObject:itemModel];
  2164. self.resourceModel.lastIndex = self.mode;
  2165. // self.recordedFileUrl = outputFileURL;
  2166. // [self.typeArray addObject:@"movie"];
  2167. [self updateViewStatus];
  2168. [self.timerLabel updateWith:0];
  2169. dispatch_async(dispatch_get_main_queue(), ^{
  2170. [self.currentOperationNode triggered];
  2171. self.thumbnailOritaionByCurrentVideoOrientation = UIImageOrientationUp;
  2172. });
  2173. }
  2174. - (BOOL)encodeFrame:(CMSampleBufferRef) sampleBuffer{
  2175. if (CMSampleBufferDataIsReady(sampleBuffer)) {
  2176. if (self.videoWriter.status == AVAssetWriterStatusUnknown) {
  2177. CMTime startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
  2178. [self.videoWriter startWriting];
  2179. [self.videoWriter startSessionAtSourceTime:startTime];
  2180. }
  2181. if (self.videoWriter.status == AVAssetWriterStatusFailed) {
  2182. NSLog(@"writer error %@", self.videoWriter.error.localizedDescription);
  2183. return NO;
  2184. }
  2185. if (self.videoWriterInput.readyForMoreMediaData) {
  2186. [self.videoWriterInput appendSampleBuffer:sampleBuffer];
  2187. return YES;
  2188. }
  2189. }
  2190. return NO;
  2191. }
  2192. #pragma mark - AVCaptureAudioDataOutputSampleBufferDelegate
  2193. #pragma mark - UIViewControllerTransitioningDelegate
  2194. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
  2195. return [[CustomModalViewTransitionPresent alloc] init];
  2196. }
  2197. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
  2198. return [[CustomModalViewTransitionDismiss alloc] init];
  2199. }
  2200. #pragma mark - PhotoListViewControllerDelegate
  2201. //删除视频
  2202. - (void)deleteMovie: (MovieListCellModel*)model completion: (DeleteImageCompletionCallBackType)completion{
  2203. for (int i = 0; i < self.totalArray.count; i ++) {
  2204. UIImage *image = self.totalArray[i];
  2205. if (image == (UIImage *)model.movieModel.thumbnail) {
  2206. [self.totalArray removeObjectAtIndex:i];
  2207. [self.typeArray removeObjectAtIndex:i];
  2208. break;;
  2209. }
  2210. }
  2211. // id<OperationNodeProtocol> curr = self.currentOperationNode;
  2212. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2213. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2214. [curr deleteCacheForKey:model.movieModel.fileUrl.path completion:completion];
  2215. }
  2216. }
  2217. //连拍删除
  2218. - (void)deleteImage:(UIImage *)image completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2219. // id<OperationNodeProtocol> curr = self.currentOperationNode;
  2220. for (int i = 0; i < self.totalArray.count; i ++) {
  2221. UIImage *img = self.totalArray[i];
  2222. if (img == image) {
  2223. [self.totalArray removeObjectAtIndex:i];
  2224. [self.typeArray removeObjectAtIndex:i];
  2225. break;;
  2226. }
  2227. }
  2228. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2229. if([curr respondsToSelector:@selector(deleteCacheForImage:completion:)]){
  2230. [curr deleteCacheForImage:image completion:completion];
  2231. }
  2232. }
  2233. - (void)deleteImageWithName:(NSString *)name completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2234. id<OperationNodeProtocol> curr = self.currentOperationNode;
  2235. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2236. [curr deleteCacheForKey:name completion:completion];
  2237. }
  2238. }
  2239. #pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate
  2240. - (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
  2241. @autoreleasepool {
  2242. if (connection == [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo]) {
  2243. [self.stitchkLock lock];
  2244. // dispatch_semaphore_wait(self.videoStitchSemaphore, DISPATCH_TIME_FOREVER);
  2245. OperationNodeVideoBase *base = nil;
  2246. if ([self.currentOperationNode isKindOfClass:[OperationNodeVideoBase class]]) {
  2247. base = (OperationNodeVideoBase *)self.currentOperationNode;
  2248. }
  2249. if (self.isVideoStitchStopedWhenRecording &&
  2250. (self.stitchResult != LenVideoStitchResultFail && self.stitchResult != LenVideoStitchResultStitchFail)) {
  2251. [self updateViewStatusWhenStitchSave:YES];
  2252. self.isStitchBigImage = YES;
  2253. }
  2254. [LenStitcher videoStitchWith:sampleBuffer
  2255. dirction:(LenVideoStitchDirction)self.panoramOrientationGuideView.selectedItemIndex
  2256. isStop:self.isVideoStitchStopedWhenRecording
  2257. complete:^(LenVideoStitchResult result, LenVideoStitchNeedSave needSave) {
  2258. self.stitchResult = result;
  2259. self.isVideoStitchStopedWhenRecording = NO;
  2260. UIImage *image = [LenStitcher getCurrentPanoramaShowImage];
  2261. LenzResourceItemModel *model = nil;
  2262. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2263. model = self.resourceModel.panoramArray.lastObject;
  2264. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2265. model = self.resourceModel.aiPanoramArray.lastObject;
  2266. }
  2267. if (!image || !model) {
  2268. [self.stitchkLock unlock];
  2269. return;
  2270. }
  2271. if (result == LenVideoStitchResultSuccess) {
  2272. dispatch_async(dispatch_get_main_queue(), ^{
  2273. if (self.isStitchBigImage) {
  2274. //保存大图拼接路径
  2275. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2276. if (obj.model == self.mode) {
  2277. model.cameraType = obj.cameraPositionString;
  2278. }
  2279. }];
  2280. model.mode = self.mode;
  2281. if ([LenStitcher getCurrentPanoramaShow]) {
  2282. model.image = image;
  2283. model.path = [LenStitcher getCurrentPanoramaShow];
  2284. }
  2285. [self updateViewStatusWhenStitchSave:NO];
  2286. self.isStitchBigImage = NO;
  2287. [self.panoramaGuideView clearImage];
  2288. [self updateViewStatus];
  2289. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  2290. } else {
  2291. if (base.isRecording) {
  2292. __block BOOL keyFrame = NO;
  2293. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2294. if (obj.model == self.mode) {
  2295. keyFrame = obj.keyFrame;
  2296. }
  2297. }];
  2298. if (needSave && keyFrame) {
  2299. NSString *path = [LenzDataManager saveImageWith:UIImageJPEGRepresentation(image, .6) mode:self.mode];
  2300. // itemModel.path = path;
  2301. if (path) {
  2302. [model.keyFrame addObject:path];
  2303. }
  2304. }
  2305. if (self.panoramOrientationGuideView.selectedItemIndex != PanoramaOrientationViewAny) {
  2306. [self.panoramaGuideView showImageWith:image dir:self.panoramOrientationGuideView.selectedItemIndex];
  2307. } else {
  2308. self.ablumImageView.hidden = NO;
  2309. self.ablumImageView.image = image;
  2310. }
  2311. }
  2312. }
  2313. self.resourceModel.lastIndex = self.mode;
  2314. });
  2315. } else {
  2316. if (!base.isRecording) {
  2317. // [self removeLastStich];
  2318. //停止拼接,移除保存中 非success数据
  2319. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2320. NSMutableArray *array = [NSMutableArray array];
  2321. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2322. if (obj.path.length) {
  2323. [array addObject:obj];
  2324. }
  2325. }];
  2326. self.resourceModel.panoramArray = array;
  2327. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2328. NSMutableArray *array = [NSMutableArray array];
  2329. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2330. if (obj.path.length) {
  2331. [array addObject:obj];
  2332. }
  2333. }];
  2334. self.resourceModel.aiPanoramArray = array;
  2335. }
  2336. [self updateViewStatus];
  2337. [self.stitchkLock unlock];
  2338. return;
  2339. }
  2340. if (result == LenVideoStitchResultFail || result == LenVideoStitchResultStitchFail) {
  2341. if (result == LenVideoStitchResultFail) {
  2342. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接失败,流程结束"];
  2343. } else {
  2344. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接大图失败,流程结束"];
  2345. }
  2346. self.isVideoStitchStopedWhenRecording = NO;
  2347. // base.isRecording = NO;
  2348. dispatch_async(dispatch_get_main_queue(), ^{
  2349. [base takePhotoButtonTouched];
  2350. [self stopMotion];
  2351. // [self takePhotoButtonTouchUpInside:[NSObject new]];
  2352. [self removeLastStich];
  2353. [self updateViewStatusWhenStitchFail];
  2354. [self.panoramaGuideView clearImage];
  2355. [self updateViewStatus];
  2356. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  2357. });
  2358. [SVProgressHUD dismissWithDelay:3 completion:^{
  2359. }];
  2360. } else if(result == LenVideoStitchResultSlowMore) {
  2361. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"目标物较少,请对准目标物低速且匀速拍摄"];
  2362. } else if (result == LenVideoStitchResultSlow) {
  2363. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"目标物较少,请对准目标物低速且匀速拍摄"];
  2364. } else {
  2365. // [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"请勿往反方向移动"];
  2366. }
  2367. }
  2368. [self.stitchkLock unlock];
  2369. // dispatch_semaphore_signal(self.videoStitchSemaphore);
  2370. }];
  2371. }
  2372. }
  2373. }
  2374. - (void)removeLastStich {
  2375. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2376. if (self.resourceModel.panoramArray.count > 0) {
  2377. [self.resourceModel.panoramArray removeLastObject];
  2378. }
  2379. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2380. if (self.resourceModel.aiPanoramArray.count > 0) {
  2381. [self.resourceModel.aiPanoramArray removeLastObject];
  2382. }
  2383. }
  2384. }
  2385. //*
  2386. #pragma mark - Navigation
  2387. // In a storyboard-based application, you will often want to do a little preparation before navigation
  2388. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  2389. // Get the new view controller using [segue destinationViewController].
  2390. // Pass the selected object to the new view controller.
  2391. if([segue.identifier isEqualToString:@"show-photos"]){
  2392. if([segue.destinationViewController isKindOfClass:[PhotoListViewController class]]){
  2393. PhotoListViewController* dst = segue.destinationViewController;
  2394. OperationNodeMultiple* node = self.currentOperationNode;
  2395. dst.transitioningDelegate = self;
  2396. [dst setImagesInMemory:node.cachesInMemory andImageNamesOnDisk:node.cachesOnDisk];
  2397. dst.delegate = self;
  2398. }
  2399. }
  2400. else if([segue.identifier isEqualToString:@"show-movies"]){
  2401. if([segue.destinationViewController isKindOfClass:[MovieListViewController class]]){
  2402. MovieListViewController* dst = segue.destinationViewController;
  2403. OperationNodeMovie* node = self.currentOperationNode;
  2404. dst.transitioningDelegate = self;
  2405. dst.movieModels = node.cachedMovies;
  2406. dst.delegate = self;
  2407. }
  2408. }
  2409. else if([segue.identifier isEqualToString:@"preview_single"]){
  2410. PreviewSingleViewController* dst = segue.destinationViewController;
  2411. dst.singleModeNode = self.currentOperationNode;
  2412. if (self.resourceModel.singleArray.count > 0) {
  2413. LenzResourceItemModel *model = self.resourceModel.singleArray.firstObject;
  2414. dst.image = model.image;
  2415. }
  2416. // dst.image = self.capturedImage;
  2417. }else if ([segue.identifier isEqualToString:@"show-photoalbum"]){
  2418. PhotoAlbumListViewController *dst = segue.destinationViewController;
  2419. dst.typeArray = self.typeArray;
  2420. //图片数据
  2421. NSString *typeStr = self.typeArray.lastObject;
  2422. // if ([typeStr isEqualToString:@"photo"]) {
  2423. OperationNodeMultiple* node = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2424. // OperationNodeMultiple* node = self.currentOperationNode;
  2425. dst.node = node;
  2426. dst.photoListVC.transitioningDelegate = self;
  2427. [dst.photoListVC setImagesInMemory:node.cachesInMemory andImageNamesOnDisk:node.cachesOnDisk];
  2428. dst.photoListVC.delegate = self;
  2429. // }else if ([typeStr isEqualToString:@"movie"]) {
  2430. OperationNodeMovie* movieNode = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2431. dst.movieListVC.transitioningDelegate = self;
  2432. dst.movieListVC.movieModels = movieNode.cachedMovies;
  2433. dst.movieListVC.delegate = self;
  2434. // }
  2435. //视频数据
  2436. }
  2437. }
  2438. //*/
  2439. - (void)clearSingleData {
  2440. [self.resourceModel.singleArray removeAllObjects];
  2441. [self updateViewStatus];
  2442. }
  2443. - (UIImage *)videoFrameImageWith:(NSURL *)url {
  2444. AVURLAsset* asset = [[AVURLAsset alloc] initWithURL:url options:nil];
  2445. AVAssetImageGenerator *generateImg = [[AVAssetImageGenerator alloc] initWithAsset:asset];
  2446. NSError *err = NULL;
  2447. CMTime time = CMTimeMake(1, 65);
  2448. CGImageRef refImg = [generateImg copyCGImageAtTime:time actualTime:NULL error:&err];
  2449. UIImage *frameImage= [[UIImage alloc] initWithCGImage:refImg scale:1.0 orientation:self.thumbnailOritaionByCurrentVideoOrientation];
  2450. return frameImage;
  2451. }
  2452. @end