PCSBaseViewController.m 114 KB

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