PCSBaseViewController.m 108 KB

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