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. [self dismissViewControllerAnimated:YES completion:^{}];
  1779. }];
  1780. }];
  1781. }
  1782. - (void)albumButtonTouchUpInside:(id)sender{
  1783. [self performSegueWithIdentifier:@"show-photoalbum" sender:nil];
  1784. }
  1785. - (__kindof id<OperationNodeProtocol>)currentOperationNode{
  1786. return self.operationNodes[@(self.mode)];
  1787. }
  1788. - (void)updateNumberLabel {
  1789. self.aiPanPromtLabel.hidden = YES;
  1790. switch (self.mode) {
  1791. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1792. if (self.resourceModel.continousArray.count > 0) {
  1793. self.numberOfImagesLabel.hidden = NO;
  1794. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已连拍%ld张", self.resourceModel.continousArray.count];
  1795. } else {
  1796. self.numberOfImagesLabel.hidden = YES;
  1797. }
  1798. }
  1799. break;
  1800. case SDK_CAPTURE_MODE_MOVIE:{
  1801. if (self.resourceModel.movieArray.count > 0) {
  1802. self.numberOfImagesLabel.hidden = NO;
  1803. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍视频%ld条", self.resourceModel.movieArray.count];
  1804. } else {
  1805. self.numberOfImagesLabel.hidden = YES;
  1806. }
  1807. }
  1808. break;
  1809. case SDK_CAPTURE_MODE_PANORAMA:
  1810. {
  1811. if (self.resourceModel.panoramArray.count > 0) {
  1812. self.numberOfImagesLabel.hidden = NO;
  1813. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拼接%ld张", self.resourceModel.panoramArray.count];
  1814. } else {
  1815. self.numberOfImagesLabel.hidden = YES;
  1816. }
  1817. }
  1818. break;
  1819. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  1820. {
  1821. self.aiPanPromtLabel.hidden = NO;
  1822. if (self.resourceModel.aiPanoramArray.count > 0) {
  1823. self.numberOfImagesLabel.hidden = NO;
  1824. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍摄%ld张", self.resourceModel.aiPanoramArray.count];
  1825. } else {
  1826. self.numberOfImagesLabel.text = @"轻点拍照,长按录制";
  1827. self.numberOfImagesLabel.hidden = NO;
  1828. }
  1829. }
  1830. break;
  1831. default:
  1832. self.numberOfImagesLabel.hidden = YES;
  1833. break;
  1834. }
  1835. }
  1836. - (void)savePhotoWith:(NSData *)data isRemake:(BOOL)isRemake{
  1837. UIImage *image = [[UIImage alloc] initWithData:data];
  1838. NSString *path = [LenzDataManager saveImageWith:data mode:self.mode];
  1839. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1840. itemModel.path = path;
  1841. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1842. if (obj.model == self.mode) {
  1843. itemModel.cameraType = obj.cameraPositionString;
  1844. }
  1845. }];
  1846. itemModel.mode = self.mode;
  1847. itemModel.image = image;
  1848. itemModel.isRemake = isRemake;
  1849. switch (self.mode) {
  1850. case SDK_CAPTURE_MODE_CONTINUOUS:{
  1851. [self.resourceModel.continousArray addObject:itemModel];
  1852. }
  1853. break;
  1854. case SDK_CAPTURE_MODE_SINGLE: {
  1855. [self.resourceModel.singleArray addObject:itemModel];
  1856. }
  1857. break;
  1858. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  1859. [self.resourceModel.aiPanoramArray addObject:itemModel];
  1860. }
  1861. break;
  1862. default:
  1863. break;
  1864. }
  1865. self.resourceModel.lastIndex = self.mode;
  1866. [self updateViewStatus];
  1867. [self.currentOperationNode triggered];
  1868. if(self.mode == SDK_CAPTURE_MODE_SINGLE){
  1869. [self stopCaptureSession];
  1870. [self performSegueWithIdentifier:@"preview_single" sender:nil];
  1871. }
  1872. else if(self.mode == SDK_CAPTURE_MODE_CONTINUOUS){
  1873. self.discardPhotoButton.hidden = NO;
  1874. self.savePhotoButton.hidden = NO;
  1875. }
  1876. self.resultImageView.image = image;
  1877. }
  1878. #pragma mark 相机单拍,和连拍的代理
  1879. - (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
  1880. NSData* imageData = [photo fileDataRepresentation];
  1881. if (imageData == nil){
  1882. return;
  1883. }
  1884. UIImage *image = [[UIImage alloc] initWithData:imageData];
  1885. BOOL isRemake = [self.tensorFlow remake:image];
  1886. __block BOOL needCheckRemake = NO;
  1887. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1888. if (obj.model == self.mode) {
  1889. needCheckRemake = obj.isRemake;
  1890. }
  1891. }];
  1892. if (isRemake && needCheckRemake) {
  1893. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"检测到该图片为翻拍,是否继续使用?" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1894. [alertController dismissViewControllerAnimated:YES completion:nil];
  1895. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1896. [alertController dismissViewControllerAnimated:YES completion:nil];
  1897. [self savePhotoWith:imageData isRemake:isRemake];
  1898. }];
  1899. } else {
  1900. [self savePhotoWith:imageData isRemake:isRemake];
  1901. }
  1902. }
  1903. - (void)updateViewStatus {
  1904. dispatch_async(dispatch_get_main_queue(), ^{
  1905. UIImage *image = nil;
  1906. NSMutableArray *continousMutArray = [NSMutableArray array];
  1907. [self.resourceModel.continousArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1908. if (obj.path && obj.image) {
  1909. [continousMutArray addObject:obj];
  1910. }
  1911. }];
  1912. self.resourceModel.continousArray = continousMutArray;
  1913. NSMutableArray *singleMutArray = [NSMutableArray array];
  1914. [self.resourceModel.singleArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1915. if (obj.path && obj.image) {
  1916. [singleMutArray addObject:obj];
  1917. }
  1918. }];
  1919. self.resourceModel.singleArray = singleMutArray;
  1920. NSMutableArray *movieMutArray = [NSMutableArray array];
  1921. [self.resourceModel.movieArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1922. if (obj.path && obj.image) {
  1923. [movieMutArray addObject:obj];
  1924. }
  1925. }];
  1926. self.resourceModel.movieArray = movieMutArray;
  1927. NSMutableArray *panoramMutArray = [NSMutableArray array];
  1928. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1929. if (obj.path && obj.image) {
  1930. [panoramMutArray addObject:obj];
  1931. }
  1932. }];
  1933. self.resourceModel.panoramArray = panoramMutArray;
  1934. NSMutableArray *aiPanoramMutArray = [NSMutableArray array];
  1935. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1936. if (obj.path && obj.image) {
  1937. [aiPanoramMutArray addObject:obj];
  1938. }
  1939. }];
  1940. self.resourceModel.aiPanoramArray = aiPanoramMutArray;
  1941. switch (self.resourceModel.lastIndex) {
  1942. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1943. if (self.resourceModel.continousArray.count > 0) {
  1944. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1945. image = model.image;
  1946. } else {
  1947. if (self.resourceModel.singleArray.count > 0) {
  1948. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1949. image = model.image;
  1950. } else if (self.resourceModel.movieArray.count > 0) {
  1951. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1952. image = model.image;
  1953. } else if (self.resourceModel.panoramArray.count > 0) {
  1954. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1955. image = model.image;
  1956. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1957. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1958. image = model.image;
  1959. }
  1960. }
  1961. }
  1962. break;
  1963. case SDK_CAPTURE_MODE_SINGLE:{
  1964. if (self.resourceModel.singleArray.count > 0) {
  1965. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1966. image = model.image;
  1967. } else {
  1968. if (self.resourceModel.continousArray.count > 0) {
  1969. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1970. image = model.image;
  1971. } else if (self.resourceModel.movieArray.count > 0) {
  1972. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1973. image = model.image;
  1974. } else if (self.resourceModel.panoramArray.count > 0) {
  1975. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1976. image = model.image;
  1977. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1978. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1979. image = model.image;
  1980. }
  1981. }
  1982. }
  1983. break;
  1984. case SDK_CAPTURE_MODE_MOVIE:{
  1985. if (self.resourceModel.movieArray.count > 0) {
  1986. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1987. image = model.image;
  1988. } else {
  1989. if (self.resourceModel.singleArray.count > 0) {
  1990. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1991. image = model.image;
  1992. } else if (self.resourceModel.continousArray.count > 0) {
  1993. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1994. image = model.image;
  1995. } else if (self.resourceModel.panoramArray.count > 0) {
  1996. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1997. image = model.image;
  1998. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1999. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2000. image = model.image;
  2001. }
  2002. }
  2003. }
  2004. break;
  2005. case SDK_CAPTURE_MODE_PANORAMA:{
  2006. if (self.resourceModel.panoramArray.count > 0) {
  2007. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2008. image = model.image;
  2009. } else {
  2010. if (self.resourceModel.singleArray.count > 0) {
  2011. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2012. image = model.image;
  2013. } else if (self.resourceModel.movieArray.count > 0) {
  2014. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2015. image = model.image;
  2016. } else if (self.resourceModel.continousArray.count > 0) {
  2017. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2018. image = model.image;
  2019. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2020. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2021. image = model.image;
  2022. }
  2023. }
  2024. }
  2025. break;
  2026. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:{
  2027. if (self.resourceModel.aiPanoramArray.count > 0) {
  2028. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2029. image = model.image;
  2030. } else {
  2031. if (self.resourceModel.singleArray.count > 0) {
  2032. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2033. image = model.image;
  2034. } else if (self.resourceModel.movieArray.count > 0) {
  2035. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2036. image = model.image;
  2037. } else if (self.resourceModel.panoramArray.count > 0) {
  2038. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2039. image = model.image;
  2040. } else if (self.resourceModel.continousArray.count > 0) {
  2041. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2042. image = model.image;
  2043. }
  2044. }
  2045. }
  2046. break;
  2047. default:
  2048. break;
  2049. }
  2050. if (image) {
  2051. self.ablumImageView.image = image;
  2052. self.ablumImageView.hidden = NO;
  2053. self.discardPhotoButton.hidden = NO;
  2054. self.savePhotoButton.hidden = NO;
  2055. self.backButton.hidden = YES;
  2056. } else {
  2057. self.ablumImageView.image = nil;
  2058. self.ablumImageView.hidden = YES;
  2059. self.discardPhotoButton.hidden = YES;
  2060. self.savePhotoButton.hidden = YES;
  2061. self.backButton.hidden = NO;
  2062. }
  2063. [self updateNumberLabel];
  2064. });
  2065. }
  2066. #pragma mark - AVCaptureFileOutputRecordingDelegate
  2067. - (void)captureOutput:(AVCaptureFileOutput *)output didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections error:(NSError *)error{
  2068. //视频录制
  2069. BOOL recordedSuccessfully = YES;
  2070. if(error.code == AVErrorMaximumDurationReached){
  2071. }
  2072. else if (error.code == AVErrorDiskFull){
  2073. dispatch_async(dispatch_get_main_queue(), ^{
  2074. [[NSNotificationCenter defaultCenter] postNotificationName:LenzSDKNotificationDiskIsFull object:error];
  2075. });
  2076. }
  2077. else if (error.code == AVErrorSessionWasInterrupted){
  2078. }
  2079. id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
  2080. if (value) {
  2081. recordedSuccessfully = [value boolValue];
  2082. [self.recordTimer invalidate];
  2083. self.recordTimer = nil;
  2084. }
  2085. if(!recordedSuccessfully){
  2086. return;
  2087. }
  2088. OperationNodeMovie *node = nil;
  2089. if ([self.currentOperationNode isKindOfClass:[OperationNodeMovie class]]) {
  2090. node = (OperationNodeMovie *)self.currentOperationNode;
  2091. if (node.isRecording) {
  2092. [self.currentOperationNode takePhotoButtonTouched];
  2093. }
  2094. }
  2095. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  2096. itemModel.path = outputFileURL.absoluteString;
  2097. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2098. if (obj.model == self.mode) {
  2099. itemModel.cameraType = obj.cameraPositionString;
  2100. }
  2101. }];
  2102. itemModel.mode = self.mode;
  2103. itemModel.image = [self videoFrameImageWith:outputFileURL];
  2104. [self.resourceModel.movieArray addObject:itemModel];
  2105. self.resourceModel.lastIndex = self.mode;
  2106. [self updateViewStatus];
  2107. [self.timerLabel updateWith:0];
  2108. dispatch_async(dispatch_get_main_queue(), ^{
  2109. [self.currentOperationNode triggered];
  2110. self.thumbnailOritaionByCurrentVideoOrientation = UIImageOrientationUp;
  2111. });
  2112. }
  2113. - (BOOL)encodeFrame:(CMSampleBufferRef) sampleBuffer{
  2114. if (CMSampleBufferDataIsReady(sampleBuffer)) {
  2115. if (self.videoWriter.status == AVAssetWriterStatusUnknown) {
  2116. CMTime startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
  2117. [self.videoWriter startWriting];
  2118. [self.videoWriter startSessionAtSourceTime:startTime];
  2119. }
  2120. if (self.videoWriter.status == AVAssetWriterStatusFailed) {
  2121. return NO;
  2122. }
  2123. if (self.videoWriterInput.readyForMoreMediaData) {
  2124. [self.videoWriterInput appendSampleBuffer:sampleBuffer];
  2125. return YES;
  2126. }
  2127. }
  2128. return NO;
  2129. }
  2130. #pragma mark - AVCaptureAudioDataOutputSampleBufferDelegate
  2131. #pragma mark - UIViewControllerTransitioningDelegate
  2132. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
  2133. return [[CustomModalViewTransitionPresent alloc] init];
  2134. }
  2135. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
  2136. return [[CustomModalViewTransitionDismiss alloc] init];
  2137. }
  2138. #pragma mark - PhotoListViewControllerDelegate
  2139. //删除视频
  2140. - (void)deleteMovie: (MovieListCellModel*)model completion: (DeleteImageCompletionCallBackType)completion{
  2141. for (int i = 0; i < self.totalArray.count; i ++) {
  2142. UIImage *image = self.totalArray[i];
  2143. if (image == (UIImage *)model.movieModel.thumbnail) {
  2144. [self.totalArray removeObjectAtIndex:i];
  2145. [self.typeArray removeObjectAtIndex:i];
  2146. break;;
  2147. }
  2148. }
  2149. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2150. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2151. [curr deleteCacheForKey:model.movieModel.fileUrl.path completion:completion];
  2152. }
  2153. }
  2154. //连拍删除
  2155. - (void)deleteImage:(UIImage *)image completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2156. for (int i = 0; i < self.totalArray.count; i ++) {
  2157. UIImage *img = self.totalArray[i];
  2158. if (img == image) {
  2159. [self.totalArray removeObjectAtIndex:i];
  2160. [self.typeArray removeObjectAtIndex:i];
  2161. break;;
  2162. }
  2163. }
  2164. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2165. if([curr respondsToSelector:@selector(deleteCacheForImage:completion:)]){
  2166. [curr deleteCacheForImage:image completion:completion];
  2167. }
  2168. }
  2169. - (void)deleteImageWithName:(NSString *)name completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2170. id<OperationNodeProtocol> curr = self.currentOperationNode;
  2171. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2172. [curr deleteCacheForKey:name completion:completion];
  2173. }
  2174. }
  2175. #pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate
  2176. - (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
  2177. @autoreleasepool {
  2178. if (connection == [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo]) {
  2179. [self.stitchkLock lock];
  2180. OperationNodeVideoBase *base = nil;
  2181. if ([self.currentOperationNode isKindOfClass:[OperationNodeVideoBase class]]) {
  2182. base = (OperationNodeVideoBase *)self.currentOperationNode;
  2183. }
  2184. if (self.isVideoStitchStopedWhenRecording &&
  2185. (self.stitchResult != LenVideoStitchResultFail && self.stitchResult != LenVideoStitchResultStitchFail)) {
  2186. [self updateViewStatusWhenStitchSave:YES];
  2187. self.isStitchBigImage = YES;
  2188. }
  2189. [LenStitcher videoStitchWith:sampleBuffer
  2190. dirction:(LenVideoStitchDirction)self.panoramOrientationGuideView.selectedItemIndex
  2191. isStop:self.isVideoStitchStopedWhenRecording
  2192. complete:^(LenVideoStitchResult result, LenVideoStitchNeedSave needSave) {
  2193. self.stitchResult = result;
  2194. self.isVideoStitchStopedWhenRecording = NO;
  2195. UIImage *image = [LenStitcher getCurrentPanoramaShowImage];
  2196. LenzResourceItemModel *model = nil;
  2197. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2198. model = self.resourceModel.panoramArray.lastObject;
  2199. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2200. model = self.resourceModel.aiPanoramArray.lastObject;
  2201. }
  2202. if (!image || !model) {
  2203. [self.stitchkLock unlock];
  2204. return;
  2205. }
  2206. if (result == LenVideoStitchResultSuccess) {
  2207. dispatch_async(dispatch_get_main_queue(), ^{
  2208. if (self.isStitchBigImage) {
  2209. //保存大图拼接路径
  2210. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2211. if (obj.model == self.mode) {
  2212. model.cameraType = obj.cameraPositionString;
  2213. }
  2214. }];
  2215. model.mode = self.mode;
  2216. if ([LenStitcher getCurrentPanoramaShow]) {
  2217. model.image = image;
  2218. NSString *path = [LenzDataManager saveImageWith:UIImageJPEGRepresentation(image, .8) mode:self.mode];
  2219. model.path = path;
  2220. }
  2221. [self updateViewStatusWhenStitchSave:NO];
  2222. self.isStitchBigImage = NO;
  2223. [self.panoramaGuideView clearImage];
  2224. [self updateViewStatus];
  2225. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  2226. } else {
  2227. if (base.isRecording) {
  2228. __block BOOL keyFrame = NO;
  2229. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2230. if (obj.model == self.mode) {
  2231. keyFrame = [obj.keyFrame boolValue];
  2232. }
  2233. }];
  2234. if (needSave && keyFrame) {
  2235. NSString *path = [LenzDataManager saveImageWith:UIImageJPEGRepresentation(image, .6) mode:self.mode];
  2236. if (path) {
  2237. [model.keyFrame addObject:path];
  2238. }
  2239. }
  2240. if (self.panoramOrientationGuideView.selectedItemIndex != PanoramaOrientationViewAny) {
  2241. [self.panoramaGuideView showImageWith:image dir:self.panoramOrientationGuideView.selectedItemIndex];
  2242. } else {
  2243. self.ablumImageView.hidden = NO;
  2244. self.ablumImageView.image = image;
  2245. }
  2246. }
  2247. }
  2248. self.resourceModel.lastIndex = self.mode;
  2249. });
  2250. } else {
  2251. if (!base.isRecording) {
  2252. //停止拼接,移除保存中 非success数据
  2253. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2254. NSMutableArray *array = [NSMutableArray array];
  2255. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2256. if (obj.path.length) {
  2257. [array addObject:obj];
  2258. }
  2259. }];
  2260. self.resourceModel.panoramArray = array;
  2261. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2262. NSMutableArray *array = [NSMutableArray array];
  2263. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2264. if (obj.path.length) {
  2265. [array addObject:obj];
  2266. }
  2267. }];
  2268. self.resourceModel.aiPanoramArray = array;
  2269. }
  2270. [self updateViewStatusWhenStitchSave:NO];
  2271. [self updateViewStatus];
  2272. [self.stitchkLock unlock];
  2273. return;
  2274. }
  2275. if (result == LenVideoStitchResultFail || result == LenVideoStitchResultStitchFail) {
  2276. if (result == LenVideoStitchResultFail) {
  2277. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接失败,流程结束"];
  2278. } else {
  2279. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接大图失败,流程结束"];
  2280. }
  2281. self.isVideoStitchStopedWhenRecording = NO;
  2282. dispatch_async(dispatch_get_main_queue(), ^{
  2283. [base takePhotoButtonTouched];
  2284. [self stopMotion];
  2285. [self removeLastStich];
  2286. [self updateViewStatusWhenStitchFail];
  2287. [self.panoramaGuideView clearImage];
  2288. [self updateViewStatus];
  2289. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  2290. });
  2291. [SVProgressHUD dismissWithDelay:3 completion:^{
  2292. }];
  2293. } else if(result == LenVideoStitchResultSlowMore) {
  2294. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"目标物较少,请对准目标物低速且匀速拍摄"];
  2295. } else if (result == LenVideoStitchResultSlow) {
  2296. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"目标物较少,请对准目标物低速且匀速拍摄"];
  2297. } else {
  2298. // [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"请勿往反方向移动"];
  2299. }
  2300. }
  2301. [self.stitchkLock unlock];
  2302. }];
  2303. }
  2304. }
  2305. }
  2306. - (void)removeLastStich {
  2307. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2308. if (self.resourceModel.panoramArray.count > 0) {
  2309. [self.resourceModel.panoramArray removeLastObject];
  2310. }
  2311. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2312. if (self.resourceModel.aiPanoramArray.count > 0) {
  2313. [self.resourceModel.aiPanoramArray removeLastObject];
  2314. }
  2315. }
  2316. }
  2317. #pragma mark - Navigation
  2318. // In a storyboard-based application, you will often want to do a little preparation before navigation
  2319. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  2320. // Get the new view controller using [segue destinationViewController].
  2321. if([segue.identifier isEqualToString:@"show-photos"]){
  2322. if([segue.destinationViewController isKindOfClass:[PhotoListViewController class]]){
  2323. PhotoListViewController* dst = segue.destinationViewController;
  2324. OperationNodeMultiple* node = self.currentOperationNode;
  2325. dst.transitioningDelegate = self;
  2326. [dst setImagesInMemory:node.cachesInMemory andImageNamesOnDisk:node.cachesOnDisk];
  2327. dst.delegate = self;
  2328. }
  2329. }
  2330. else if([segue.identifier isEqualToString:@"show-movies"]){
  2331. if([segue.destinationViewController isKindOfClass:[MovieListViewController class]]){
  2332. MovieListViewController* dst = segue.destinationViewController;
  2333. OperationNodeMovie* node = self.currentOperationNode;
  2334. dst.transitioningDelegate = self;
  2335. dst.movieModels = node.cachedMovies;
  2336. dst.delegate = self;
  2337. }
  2338. }
  2339. else if([segue.identifier isEqualToString:@"preview_single"]){
  2340. PreviewSingleViewController* dst = segue.destinationViewController;
  2341. dst.singleModeNode = self.currentOperationNode;
  2342. if (self.resourceModel.singleArray.count > 0) {
  2343. LenzResourceItemModel *model = self.resourceModel.singleArray.firstObject;
  2344. dst.image = model.image;
  2345. }
  2346. // dst.image = self.capturedImage;
  2347. }else if ([segue.identifier isEqualToString:@"show-photoalbum"]){
  2348. PhotoAlbumListViewController *dst = segue.destinationViewController;
  2349. dst.typeArray = self.typeArray;
  2350. //图片数据
  2351. NSString *typeStr = self.typeArray.lastObject;
  2352. // if ([typeStr isEqualToString:@"photo"]) {
  2353. OperationNodeMultiple* node = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2354. // OperationNodeMultiple* node = self.currentOperationNode;
  2355. dst.node = node;
  2356. dst.photoListVC.transitioningDelegate = self;
  2357. [dst.photoListVC setImagesInMemory:node.cachesInMemory andImageNamesOnDisk:node.cachesOnDisk];
  2358. dst.photoListVC.delegate = self;
  2359. // }else if ([typeStr isEqualToString:@"movie"]) {
  2360. OperationNodeMovie* movieNode = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2361. dst.movieListVC.transitioningDelegate = self;
  2362. dst.movieListVC.movieModels = movieNode.cachedMovies;
  2363. dst.movieListVC.delegate = self;
  2364. // }
  2365. }
  2366. }
  2367. //*/
  2368. - (void)clearSingleData {
  2369. [self.resourceModel.singleArray removeAllObjects];
  2370. [self updateViewStatus];
  2371. }
  2372. - (UIImage *)videoFrameImageWith:(NSURL *)url {
  2373. AVURLAsset* asset = [[AVURLAsset alloc] initWithURL:url options:nil];
  2374. AVAssetImageGenerator *generateImg = [[AVAssetImageGenerator alloc] initWithAsset:asset];
  2375. NSError *err = NULL;
  2376. CMTime time = CMTimeMake(1, 65);
  2377. CGImageRef refImg = [generateImg copyCGImageAtTime:time actualTime:NULL error:&err];
  2378. UIImage *frameImage= [[UIImage alloc] initWithCGImage:refImg scale:1.0 orientation:self.thumbnailOritaionByCurrentVideoOrientation];
  2379. return frameImage;
  2380. }
  2381. @end