PCSBaseViewController.m 132 KB

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