PCSBaseViewController.m 108 KB

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