PCSBaseViewController.m 112 KB

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