PCSBaseViewController.m 142 KB

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