PCSBaseViewController.m 114 KB

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