PCSBaseViewController.m 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314
  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(@"~~~~~~~~~~~s~~~~ 右");
  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. if (connection.supportsVideoOrientation) {
  1171. if (self.currentTgDirection == TgDirectionLeft) {
  1172. connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
  1173. } else if (self.currentTgDirection == TgDirectionRight) {
  1174. connection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
  1175. } else if (self.currentTgDirection == TgDirectionPortrait) {
  1176. connection.videoOrientation = AVCaptureVideoOrientationPortrait;
  1177. } else {
  1178. connection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
  1179. }
  1180. }
  1181. [self.movieFileOutput startRecordingToOutputFileURL: tmpMovieFileUrl recordingDelegate:self];
  1182. return YES;
  1183. }
  1184. - (void)stopRecording{
  1185. [self.movieFileOutput stopRecording];
  1186. AVCaptureDevice* camera = self.currentCamera;
  1187. [camera lockForConfiguration:nil];
  1188. if ([camera hasFlash] && self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  1189. [camera setTorchMode:AVCaptureTorchModeOff];
  1190. }
  1191. [camera unlockForConfiguration];
  1192. [self.recordTimer invalidate];
  1193. self.recordTimer = nil;
  1194. }
  1195. - (BOOL)startVideoDataOutputing{
  1196. [[NSNotificationCenter defaultCenter] removeObserver:self name:PCS_NotificationNameOrientationDidChange object:nil];
  1197. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:PCS_NotificationNameOrientationDidChange object:nil];
  1198. UIDeviceOrientation deviceOrientation = UIDeviceOrientationPortrait;
  1199. AVCaptureVideoOrientation orientation = [self videoOrientation:&deviceOrientation];
  1200. CGFloat degree = 0;
  1201. AVCaptureDevice* camera = self.currentCamera;
  1202. CameraManager* cameraMgr = [CameraManager shared];
  1203. BOOL isFront = camera == cameraMgr.front;
  1204. BOOL isLandscape = NO;
  1205. // 前摄像头需要镜像一下
  1206. switch (deviceOrientation) {
  1207. case UIDeviceOrientationPortrait:
  1208. degree = 0;
  1209. break;
  1210. case UIDeviceOrientationLandscapeRight:
  1211. degree = isFront ? 90 : -90;
  1212. isLandscape = YES;
  1213. break;
  1214. case UIDeviceOrientationPortraitUpsideDown:
  1215. degree = 180;
  1216. break;
  1217. case UIDeviceOrientationLandscapeLeft:
  1218. degree = isFront ? -90 : 90;
  1219. isLandscape = YES;
  1220. break;
  1221. default:
  1222. break;
  1223. }
  1224. __block BOOL ret = NO;
  1225. dispatch_sync(self.videoDataQueue, ^{
  1226. if(self.videoDataOutput.sampleBufferDelegate != nil){
  1227. return;
  1228. }
  1229. if([self configureVideoWritter]){
  1230. AVCaptureConnection *connection = [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo];
  1231. if ([connection isVideoStabilizationSupported]) {
  1232. // connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
  1233. }
  1234. if(connection == nil){
  1235. return;
  1236. }
  1237. [connection setVideoOrientation:orientation];
  1238. CGFloat aspect = isFront ? cameraMgr.frontAspect : cameraMgr.backAspect;
  1239. aspect = isLandscape ? 1.0 / aspect : aspect;
  1240. [self.videoDataOutput setSampleBufferDelegate:self queue:self.videoDataQueue];
  1241. ret = YES;
  1242. }
  1243. });
  1244. return ret;
  1245. }
  1246. - (PanoramaGuideView *)panoramaGuideView{
  1247. if (_panoramaGuideView == nil) {
  1248. _panoramaGuideView = [[PanoramaGuideView alloc]init];
  1249. _panoramaGuideView.hidden = YES;
  1250. }
  1251. return _panoramaGuideView;;
  1252. }
  1253. - (void)stopVideoDataOutputing{
  1254. [self.motionTimer invalidate];
  1255. self.motionTimer = nil;
  1256. [[NSNotificationCenter defaultCenter] removeObserver:self name:PCS_NotificationNameOrientationDidChange object:nil];
  1257. dispatch_async(self.videoDataQueue, ^{
  1258. [self.videoDataOutput setSampleBufferDelegate:nil queue:nil];
  1259. [Renderer shared].cameraPass.texture = nil;
  1260. });
  1261. [self stopMotion];
  1262. [self.panoramaGuideView showImageWith:nil];
  1263. [self updateViewStatus];
  1264. }
  1265. - (void)updateViewStatusWhenStitchSave:(BOOL)isSaveIng {
  1266. dispatch_async(dispatch_get_main_queue(), ^{
  1267. self.stitchView.hidden = !isSaveIng;
  1268. if (self.stitchView.hidden) {
  1269. [self.stitchImageView.layer removeAnimationForKey:@"loadingAnimation"];
  1270. } else {
  1271. [self.stitchImageView.layer addAnimation:self.loadingAnimation forKey:@"loadingAnimation"];
  1272. }
  1273. self.flashButton.hidden = isSaveIng;
  1274. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1275. self.panoramOrientationGuideView.hidden = isSaveIng;
  1276. self.ai_fullView.hidden = YES;
  1277. self.panoramaGuideView.hidden = YES;
  1278. } else {
  1279. self.panoramOrientationGuideView.hidden = isSaveIng;
  1280. self.ai_fullView.hidden = YES;
  1281. self.panoramaGuideView.hidden = isSaveIng;
  1282. }
  1283. self.modeList.hidden = isSaveIng;
  1284. self.savePhotoButton.hidden = isSaveIng;
  1285. self.takePhotoButton.hidden = isSaveIng;
  1286. self.discardPhotoButton.hidden = isSaveIng;
  1287. self.backButton.hidden = !isSaveIng;
  1288. self.ablumImageView.hidden = isSaveIng;
  1289. });
  1290. }
  1291. - (void)updateViewStatusWhenStitchFail {
  1292. dispatch_async(dispatch_get_main_queue(), ^{
  1293. self.stitchView.hidden = YES;
  1294. self.flashButton.hidden = NO;
  1295. self.modeList.hidden = NO;
  1296. self.savePhotoButton.hidden = NO;
  1297. self.takePhotoButton.hidden = NO;
  1298. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1299. self.ai_fullView.hidden = YES;
  1300. self.panoramOrientationGuideView.hidden = NO;
  1301. self.panoramaGuideView.hidden = YES;
  1302. } else {
  1303. self.ai_fullView.hidden = YES;
  1304. self.panoramOrientationGuideView.hidden = NO;
  1305. self.panoramaGuideView.hidden = NO;
  1306. }
  1307. self.discardPhotoButton.hidden = NO;
  1308. self.backButton.hidden = YES;
  1309. self.ablumImageView.hidden = NO;
  1310. [self.takePhotoButton setImage:[UIImage loadNamed:@"take-photo-btn"] forState:UIControlStateNormal];
  1311. });
  1312. }
  1313. - (BOOL)getStitchBigImageIfNeed {
  1314. BOOL isSuccess = NO;
  1315. NSString *s = [LenStitcher getCurrentPanoramaShow];
  1316. if (s.length) {
  1317. isSuccess = YES;
  1318. }
  1319. return isSuccess;
  1320. }
  1321. - (BOOL)configureVideoWritter{
  1322. // setup asset writter for the video data output
  1323. NSURL* tmpMovieFileUrl = [NSURL fileURLWithPath:[[PCSTools shared].tmpPath stringByAppendingPathComponent:@"video-data-tmp-file.mov"] isDirectory:NO];
  1324. NSError* err = nil;
  1325. [[NSFileManager defaultManager] removeItemAtURL:tmpMovieFileUrl error:nil];
  1326. self.videoWriter = [[AVAssetWriter alloc] initWithURL:tmpMovieFileUrl fileType:AVFileTypeQuickTimeMovie error:&err];
  1327. if(err != nil){
  1328. self.videoWriter = nil;
  1329. return NO;
  1330. }
  1331. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1332. if (obj.model == self.mode) {
  1333. NSDictionary* settings = [NSDictionary dictionaryWithObjectsAndKeys:
  1334. AVVideoCodecTypeH264, AVVideoCodecKey,
  1335. [NSNumber numberWithInteger: obj.resolution.width], AVVideoWidthKey,
  1336. [NSNumber numberWithInteger: obj.resolution.height], AVVideoHeightKey,
  1337. nil];
  1338. self.videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:settings];
  1339. }
  1340. }];
  1341. self.videoWriterInput.expectsMediaDataInRealTime = YES;
  1342. [self.videoWriter addInput:self.videoWriterInput];
  1343. return YES;
  1344. }
  1345. - (void)prepareCamera{
  1346. if (self.cameraPrepared) {
  1347. return;
  1348. }
  1349. __block AVCaptureDevice* device = nil;
  1350. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1351. if (obj.model == self.mode) {
  1352. device = obj.cameraPosition == SDK_CAMERA_PISITION_BACK ? [CameraManager shared].back : [CameraManager shared].front;
  1353. }
  1354. }];
  1355. if (device == nil) {
  1356. self.cameraPrepared = false;
  1357. return;
  1358. }
  1359. NSError* error;
  1360. AVCaptureDeviceInput* input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
  1361. if(error != nil){
  1362. self.cameraPrepared = false;
  1363. return;
  1364. }
  1365. [self.captureSession beginConfiguration];
  1366. if([self.captureSession canAddInput:input]){
  1367. [self.captureSession addInput:input];
  1368. }
  1369. else{
  1370. return;
  1371. }
  1372. self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
  1373. self.previewLayer.frame = self.view.layer.bounds;
  1374. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  1375. [self.view.layer insertSublayer:self.previewLayer atIndex:0u];
  1376. if([self.captureSession canAddOutput:self.photoOutput]){
  1377. [self.captureSession addOutput:self.photoOutput];
  1378. }
  1379. if([self.captureSession canAddOutput:self.movieFileOutput]){
  1380. [self.captureSession addOutput:self.movieFileOutput];
  1381. }
  1382. [self.captureSession commitConfiguration];
  1383. self.cameraPrepared = YES;
  1384. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1385. if (obj.model == self.mode) {
  1386. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:obj.resolution.height model:self.mode];
  1387. // [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:obj.resolution.height model:self.mode];
  1388. }
  1389. }];
  1390. [self updatePreViewLayer];
  1391. }
  1392. #pragma mark - Gesture
  1393. - (void)tapGestureHandler: (UITapGestureRecognizer*)gesture{
  1394. switch(gesture.state){
  1395. case UIGestureRecognizerStateBegan:{
  1396. break;
  1397. }
  1398. case UIGestureRecognizerStateChanged:{
  1399. break;
  1400. }
  1401. case UIGestureRecognizerStateEnded:{
  1402. CGPoint pt = [gesture locationInView:self.view];
  1403. [self focusOn:pt];
  1404. break;
  1405. }
  1406. case UIGestureRecognizerStateCancelled:{
  1407. break;
  1408. }
  1409. default:
  1410. break;
  1411. }
  1412. }
  1413. - (void)panGestureHandler: (UIPanGestureRecognizer*)gesture{
  1414. switch(gesture.state){
  1415. case UIGestureRecognizerStateBegan:{
  1416. break;
  1417. }
  1418. case UIGestureRecognizerStateChanged:{
  1419. if(self.flag){
  1420. return;
  1421. }
  1422. self.flag = YES;
  1423. CGPoint translation = [gesture translationInView:self.view];
  1424. [self.modeList updateIndexByTanslation:translation];
  1425. break;
  1426. }
  1427. case UIGestureRecognizerStateEnded:{
  1428. self.flag = NO;
  1429. break;
  1430. }
  1431. case UIGestureRecognizerStateCancelled:{
  1432. self.flag = NO;
  1433. break;
  1434. }
  1435. default:
  1436. self.flag = NO;
  1437. break;
  1438. }
  1439. }
  1440. #pragma mark - orientation
  1441. //- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
  1442. // return UIInterfaceOrientationMaskPortrait;
  1443. //}
  1444. - (void)updateUIByMode{
  1445. self.albumButton.hidden = YES;
  1446. self.numberOfImagesLabel.hidden = YES;
  1447. self.modeLabel.text = self.currentOperationNode.modeTitleString;
  1448. self.ai_fullView.hidden = YES;
  1449. self.panGesture.enabled = YES;
  1450. if([self.currentOperationNode respondsToSelector:@selector(updateUI)]){
  1451. [self.currentOperationNode updateUI];
  1452. }
  1453. [self updatePreViewLayer];
  1454. [self updateUIByDir];
  1455. }
  1456. - (void)updateUIByDir {
  1457. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  1458. [self updatePanormaViewWith:self.currentTgDirection];
  1459. } else {
  1460. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1461. make.centerX.mas_equalTo(self.view);
  1462. make.centerY.mas_equalTo(self.flashButton);
  1463. }];
  1464. self.modeLabel.transform = CGAffineTransformMakeRotation(0);
  1465. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1466. make.edges.mas_equalTo(self.modeLabel);
  1467. }];
  1468. self.timerLabel.transform = CGAffineTransformMakeRotation(0);
  1469. }
  1470. }
  1471. - (void)updatePreViewLayer {
  1472. CGFloat width = [UIScreen mainScreen].bounds.size.width;
  1473. CGFloat height = [UIScreen mainScreen].bounds.size.height;
  1474. self.previewLayer.frame = CGRectMake(0, 0, width, height);
  1475. switch (self.mode) {
  1476. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1477. self.switchButton.hidden = NO;
  1478. self.panoramaGuideView.hidden = YES;
  1479. self.panoramOrientationGuideView.hidden = YES;
  1480. // self.previewLayer.frame = CGRectMake(0, (height - width*4/3)/2, width, width*4/3);
  1481. }
  1482. break;
  1483. case SDK_CAPTURE_MODE_SINGLE: {
  1484. self.switchButton.hidden = NO;
  1485. self.panoramaGuideView.hidden = YES;
  1486. self.panoramOrientationGuideView.hidden = YES;
  1487. // self.previewLayer.frame = CGRectMake(0, (height - width*4/3)/2, width, width*4/3);
  1488. }
  1489. break;
  1490. case SDK_CAPTURE_MODE_MOVIE: {
  1491. self.switchButton.hidden = NO;
  1492. self.panoramaGuideView.hidden = YES;
  1493. self.panoramOrientationGuideView.hidden = YES;
  1494. // self.previewLayer.frame = CGRectMake(0, 0, width, height);
  1495. }
  1496. break;
  1497. case SDK_CAPTURE_MODE_PANORAMA: {
  1498. self.switchButton.hidden = YES;
  1499. self.panoramaGuideView.hidden = NO;
  1500. self.panoramOrientationGuideView.hidden = NO;
  1501. // self.previewLayer.frame = CGRectMake(0, (height - width*16/9)/2, width, width*16/9);
  1502. }
  1503. break;
  1504. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  1505. self.switchButton.hidden = YES;
  1506. self.panoramaGuideView.hidden = YES;
  1507. self.panoramOrientationGuideView.hidden = NO;
  1508. // self.previewLayer.frame = CGRectMake(0, (height - width*16/9)/2, width, width*16/9);
  1509. }
  1510. break;
  1511. default:
  1512. break;
  1513. }
  1514. [self.view setNeedsDisplay];
  1515. [self.view layoutIfNeeded];
  1516. }
  1517. - (void)modeWillChange: (NSUInteger)newIndex oldIndex: (NSUInteger)oldIndex{
  1518. if(newIndex >= INT_MAX){
  1519. return;
  1520. }
  1521. [self.currentOperationNode willQuitOnCompletion:^() {}];
  1522. }
  1523. - (void)modeDidChange: (NSUInteger)newIndex oldIndex: (NSUInteger)oldIndex{
  1524. if(newIndex >= INT_MAX){
  1525. return;
  1526. }
  1527. if(newIndex != SDK_CAPTURE_MODE_MOVIE){
  1528. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1529. if (obj.model == self.mode) {
  1530. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:obj.resolution.height model:self.mode];
  1531. // [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:obj.resolution.height model:self.mode];
  1532. }
  1533. }];
  1534. }
  1535. else{
  1536. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1537. if (obj.model == self.mode) {
  1538. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:obj.videoResolution.height model:self.mode];
  1539. // [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:obj.videoResolution.height model:self.mode];
  1540. }
  1541. }];
  1542. }
  1543. [self updateUIByMode];
  1544. [self switchDevicePositionBack];
  1545. [self updateNumberLabel];
  1546. }
  1547. - (void)updateCaptureSessionWith:(NSInteger)oldIndex {
  1548. PhotographModeEnum oldModeEnum = (PhotographModeEnum)(oldIndex);
  1549. if((self.mode == SDK_CAPTURE_MODE_PANORAMA || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)
  1550. && oldModeEnum != SDK_CAPTURE_MODE_PANORAMA
  1551. && oldModeEnum != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA){
  1552. [self.captureSession beginConfiguration];
  1553. if([self.captureSession canAddOutput:self.videoDataOutput]){
  1554. [self.captureSession removeOutput:self.movieFileOutput];
  1555. [self.captureSession addOutput:self.videoDataOutput];
  1556. }
  1557. [self.captureSession commitConfiguration];
  1558. }
  1559. else if((self.mode == SDK_CAPTURE_MODE_MOVIE)
  1560. && (oldModeEnum == SDK_CAPTURE_MODE_PANORAMA
  1561. || oldModeEnum == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)){
  1562. [self.captureSession beginConfiguration];
  1563. if([self.captureSession canAddOutput:self.movieFileOutput]){
  1564. [self.captureSession removeOutput:self.videoDataOutput];
  1565. [self.captureSession addOutput:self.movieFileOutput];
  1566. }
  1567. [self.captureSession commitConfiguration];
  1568. }
  1569. }
  1570. - (void)setupMicrophone{
  1571. NSError* audioError = nil;
  1572. AVCaptureDevice* audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
  1573. AVCaptureDeviceInput* audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&audioError];
  1574. if(audioError == nil){
  1575. AVCaptureAudioDataOutput* audioOutput = [[AVCaptureAudioDataOutput alloc] init];
  1576. [audioOutput setSampleBufferDelegate:self queue:dispatch_get_global_queue(0, 0)];
  1577. if([self.captureSession canAddInput:audioInput]){
  1578. [self.captureSession addInput:audioInput];
  1579. }
  1580. if([self.captureSession canAddOutput:audioOutput]){
  1581. [self.captureSession addOutput:audioOutput];
  1582. }
  1583. }
  1584. }
  1585. - (UIStatusBarStyle)preferredStatusBarStyle{
  1586. return UIStatusBarStyleLightContent;
  1587. }
  1588. #pragma mark - DeviceOrigatrion Delegate
  1589. - (void)directionChange:(TgDirection)direction {
  1590. self.currentTgDirection = direction;
  1591. if (self.mode != SDK_CAPTURE_MODE_PANORAMA && self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1592. return;
  1593. }
  1594. OperationNodeVideoBase *base = nil;
  1595. if ([self.currentOperationNode isKindOfClass:[OperationNodeVideoBase class]]) {
  1596. base = (OperationNodeVideoBase *)self.currentOperationNode;
  1597. }
  1598. if (base.isRecording) {
  1599. return;
  1600. }
  1601. self.panoramaGuideView.dir = self.currentTgDirection;
  1602. self.panoramaGuideView.orginDir = self.panoramOrientationGuideView.selectedItemIndex;
  1603. [self updatePanormaViewWith:direction];
  1604. }
  1605. - (void)updatePanormaViewWith:(TgDirection)direction {
  1606. CGFloat height = [UIScreen mainScreen].bounds.size.height;
  1607. CGFloat width = [UIScreen mainScreen].bounds.size.width;
  1608. switch (direction) {
  1609. case TgDirectionPortrait:{
  1610. [self panoramaOrientationViewslt:self.panoramOrientationGuideView.selectedItemIndex];
  1611. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1612. make.centerX.mas_equalTo(self.view);
  1613. make.centerY.mas_equalTo(self.flashButton);
  1614. }];
  1615. [self.aiPanPromtLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1616. make.centerX.mas_equalTo(self.view);
  1617. make.top.mas_equalTo(self.modeLabel.mas_bottom).mas_offset(20);
  1618. make.width.mas_offset(240);
  1619. make.height.mas_offset(20);
  1620. }];
  1621. self.modeLabel.transform = CGAffineTransformMakeRotation(0);
  1622. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1623. make.edges.mas_equalTo(self.modeLabel);
  1624. }];
  1625. self.timerLabel.transform = CGAffineTransformMakeRotation(0);
  1626. self.svContentView.transform = CGAffineTransformMakeRotation(0);
  1627. self.aiPanPromtLabel.transform = CGAffineTransformMakeRotation(0);
  1628. }
  1629. break;
  1630. case TgDirectionDown:{
  1631. if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewLeft) {
  1632. [self panoramaOrientationViewslt:PanoramaOrientationViewRight];
  1633. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewRight) {
  1634. [self panoramaOrientationViewslt:PanoramaOrientationViewLeft];
  1635. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewUp) {
  1636. [self panoramaOrientationViewslt:PanoramaOrientationViewDown];
  1637. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewDown) {
  1638. [self panoramaOrientationViewslt:PanoramaOrientationViewUp];
  1639. } else {
  1640. [self panoramaOrientationViewslt:PanoramaOrientationViewAny];
  1641. }
  1642. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1643. make.centerX.mas_equalTo(self.view);
  1644. make.centerY.mas_equalTo(self.flashButton);
  1645. }];
  1646. [self.aiPanPromtLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1647. make.centerX.mas_equalTo(self.view);
  1648. make.top.mas_equalTo(self.modeLabel.mas_bottom).mas_offset(20);
  1649. make.width.mas_offset(240);
  1650. make.height.mas_offset(20);
  1651. }];
  1652. self.modeLabel.transform = CGAffineTransformMakeRotation(0);
  1653. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1654. make.edges.mas_equalTo(self.modeLabel);
  1655. }];
  1656. self.timerLabel.transform = CGAffineTransformMakeRotation(0);
  1657. self.svContentView.transform = CGAffineTransformMakeRotation(0);
  1658. self.aiPanPromtLabel.transform = CGAffineTransformMakeRotation(0);
  1659. }
  1660. break;
  1661. case TgDirectionRight:{
  1662. if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewLeft) {
  1663. [self panoramaOrientationViewslt:PanoramaOrientationViewDown];
  1664. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1665. make.top.mas_equalTo((height - 40)/2);
  1666. make.height.mas_offset(22);
  1667. make.right.mas_offset(-(width-80));
  1668. }];
  1669. [self.aiPanPromtLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1670. make.centerY.mas_equalTo(self.view);
  1671. make.right.mas_offset(-(width-200));
  1672. make.width.mas_offset(240);
  1673. make.height.mas_offset(20);
  1674. }];
  1675. self.modeLabel.transform = CGAffineTransformMakeRotation(-M_PI/2);
  1676. self.aiPanPromtLabel.transform = CGAffineTransformMakeRotation(-M_PI/2);
  1677. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1678. make.edges.mas_equalTo(self.modeLabel);
  1679. }];
  1680. self.timerLabel.transform = CGAffineTransformMakeRotation(-M_PI/2);
  1681. self.svContentView.transform = CGAffineTransformMakeRotation(-M_PI/2);
  1682. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewRight) {
  1683. [self panoramaOrientationViewslt:PanoramaOrientationViewUp];
  1684. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1685. make.top.mas_equalTo((height - 40)/2);
  1686. make.height.mas_offset(22);
  1687. make.right.mas_offset(-(width-80));
  1688. }];
  1689. [self.aiPanPromtLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1690. make.centerY.mas_equalTo(self.view);
  1691. make.right.mas_offset(-(width-200));
  1692. make.width.mas_offset(240);
  1693. make.height.mas_offset(20);
  1694. }];
  1695. self.modeLabel.transform = CGAffineTransformMakeRotation(-M_PI/2);
  1696. self.aiPanPromtLabel.transform = CGAffineTransformMakeRotation(-M_PI/2);
  1697. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1698. make.edges.mas_equalTo(self.modeLabel);
  1699. }];
  1700. self.timerLabel.transform = CGAffineTransformMakeRotation(-M_PI/2);
  1701. self.svContentView.transform = CGAffineTransformMakeRotation(-M_PI/2);
  1702. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewUp) {
  1703. [self panoramaOrientationViewslt:PanoramaOrientationViewLeft];
  1704. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1705. make.centerX.mas_equalTo(self.view);
  1706. make.centerY.mas_equalTo(self.flashButton);
  1707. }];
  1708. [self.aiPanPromtLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1709. make.centerX.mas_equalTo(self.view);
  1710. make.top.mas_equalTo(self.modeLabel.mas_bottom).mas_offset(20);
  1711. make.width.mas_offset(240);
  1712. make.height.mas_offset(20);
  1713. }];
  1714. self.modeLabel.transform = CGAffineTransformMakeRotation(0);
  1715. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1716. make.edges.mas_equalTo(self.modeLabel);
  1717. }];
  1718. self.timerLabel.transform = CGAffineTransformMakeRotation(0);
  1719. self.svContentView.transform = CGAffineTransformMakeRotation(0);
  1720. self.aiPanPromtLabel.transform = CGAffineTransformMakeRotation(0);
  1721. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewDown) {
  1722. [self panoramaOrientationViewslt:PanoramaOrientationViewRight];
  1723. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1724. make.centerX.mas_equalTo(self.view);
  1725. make.centerY.mas_equalTo(self.flashButton);
  1726. }];
  1727. [self.aiPanPromtLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1728. make.centerX.mas_equalTo(self.view);
  1729. make.top.mas_equalTo(self.modeLabel.mas_bottom).mas_offset(20);
  1730. make.width.mas_offset(240);
  1731. make.height.mas_offset(20);
  1732. }];
  1733. self.modeLabel.transform = CGAffineTransformMakeRotation(0);
  1734. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1735. make.edges.mas_equalTo(self.modeLabel);
  1736. }];
  1737. self.timerLabel.transform = CGAffineTransformMakeRotation(0);
  1738. self.svContentView.transform = CGAffineTransformMakeRotation(0);
  1739. self.aiPanPromtLabel.transform = CGAffineTransformMakeRotation(0);
  1740. } else {
  1741. [self panoramaOrientationViewslt:PanoramaOrientationViewAny];
  1742. }
  1743. }
  1744. break;
  1745. case TgDirectionLeft:{
  1746. if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewLeft) {
  1747. [self panoramaOrientationViewslt:PanoramaOrientationViewUp];
  1748. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1749. make.top.mas_equalTo((height - 40)/2);
  1750. make.height.mas_offset(22);
  1751. make.left.mas_offset(width-80);
  1752. }];
  1753. [self.aiPanPromtLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1754. make.centerY.mas_equalTo(self.view);
  1755. make.left.mas_offset(width-200);
  1756. make.width.mas_offset(240);
  1757. make.height.mas_offset(20);
  1758. }];
  1759. self.modeLabel.transform = CGAffineTransformMakeRotation(M_PI/2);
  1760. self.aiPanPromtLabel.transform = CGAffineTransformMakeRotation(M_PI/2);
  1761. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1762. make.edges.mas_equalTo(self.modeLabel);
  1763. }];
  1764. self.timerLabel.transform = CGAffineTransformMakeRotation(M_PI/2);
  1765. self.svContentView.transform = CGAffineTransformMakeRotation(M_PI/2);
  1766. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewRight) {
  1767. [self panoramaOrientationViewslt:PanoramaOrientationViewDown];
  1768. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1769. make.top.mas_equalTo((height - 40)/2);
  1770. make.height.mas_offset(22);
  1771. make.left.mas_offset(width-80);
  1772. }];
  1773. [self.aiPanPromtLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1774. make.centerY.mas_equalTo(self.view);
  1775. make.left.mas_offset(width-200);
  1776. make.width.mas_offset(240);
  1777. make.height.mas_offset(20);
  1778. }];
  1779. self.modeLabel.transform = CGAffineTransformMakeRotation(M_PI/2);
  1780. self.aiPanPromtLabel.transform = CGAffineTransformMakeRotation(M_PI/2);
  1781. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1782. make.edges.mas_equalTo(self.modeLabel);
  1783. }];
  1784. self.timerLabel.transform = CGAffineTransformMakeRotation(M_PI/2);
  1785. self.svContentView.transform = CGAffineTransformMakeRotation(M_PI/2);
  1786. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewUp) {
  1787. [self panoramaOrientationViewslt:PanoramaOrientationViewRight];
  1788. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1789. make.centerX.mas_equalTo(self.view);
  1790. make.centerY.mas_equalTo(self.flashButton);
  1791. }];
  1792. [self.aiPanPromtLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1793. make.centerX.mas_equalTo(self.view);
  1794. make.top.mas_equalTo(self.modeLabel.mas_bottom).mas_offset(20);
  1795. make.width.mas_offset(240);
  1796. make.height.mas_offset(20);
  1797. }];
  1798. self.modeLabel.transform = CGAffineTransformMakeRotation(0);
  1799. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1800. make.edges.mas_equalTo(self.modeLabel);
  1801. }];
  1802. self.timerLabel.transform = CGAffineTransformMakeRotation(0);
  1803. self.svContentView.transform = CGAffineTransformMakeRotation(0);
  1804. self.aiPanPromtLabel.transform = CGAffineTransformMakeRotation(0);
  1805. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewDown) {
  1806. [self panoramaOrientationViewslt:PanoramaOrientationViewLeft];
  1807. [self.modeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1808. make.centerX.mas_equalTo(self.view);
  1809. make.centerY.mas_equalTo(self.flashButton);
  1810. }];
  1811. [self.aiPanPromtLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1812. make.centerX.mas_equalTo(self.view);
  1813. make.top.mas_equalTo(self.modeLabel.mas_bottom).mas_offset(20);
  1814. make.width.mas_offset(240);
  1815. make.height.mas_offset(20);
  1816. }];
  1817. self.modeLabel.transform = CGAffineTransformMakeRotation(0);
  1818. [self.timerLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1819. make.edges.mas_equalTo(self.modeLabel);
  1820. }];
  1821. self.timerLabel.transform = CGAffineTransformMakeRotation(0);
  1822. self.svContentView.transform = CGAffineTransformMakeRotation(0);
  1823. self.aiPanPromtLabel.transform = CGAffineTransformMakeRotation(0);
  1824. } else {
  1825. [self panoramaOrientationViewslt:PanoramaOrientationViewAny];
  1826. }
  1827. }
  1828. break;
  1829. default:
  1830. break;
  1831. }
  1832. }
  1833. #pragma mark 方向调用的代理
  1834. - (void)panoramDirDidChange {
  1835. [self directionChange:self.currentTgDirection];
  1836. }
  1837. - (void)panoramaOrientationViewslt:(PanoramaOrientationViewDirectionEnum)direction{
  1838. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  1839. self.panoramaGuideView.hidden = NO;
  1840. } else {
  1841. OperationNodeVideoBase *base = nil;
  1842. if ([self.currentOperationNode isKindOfClass:[OperationNodeVideoBase class]]) {
  1843. base = (OperationNodeVideoBase *)self.currentOperationNode;
  1844. }
  1845. if (base.isRecording) {
  1846. self.panoramaGuideView.hidden = NO;
  1847. } else {
  1848. self.panoramaGuideView.hidden = YES;
  1849. }
  1850. }
  1851. self.panoramaGuideView.hidden = !(self.mode == SDK_CAPTURE_MODE_PANORAMA);
  1852. [UIView animateWithDuration:0.25 animations:^{
  1853. [self.panoramaGuideView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1854. switch (direction) {
  1855. case PanoramaOrientationViewLeft:
  1856. case PanoramaOrientationViewRight:
  1857. {
  1858. make.left.right.offset(0);
  1859. make.centerY.mas_equalTo(self.view);
  1860. make.height.mas_equalTo(PanoramaGuideViewWOrH);
  1861. }
  1862. break;
  1863. case PanoramaOrientationViewUp:
  1864. case PanoramaOrientationViewDown:
  1865. {
  1866. make.centerX.mas_equalTo(self.view);
  1867. make.width.mas_equalTo(PanoramaGuideViewWOrH);
  1868. make.bottom.mas_equalTo(self.panoramOrientationGuideView.mas_top).offset(-25);
  1869. if (self.currentTgDirection == TgDirectionLeft || self.currentTgDirection == TgDirectionRight) {
  1870. make.top.offset(50);
  1871. } else {
  1872. make.top.mas_equalTo(self.timerLabel.mas_bottom).offset(15);
  1873. }
  1874. }
  1875. break;
  1876. case PanoramaOrientationViewAny: {
  1877. self.panoramaGuideView.hidden = YES;
  1878. }
  1879. break;
  1880. default:
  1881. break;
  1882. }
  1883. }];
  1884. // if (self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1885. // [self.panoramaGuideView setNeedsLayout];
  1886. // [self.panoramaGuideView layoutIfNeeded];
  1887. // }
  1888. } completion:^(BOOL finished) {
  1889. self.panoramaGuideView.dir = self.currentTgDirection;
  1890. self.panoramaGuideView.orginDir = self.panoramOrientationGuideView.selectedItemIndex;
  1891. [self.panoramaGuideView direction:direction];
  1892. // [self updatePanormaViewWith:direction];
  1893. }];
  1894. }
  1895. - (void)stopAllSensors{
  1896. dispatch_async(self.videoQueue, ^{
  1897. [self.captureSession stopRunning];
  1898. });
  1899. [[PCSMotionManager shared] stopAccelerometerUpdates];
  1900. }
  1901. #pragma mark - session
  1902. - (void)turnTorchOff{
  1903. AVCaptureDevice* currentDevice = self.currentCamera;
  1904. if(currentDevice == nil || !currentDevice.hasTorch){
  1905. return;
  1906. }
  1907. NSError* error;
  1908. if(error == nil){
  1909. [currentDevice lockForConfiguration:&error];
  1910. currentDevice.torchMode = AVCaptureTorchModeOff;
  1911. [currentDevice unlockForConfiguration];
  1912. }
  1913. }
  1914. - (void)stopCaptureSession{
  1915. [self turnTorchOff];
  1916. if (self.captureSession.isRunning) {
  1917. dispatch_async(self.videoQueue, ^{
  1918. [self.captureSession stopRunning];
  1919. });
  1920. }
  1921. }
  1922. - (void)startCaptureSession{
  1923. if (!self.cameraPrepared) {
  1924. [self prepareCamera];
  1925. }
  1926. if (self.cameraPrepared && (!self.captureSession.isRunning)) {
  1927. // dispatch_async(dispatch_get_global_queue(0, 0), ^{
  1928. dispatch_async(self.videoQueue, ^{
  1929. [self.captureSession startRunning];
  1930. });
  1931. // [self.captureSession startRunning];
  1932. // });
  1933. }
  1934. }
  1935. #pragma mark - Btn call back
  1936. -(IBAction)switchCameraTapped:(id)sender
  1937. {
  1938. if(self.captureSession == nil){
  1939. return;
  1940. }
  1941. AVCaptureDeviceInput* currInput = self.currentCameraInput;
  1942. if(currInput == nil){
  1943. return;
  1944. }
  1945. AVCaptureDevice* currentDevice = currInput.device;
  1946. AVCaptureDevice *newCamera = nil;
  1947. if(currentDevice.position == AVCaptureDevicePositionBack){
  1948. newCamera = [CameraManager shared].front;
  1949. }
  1950. else if(currentDevice.position == AVCaptureDevicePositionFront){
  1951. newCamera = [CameraManager shared].back;
  1952. }
  1953. else{
  1954. return;
  1955. }
  1956. [self.captureSession beginConfiguration];
  1957. if(currentDevice.hasTorch){
  1958. NSError* error;
  1959. [currentDevice lockForConfiguration:&error];
  1960. currentDevice.torchMode = AVCaptureTorchModeOff;
  1961. [currentDevice unlockForConfiguration];
  1962. }
  1963. [self.captureSession removeInput:currInput];
  1964. self.flashButton.hidden = !newCamera.hasFlash;
  1965. NSError *err = nil;
  1966. AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
  1967. if(newVideoInput == nil || err != nil){
  1968. }
  1969. else if([self.captureSession canAddInput:newVideoInput]){
  1970. [self.captureSession addInput:newVideoInput];
  1971. }
  1972. [self.captureSession commitConfiguration];
  1973. }
  1974. - (void)switchDevicePositionBack {
  1975. if(self.captureSession == nil ||
  1976. (self.mode != SDK_CAPTURE_MODE_PANORAMA && self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)){
  1977. return;
  1978. }
  1979. AVCaptureDeviceInput* currInput = self.currentCameraInput;
  1980. if(currInput == nil){
  1981. return;
  1982. }
  1983. AVCaptureDevice* currentDevice = currInput.device;
  1984. AVCaptureDevice *newCamera = nil;
  1985. if(currentDevice.position == AVCaptureDevicePositionBack){
  1986. return;
  1987. }
  1988. if(currentDevice.position == AVCaptureDevicePositionFront){
  1989. newCamera = [CameraManager shared].back;
  1990. }
  1991. [self.captureSession beginConfiguration];
  1992. if(currentDevice.hasTorch){
  1993. NSError* error;
  1994. [currentDevice lockForConfiguration:&error];
  1995. currentDevice.torchMode = AVCaptureTorchModeOff;
  1996. [currentDevice unlockForConfiguration];
  1997. }
  1998. [self.captureSession removeInput:currInput];
  1999. NSError *err = nil;
  2000. AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
  2001. if(newVideoInput == nil || err != nil){
  2002. } else if([self.captureSession canAddInput:newVideoInput]){
  2003. [self.captureSession addInput:newVideoInput];
  2004. }
  2005. [self.captureSession commitConfiguration];
  2006. }
  2007. - (void)takePhotoButtonTouchUpInside:(id)sender{
  2008. if(![self.currentOperationNode respondsToSelector:@selector(enable)] || self.currentOperationNode.enable){
  2009. if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  2010. __block SDKParametersItem *videoItems = nil;
  2011. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2012. if (obj.model == self.mode) {
  2013. videoItems = obj;
  2014. }
  2015. }];
  2016. if (videoItems.quantity > 0 && self.resourceModel.movieArray.count >= videoItems.quantity) {
  2017. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"最多录制%ld条视频", videoItems.quantity]];
  2018. return;
  2019. }
  2020. }
  2021. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2022. OperationNodeAIPanorama *aiPan = nil;
  2023. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  2024. aiPan = self.currentOperationNode;
  2025. if (!aiPan.isRecording) {
  2026. aiPan.AIType = OperationAITypeTap;
  2027. }
  2028. }
  2029. }
  2030. [self.currentOperationNode takePhotoButtonTouched];
  2031. if (self.mode == SDK_CAPTURE_MODE_PANORAMA && !self.isVideoStitchStopedWhenRecording) {
  2032. [LenStitcher videoResetPath];
  2033. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  2034. [self.resourceModel.panoramArray addObject:itemModel];
  2035. [self startMotion];
  2036. }
  2037. }
  2038. }
  2039. - (void)longPressGes:(UILongPressGestureRecognizer *)ges {
  2040. switch (ges.state) {
  2041. case UIGestureRecognizerStateBegan:
  2042. {
  2043. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2044. OperationNodeAIPanorama *aiPan = nil;
  2045. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  2046. [LenStitcher videoResetPath];
  2047. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  2048. itemModel.isStitch = YES;
  2049. [self.resourceModel.aiPanoramArray addObject:itemModel];
  2050. [self startMotion];
  2051. aiPan = self.currentOperationNode;
  2052. aiPan.AIType = OperationAITypeLongPress;
  2053. [self.currentOperationNode takePhotoButtonTouched];
  2054. }
  2055. }
  2056. }
  2057. break;
  2058. case UIGestureRecognizerStateEnded:
  2059. break;
  2060. default:
  2061. break;
  2062. }
  2063. }
  2064. - (void)takePhotoButtonTouchDownInside:(id)sender{
  2065. }
  2066. - (void)flashButtonTouchUpInside:(id)sender{
  2067. AVCaptureDevice* currentDevice = self.currentCamera;
  2068. if(currentDevice == nil || !currentDevice.hasFlash){
  2069. return;
  2070. }
  2071. NSError* error = nil;
  2072. [currentDevice lockForConfiguration:&error];
  2073. if(error != nil){
  2074. return;
  2075. }
  2076. if(self.outputSettings.flashMode == AVCaptureFlashModeOn){
  2077. self.outputSettings.flashMode = AVCaptureFlashModeAuto;
  2078. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-auto-btn"] forState:UIControlStateNormal];
  2079. }
  2080. else if(self.outputSettings.flashMode == AVCaptureFlashModeAuto){
  2081. self.outputSettings.flashMode = AVCaptureFlashModeOff;
  2082. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-disable-btn"] forState:UIControlStateNormal];
  2083. }
  2084. else{
  2085. self.outputSettings.flashMode = AVCaptureFlashModeOn;
  2086. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-btn"] forState:UIControlStateNormal];
  2087. }
  2088. [currentDevice unlockForConfiguration];
  2089. }
  2090. - (void)backButtonTouchUpInside:(id)sender{
  2091. if (!self.stitchView.hidden) {
  2092. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"图片拼接中,返回会清空正在拼接的数据" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  2093. [alertController dismissViewControllerAnimated:NO completion:^{}];
  2094. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  2095. [self updateViewStatusWhenStitchSave:NO];
  2096. [self.panoramaGuideView clearImage];
  2097. [self.panoramaGuideView showImageWith:nil];
  2098. [alertController dismissViewControllerAnimated:NO completion:^{
  2099. }];
  2100. }];
  2101. } else {
  2102. [self stopCaptureSession];
  2103. [[PCSMotionManager shared] stopAccelerometerUpdates];
  2104. [self dismissViewControllerAnimated:YES completion:^{
  2105. }];
  2106. }
  2107. }
  2108. - (void)makeResData:(NSMutableArray <LenzResourceItemModel *> *)array {
  2109. [array enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2110. }];
  2111. }
  2112. - (void)savePhotoButtonTouchUpInside:(id)sender{
  2113. //待优化
  2114. NSMutableArray *res = [NSMutableArray array];
  2115. __block NSInteger idIndex = 1;
  2116. [self.resourceModel.singleArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2117. idIndex += idx;
  2118. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  2119. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  2120. dict[@"path"] = obj.path;
  2121. dict[@"cameraMode"] = obj.cameraMode;
  2122. dict[@"cameraType"] = obj.cameraType;
  2123. dict[@"isRemake"] = @(obj.isRemake);
  2124. [res addObject:dict];
  2125. }];
  2126. [self.resourceModel.continousArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2127. idIndex += idx;
  2128. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  2129. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  2130. dict[@"path"] = obj.path;
  2131. dict[@"cameraMode"] = obj.cameraMode;
  2132. dict[@"cameraType"] = obj.cameraType;
  2133. dict[@"isRemake"] = @(obj.isRemake);
  2134. [res addObject:dict];
  2135. }];
  2136. [self.resourceModel.movieArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2137. idIndex += idx;
  2138. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  2139. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  2140. dict[@"path"] = obj.path;
  2141. dict[@"cameraMode"] = obj.cameraMode;
  2142. dict[@"cameraType"] = obj.cameraType;
  2143. dict[@"isRemake"] = @(obj.isRemake);
  2144. [res addObject:dict];
  2145. }];
  2146. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2147. if (obj.path.length) {
  2148. idIndex += idx;
  2149. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  2150. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  2151. dict[@"mosaicPictureUrl"] = obj.path;
  2152. dict[@"cameraMode"] = obj.cameraMode;
  2153. dict[@"cameraType"] = obj.cameraType;
  2154. dict[@"isRemake"] = @(obj.isRemake);
  2155. NSMutableArray *keyFrame = [NSMutableArray array];
  2156. [obj.keyFrame enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2157. [keyFrame addObject:obj];
  2158. }];
  2159. dict[@"keyframe"] = keyFrame;
  2160. [res addObject:dict];
  2161. }
  2162. }];
  2163. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2164. if (obj.path.length) {
  2165. idIndex += idx;
  2166. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  2167. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  2168. dict[@"cameraMode"] = obj.cameraMode;
  2169. dict[@"cameraType"] = obj.cameraType;
  2170. dict[@"isRemake"] = @(obj.isRemake);
  2171. if (obj.isStitch) {
  2172. NSMutableArray *keyFrame = [NSMutableArray array];
  2173. [obj.keyFrame enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2174. [keyFrame addObject:obj];
  2175. }];
  2176. dict[@"keyframe"] = keyFrame;
  2177. dict[@"mosaicPictureUrl"] = obj.path;
  2178. } else {
  2179. dict[@"path"] = obj.path;
  2180. }
  2181. [res addObject:dict];
  2182. }
  2183. }];
  2184. if (self.completeBlock) {
  2185. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  2186. dict[@"code"] = @(200);
  2187. dict[@"message"] = @"成功";
  2188. dict[@"data"] = res;
  2189. [self stopCaptureSession];
  2190. [[PCSMotionManager shared] stopAccelerometerUpdates];
  2191. self.completeBlock(dict);
  2192. [self dismissViewControllerAnimated:YES completion:^{
  2193. }];
  2194. }
  2195. }
  2196. - (void)discardPhotoResultButtonTouchUpInside:(id)sender{
  2197. self.panGesture.enabled = YES;
  2198. NSString *title = @"返回会清空已拍摄数据,请确认!";
  2199. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:title leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  2200. [alertController dismissViewControllerAnimated:NO completion:^{}];
  2201. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  2202. [self.resourceModel.continousArray removeAllObjects];
  2203. [self.resourceModel.movieArray removeAllObjects];
  2204. [self.resourceModel.panoramArray removeAllObjects];
  2205. [self.resourceModel.aiPanoramArray removeAllObjects];
  2206. [alertController dismissViewControllerAnimated:NO completion:^{
  2207. [self stopCaptureSession];
  2208. [[PCSMotionManager shared] stopAccelerometerUpdates];
  2209. [self dismissViewControllerAnimated:YES completion:^{}];
  2210. }];
  2211. }];
  2212. }
  2213. - (void)albumButtonTouchUpInside:(id)sender{
  2214. [self performSegueWithIdentifier:@"show-photoalbum" sender:nil];
  2215. }
  2216. - (__kindof id<OperationNodeProtocol>)currentOperationNode{
  2217. return self.operationNodes[@(self.mode)];
  2218. }
  2219. - (void)updateNumberLabel {
  2220. self.aiPanPromtLabel.hidden = YES;
  2221. switch (self.mode) {
  2222. case SDK_CAPTURE_MODE_CONTINUOUS: {
  2223. if (self.resourceModel.continousArray.count > 0) {
  2224. self.numberOfImagesLabel.hidden = NO;
  2225. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已连拍%ld张", self.resourceModel.continousArray.count];
  2226. } else {
  2227. self.numberOfImagesLabel.hidden = YES;
  2228. }
  2229. }
  2230. break;
  2231. case SDK_CAPTURE_MODE_MOVIE:{
  2232. if (self.resourceModel.movieArray.count > 0) {
  2233. self.numberOfImagesLabel.hidden = NO;
  2234. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍视频%ld条", self.resourceModel.movieArray.count];
  2235. } else {
  2236. self.numberOfImagesLabel.hidden = YES;
  2237. }
  2238. }
  2239. break;
  2240. case SDK_CAPTURE_MODE_PANORAMA:
  2241. {
  2242. if (self.resourceModel.panoramArray.count > 0) {
  2243. self.numberOfImagesLabel.hidden = NO;
  2244. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拼接%ld张", self.resourceModel.panoramArray.count];
  2245. } else {
  2246. self.numberOfImagesLabel.hidden = YES;
  2247. }
  2248. }
  2249. break;
  2250. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  2251. {
  2252. self.aiPanPromtLabel.hidden = NO;
  2253. if (self.resourceModel.aiPanoramArray.count > 0) {
  2254. self.numberOfImagesLabel.hidden = NO;
  2255. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍摄%ld张", self.resourceModel.aiPanoramArray.count];
  2256. } else {
  2257. self.numberOfImagesLabel.text = @"轻点拍照,长按录制";
  2258. self.numberOfImagesLabel.hidden = NO;
  2259. }
  2260. }
  2261. break;
  2262. default:
  2263. self.numberOfImagesLabel.hidden = YES;
  2264. break;
  2265. }
  2266. }
  2267. - (void)savePhotoWith:(NSData *)data isRemake:(BOOL)isRemake{
  2268. UIImage *image = [[UIImage alloc] initWithData:data];
  2269. UIImage *saveImage = [self rotateImageWith:image];
  2270. data = UIImageJPEGRepresentation(saveImage, 1);
  2271. NSString *path = [LenzDataManager saveImageWith:data mode:self.mode];
  2272. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  2273. itemModel.path = path;
  2274. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2275. if (obj.model == self.mode) {
  2276. itemModel.cameraType = obj.cameraPositionString;
  2277. }
  2278. }];
  2279. itemModel.mode = self.mode;
  2280. itemModel.image = image;
  2281. itemModel.previewImage = saveImage;
  2282. itemModel.isRemake = isRemake;
  2283. switch (self.mode) {
  2284. case SDK_CAPTURE_MODE_CONTINUOUS:{
  2285. [self.resourceModel.continousArray addObject:itemModel];
  2286. }
  2287. break;
  2288. case SDK_CAPTURE_MODE_SINGLE: {
  2289. [self.resourceModel.singleArray addObject:itemModel];
  2290. }
  2291. break;
  2292. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  2293. [self.resourceModel.aiPanoramArray addObject:itemModel];
  2294. }
  2295. break;
  2296. default:
  2297. break;
  2298. }
  2299. self.resourceModel.lastIndex = self.mode;
  2300. [self updateViewStatus];
  2301. [self.currentOperationNode triggered];
  2302. if(self.mode == SDK_CAPTURE_MODE_SINGLE){
  2303. [self stopCaptureSession];
  2304. [self performSegueWithIdentifier:@"preview_single" sender:nil];
  2305. }
  2306. else if(self.mode == SDK_CAPTURE_MODE_CONTINUOUS){
  2307. self.discardPhotoButton.hidden = NO;
  2308. self.savePhotoButton.hidden = NO;
  2309. }
  2310. self.resultImageView.image = image;
  2311. }
  2312. #pragma mark 相机单拍,和连拍的代理
  2313. - (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
  2314. self.panGesture.enabled = YES;
  2315. self.isDuringTakePhoto = NO;
  2316. NSData* imageData = [photo fileDataRepresentation];
  2317. if (imageData == nil){
  2318. return;
  2319. }
  2320. UIImage *image = [[UIImage alloc] initWithData:imageData];
  2321. BOOL isRemake = [self.tensorFlow remake:image];
  2322. __block BOOL needCheckRemake = NO;
  2323. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2324. if (obj.model == self.mode) {
  2325. needCheckRemake = obj.isRemake;
  2326. }
  2327. }];
  2328. if (isRemake && needCheckRemake) {
  2329. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"检测到该图片为翻拍,是否继续使用?" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  2330. [alertController dismissViewControllerAnimated:YES completion:nil];
  2331. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  2332. [alertController dismissViewControllerAnimated:YES completion:nil];
  2333. [self savePhotoWith:imageData isRemake:isRemake];
  2334. }];
  2335. } else {
  2336. [self savePhotoWith:imageData isRemake:isRemake];
  2337. }
  2338. }
  2339. - (void)updateViewStatus {
  2340. dispatch_async(dispatch_get_main_queue(), ^{
  2341. UIImage *image = nil;
  2342. NSMutableArray *continousMutArray = [NSMutableArray array];
  2343. [self.resourceModel.continousArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2344. if (obj.path && obj.previewImage) {
  2345. [continousMutArray addObject:obj];
  2346. }
  2347. }];
  2348. self.resourceModel.continousArray = continousMutArray;
  2349. NSMutableArray *singleMutArray = [NSMutableArray array];
  2350. [self.resourceModel.singleArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2351. if (obj.path && obj.previewImage) {
  2352. [singleMutArray addObject:obj];
  2353. }
  2354. }];
  2355. self.resourceModel.singleArray = singleMutArray;
  2356. NSMutableArray *movieMutArray = [NSMutableArray array];
  2357. [self.resourceModel.movieArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2358. if (obj.path && obj.previewImage) {
  2359. [movieMutArray addObject:obj];
  2360. }
  2361. }];
  2362. self.resourceModel.movieArray = movieMutArray;
  2363. NSMutableArray *panoramMutArray = [NSMutableArray array];
  2364. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2365. if (obj.path && obj.previewImage) {
  2366. [panoramMutArray addObject:obj];
  2367. }
  2368. }];
  2369. self.resourceModel.panoramArray = panoramMutArray;
  2370. NSMutableArray *aiPanoramMutArray = [NSMutableArray array];
  2371. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2372. if (obj.path && obj.previewImage) {
  2373. [aiPanoramMutArray addObject:obj];
  2374. }
  2375. }];
  2376. self.resourceModel.aiPanoramArray = aiPanoramMutArray;
  2377. switch (self.resourceModel.lastIndex) {
  2378. case SDK_CAPTURE_MODE_CONTINUOUS: {
  2379. if (self.resourceModel.continousArray.count > 0) {
  2380. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2381. image = model.previewImage;
  2382. } else {
  2383. if (self.resourceModel.singleArray.count > 0) {
  2384. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2385. image = model.previewImage;
  2386. } else if (self.resourceModel.movieArray.count > 0) {
  2387. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2388. image = model.previewImage;
  2389. } else if (self.resourceModel.panoramArray.count > 0) {
  2390. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2391. image = model.previewImage;
  2392. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2393. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2394. image = model.previewImage;
  2395. }
  2396. }
  2397. }
  2398. break;
  2399. case SDK_CAPTURE_MODE_SINGLE:{
  2400. if (self.resourceModel.singleArray.count > 0) {
  2401. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2402. image = model.previewImage;
  2403. } else {
  2404. if (self.resourceModel.continousArray.count > 0) {
  2405. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2406. image = model.previewImage;
  2407. } else if (self.resourceModel.movieArray.count > 0) {
  2408. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2409. image = model.previewImage;
  2410. } else if (self.resourceModel.panoramArray.count > 0) {
  2411. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2412. image = model.previewImage;
  2413. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2414. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2415. image = model.previewImage;
  2416. }
  2417. }
  2418. }
  2419. break;
  2420. case SDK_CAPTURE_MODE_MOVIE:{
  2421. if (self.resourceModel.movieArray.count > 0) {
  2422. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2423. image = model.previewImage;
  2424. } else {
  2425. if (self.resourceModel.singleArray.count > 0) {
  2426. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2427. image = model.previewImage;
  2428. } else if (self.resourceModel.continousArray.count > 0) {
  2429. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2430. image = model.previewImage;
  2431. } else if (self.resourceModel.panoramArray.count > 0) {
  2432. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2433. image = model.previewImage;
  2434. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2435. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2436. image = model.previewImage;
  2437. }
  2438. }
  2439. }
  2440. break;
  2441. case SDK_CAPTURE_MODE_PANORAMA:{
  2442. if (self.resourceModel.panoramArray.count > 0) {
  2443. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2444. image = model.previewImage;
  2445. } else {
  2446. if (self.resourceModel.singleArray.count > 0) {
  2447. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2448. image = model.previewImage;
  2449. } else if (self.resourceModel.movieArray.count > 0) {
  2450. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2451. image = model.previewImage;
  2452. } else if (self.resourceModel.continousArray.count > 0) {
  2453. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2454. image = model.previewImage;
  2455. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2456. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2457. image = model.previewImage;
  2458. }
  2459. }
  2460. }
  2461. break;
  2462. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:{
  2463. if (self.resourceModel.aiPanoramArray.count > 0) {
  2464. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2465. image = model.previewImage;
  2466. } else {
  2467. if (self.resourceModel.singleArray.count > 0) {
  2468. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2469. image = model.previewImage;
  2470. } else if (self.resourceModel.movieArray.count > 0) {
  2471. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2472. image = model.previewImage;
  2473. } else if (self.resourceModel.panoramArray.count > 0) {
  2474. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2475. image = model.previewImage;
  2476. } else if (self.resourceModel.continousArray.count > 0) {
  2477. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2478. image = model.previewImage;
  2479. }
  2480. }
  2481. }
  2482. break;
  2483. default:
  2484. break;
  2485. }
  2486. if (image) {
  2487. self.ablumImageView.image = image;
  2488. self.ablumImageView.hidden = NO;
  2489. self.discardPhotoButton.hidden = NO;
  2490. self.savePhotoButton.hidden = NO;
  2491. self.backButton.hidden = YES;
  2492. } else {
  2493. self.ablumImageView.image = nil;
  2494. self.ablumImageView.hidden = YES;
  2495. self.discardPhotoButton.hidden = YES;
  2496. self.savePhotoButton.hidden = YES;
  2497. self.backButton.hidden = NO;
  2498. }
  2499. [self updateNumberLabel];
  2500. });
  2501. }
  2502. #pragma mark - AVCaptureFileOutputRecordingDelegate
  2503. - (void)captureOutput:(AVCaptureFileOutput *)output didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections error:(NSError *)error{
  2504. //视频录制
  2505. [self.timerLabel updateWith:0];
  2506. BOOL recordedSuccessfully = YES;
  2507. if(error.code == AVErrorMaximumDurationReached){
  2508. } else if (error.code == AVErrorDiskFull){
  2509. dispatch_async(dispatch_get_main_queue(), ^{
  2510. [[NSNotificationCenter defaultCenter] postNotificationName:LenzSDKNotificationDiskIsFull object:error];
  2511. });
  2512. }else if (error.code == AVErrorSessionWasInterrupted){
  2513. }
  2514. id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
  2515. if (value) {
  2516. recordedSuccessfully = [value boolValue];
  2517. [self.recordTimer invalidate];
  2518. self.recordTimer = nil;
  2519. }
  2520. if(!recordedSuccessfully){
  2521. return;
  2522. }
  2523. OperationNodeMovie *node = nil;
  2524. if ([self.currentOperationNode isKindOfClass:[OperationNodeMovie class]]) {
  2525. node = (OperationNodeMovie *)self.currentOperationNode;
  2526. if (node.isRecording) {
  2527. [self.currentOperationNode takePhotoButtonTouched];
  2528. }
  2529. }
  2530. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  2531. itemModel.path = outputFileURL.absoluteString;
  2532. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2533. if (obj.model == self.mode) {
  2534. itemModel.cameraType = obj.cameraPositionString;
  2535. }
  2536. }];
  2537. itemModel.mode = self.mode;
  2538. itemModel.previewImage = [self rotateImageWith:[self videoFrameImageWith:outputFileURL]];
  2539. [self.resourceModel.movieArray addObject:itemModel];
  2540. self.resourceModel.lastIndex = self.mode;
  2541. [self updateViewStatus];
  2542. dispatch_async(dispatch_get_main_queue(), ^{
  2543. [self.currentOperationNode triggered];
  2544. self.thumbnailOritaionByCurrentVideoOrientation = UIImageOrientationUp;
  2545. });
  2546. }
  2547. - (BOOL)encodeFrame:(CMSampleBufferRef) sampleBuffer{
  2548. if (CMSampleBufferDataIsReady(sampleBuffer)) {
  2549. if (self.videoWriter.status == AVAssetWriterStatusUnknown) {
  2550. CMTime startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
  2551. [self.videoWriter startWriting];
  2552. [self.videoWriter startSessionAtSourceTime:startTime];
  2553. }
  2554. if (self.videoWriter.status == AVAssetWriterStatusFailed) {
  2555. return NO;
  2556. }
  2557. if (self.videoWriterInput.readyForMoreMediaData) {
  2558. [self.videoWriterInput appendSampleBuffer:sampleBuffer];
  2559. return YES;
  2560. }
  2561. }
  2562. return NO;
  2563. }
  2564. #pragma mark - AVCaptureAudioDataOutputSampleBufferDelegate
  2565. #pragma mark - UIViewControllerTransitioningDelegate
  2566. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
  2567. return [[CustomModalViewTransitionPresent alloc] init];
  2568. }
  2569. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
  2570. return [[CustomModalViewTransitionDismiss alloc] init];
  2571. }
  2572. #pragma mark - PhotoListViewControllerDelegate
  2573. //删除视频
  2574. - (void)deleteMovie: (MovieListCellModel*)model completion: (DeleteImageCompletionCallBackType)completion{
  2575. for (int i = 0; i < self.totalArray.count; i ++) {
  2576. UIImage *image = self.totalArray[i];
  2577. if (image == (UIImage *)model.movieModel.thumbnail) {
  2578. [self.totalArray removeObjectAtIndex:i];
  2579. [self.typeArray removeObjectAtIndex:i];
  2580. break;;
  2581. }
  2582. }
  2583. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2584. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2585. [curr deleteCacheForKey:model.movieModel.fileUrl.path completion:completion];
  2586. }
  2587. }
  2588. //连拍删除
  2589. - (void)deleteImage:(UIImage *)image completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2590. for (int i = 0; i < self.totalArray.count; i ++) {
  2591. UIImage *img = self.totalArray[i];
  2592. if (img == image) {
  2593. [self.totalArray removeObjectAtIndex:i];
  2594. [self.typeArray removeObjectAtIndex:i];
  2595. break;;
  2596. }
  2597. }
  2598. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2599. if([curr respondsToSelector:@selector(deleteCacheForImage:completion:)]){
  2600. [curr deleteCacheForImage:image completion:completion];
  2601. }
  2602. }
  2603. - (void)deleteImageWithName:(NSString *)name completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2604. id<OperationNodeProtocol> curr = self.currentOperationNode;
  2605. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2606. [curr deleteCacheForKey:name completion:completion];
  2607. }
  2608. }
  2609. #pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate
  2610. - (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
  2611. @autoreleasepool {
  2612. if (connection == [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo]) {
  2613. [self.stitchkLock lock];
  2614. OperationNodeVideoBase *base = nil;
  2615. if ([self.currentOperationNode isKindOfClass:[OperationNodeVideoBase class]]) {
  2616. base = (OperationNodeVideoBase *)self.currentOperationNode;
  2617. }
  2618. if (self.isVideoStitchStopedWhenRecording &&
  2619. (self.stitchResult != LenVideoStitchResultFail && self.stitchResult != LenVideoStitchResultStitchFail)) {
  2620. [self updateViewStatusWhenStitchSave:YES];
  2621. self.isStitchBigImage = YES;
  2622. }
  2623. LenVideoStitchDirction dirction = LenVideoStitchDirctionLeft;
  2624. if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewUp) {
  2625. if (self.currentTgDirection == TgDirectionDown) {
  2626. dirction = LenVideoStitchDirctionDown;
  2627. } else {
  2628. dirction = LenVideoStitchDirctionUp;
  2629. }
  2630. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewDown) {
  2631. if (self.currentTgDirection == TgDirectionDown) {
  2632. dirction = LenVideoStitchDirctionUp;
  2633. } else {
  2634. dirction = LenVideoStitchDirctionDown;
  2635. }
  2636. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewLeft) {
  2637. if (self.currentTgDirection == TgDirectionDown) {
  2638. dirction = LenVideoStitchDirctionRight;
  2639. } else {
  2640. dirction = LenVideoStitchDirctionLeft;
  2641. }
  2642. } else if (self.panoramOrientationGuideView.selectedItemIndex == PanoramaOrientationViewRight) {
  2643. if (self.currentTgDirection == TgDirectionDown) {
  2644. dirction = LenVideoStitchDirctionLeft;
  2645. } else {
  2646. dirction = LenVideoStitchDirctionRight;
  2647. }
  2648. } else {
  2649. dirction = LenVideoStitchDirctionAny;
  2650. }
  2651. [LenStitcher videoStitchWith:sampleBuffer
  2652. dirction:dirction
  2653. isStop:self.isVideoStitchStopedWhenRecording
  2654. complete:^(LenVideoStitchResult result, LenVideoStitchNeedSave needSave) {
  2655. self.stitchResult = result;
  2656. self.isVideoStitchStopedWhenRecording = NO;
  2657. UIImage *image = [LenStitcher getCurrentPanoramaShowImage];
  2658. UIImage *saveImage = [self rotateImageWith:image];
  2659. LenzResourceItemModel *model = nil;
  2660. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2661. model = self.resourceModel.panoramArray.lastObject;
  2662. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2663. model = self.resourceModel.aiPanoramArray.lastObject;
  2664. }
  2665. if (!image || !model) {
  2666. [self.stitchkLock unlock];
  2667. return;
  2668. }
  2669. if (result == LenVideoStitchResultSuccess) {
  2670. dispatch_async(dispatch_get_main_queue(), ^{
  2671. if (self.isStitchBigImage) {
  2672. //保存大图拼接路径
  2673. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2674. if (obj.model == self.mode) {
  2675. model.cameraType = obj.cameraPositionString;
  2676. }
  2677. }];
  2678. model.mode = self.mode;
  2679. if ([LenStitcher getCurrentPanoramaShow]) {
  2680. model.image = image;
  2681. model.previewImage = saveImage;
  2682. NSString *path = [LenzDataManager saveImageWith:UIImageJPEGRepresentation(saveImage, .8) mode:self.mode];
  2683. model.path = path;
  2684. }
  2685. [self updateViewStatusWhenStitchSave:NO];
  2686. self.isStitchBigImage = NO;
  2687. [self.panoramaGuideView clearImage];
  2688. [self updateViewStatus];
  2689. [self.panoramaGuideView showImageWith:nil];
  2690. } else {
  2691. if (base.isRecording) {
  2692. __block BOOL keyFrame = NO;
  2693. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2694. if (obj.model == self.mode) {
  2695. keyFrame = [obj.keyFrame boolValue];
  2696. }
  2697. }];
  2698. if (needSave && keyFrame) {
  2699. NSString *path = [LenzDataManager saveImageWith:UIImageJPEGRepresentation(saveImage, .6) mode:self.mode];
  2700. if (path) {
  2701. [model.keyFrame addObject:path];
  2702. }
  2703. }
  2704. if (self.panoramOrientationGuideView.selectedItemIndex != PanoramaOrientationViewAny) {
  2705. [self.panoramaGuideView showImageWith:image];
  2706. } else {
  2707. self.ablumImageView.hidden = NO;
  2708. self.ablumImageView.image = saveImage;
  2709. }
  2710. }
  2711. }
  2712. self.resourceModel.lastIndex = self.mode;
  2713. });
  2714. } else {
  2715. if (!base.isRecording) {
  2716. //停止拼接,移除保存中 非success数据
  2717. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2718. NSMutableArray *array = [NSMutableArray array];
  2719. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2720. if (obj.path.length) {
  2721. [array addObject:obj];
  2722. }
  2723. }];
  2724. self.resourceModel.panoramArray = array;
  2725. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2726. NSMutableArray *array = [NSMutableArray array];
  2727. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2728. if (obj.path.length) {
  2729. [array addObject:obj];
  2730. }
  2731. }];
  2732. self.resourceModel.aiPanoramArray = array;
  2733. }
  2734. [self updateViewStatusWhenStitchSave:NO];
  2735. [self updateViewStatus];
  2736. [self.stitchkLock unlock];
  2737. return;
  2738. }
  2739. if (result == LenVideoStitchResultFail || result == LenVideoStitchResultStitchFail) {
  2740. if (result == LenVideoStitchResultFail) {
  2741. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接失败,流程结束"];
  2742. } else {
  2743. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接大图失败,流程结束"];
  2744. }
  2745. self.isVideoStitchStopedWhenRecording = NO;
  2746. dispatch_async(dispatch_get_main_queue(), ^{
  2747. [base takePhotoButtonTouched];
  2748. [self stopMotion];
  2749. [self removeLastStich];
  2750. [self updateViewStatusWhenStitchFail];
  2751. [self.panoramaGuideView clearImage];
  2752. [self updateViewStatus];
  2753. [self.panoramaGuideView showImageWith:nil];
  2754. });
  2755. [SVProgressHUD dismissWithDelay:3 completion:^{
  2756. }];
  2757. } else if(result == LenVideoStitchResultSlowMore) {
  2758. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"目标物较少,请对准目标物低速且匀速拍摄"];
  2759. } else if (result == LenVideoStitchResultSlow) {
  2760. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"目标物较少,请对准目标物低速且匀速拍摄"];
  2761. } else {
  2762. // [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"请勿往反方向移动"];
  2763. }
  2764. }
  2765. [self.stitchkLock unlock];
  2766. }];
  2767. }
  2768. }
  2769. }
  2770. - (void)removeLastStich {
  2771. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2772. if (self.resourceModel.panoramArray.count > 0) {
  2773. [self.resourceModel.panoramArray removeLastObject];
  2774. }
  2775. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2776. if (self.resourceModel.aiPanoramArray.count > 0) {
  2777. [self.resourceModel.aiPanoramArray removeLastObject];
  2778. }
  2779. }
  2780. }
  2781. #pragma mark - Navigation
  2782. // In a storyboard-based application, you will often want to do a little preparation before navigation
  2783. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  2784. // Get the new view controller using [segue destinationViewController].
  2785. if([segue.identifier isEqualToString:@"preview_single"]){
  2786. PreviewSingleViewController* dst = segue.destinationViewController;
  2787. dst.singleModeNode = self.currentOperationNode;
  2788. if (self.resourceModel.singleArray.count > 0) {
  2789. LenzResourceItemModel *model = self.resourceModel.singleArray.firstObject;
  2790. dst.image = model.image;
  2791. }
  2792. }
  2793. }
  2794. - (void)clearSingleData {
  2795. [self.resourceModel.singleArray removeAllObjects];
  2796. [self updateViewStatus];
  2797. }
  2798. - (BOOL)shouldAutorotate {
  2799. return NO;
  2800. }
  2801. - (UIInterfaceOrientationMask)supportedInterfaceOrientations {
  2802. return UIInterfaceOrientationMaskPortrait;
  2803. }
  2804. - (UIImage *)videoFrameImageWith:(NSURL *)url {
  2805. AVURLAsset* asset = [[AVURLAsset alloc] initWithURL:url options:nil];
  2806. AVAssetImageGenerator *generateImg = [[AVAssetImageGenerator alloc] initWithAsset:asset];
  2807. NSError *err = NULL;
  2808. CMTime time = CMTimeMake(1, 65);
  2809. CGImageRef refImg = [generateImg copyCGImageAtTime:time actualTime:NULL error:&err];
  2810. UIImage *frameImage= [[UIImage alloc] initWithCGImage:refImg scale:1.0 orientation:self.thumbnailOritaionByCurrentVideoOrientation];
  2811. return frameImage;
  2812. }
  2813. - (UIImage *)rotateImageWith:(UIImage *)image {
  2814. if (self.currentTgDirection == TgDirectionPortrait) {
  2815. return image;
  2816. } else if (self.currentTgDirection == TgDirectionLeft) {
  2817. OperationNodeAIPanorama *aiPan = nil;
  2818. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  2819. aiPan = self.currentOperationNode;
  2820. }
  2821. if (self.mode == SDK_CAPTURE_MODE_PANORAMA || (aiPan && aiPan.AIType == OperationAITypeLongPress)) {
  2822. image = [[UIImage alloc]initWithCGImage:image.CGImage
  2823. scale:1.0
  2824. orientation:UIImageOrientationLeft];
  2825. } else {
  2826. image = [[UIImage alloc]initWithCGImage:image.CGImage
  2827. scale:1.0
  2828. orientation:UIImageOrientationUp];
  2829. }
  2830. return image;
  2831. } else if (self.currentTgDirection == TgDirectionRight) {
  2832. OperationNodeAIPanorama *aiPan = nil;
  2833. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  2834. aiPan = self.currentOperationNode;
  2835. }
  2836. if (self.mode == SDK_CAPTURE_MODE_PANORAMA || (aiPan && aiPan.AIType == OperationAITypeLongPress)) {
  2837. image = [[UIImage alloc]initWithCGImage:image.CGImage
  2838. scale:1.0
  2839. orientation:UIImageOrientationRight];
  2840. } else {
  2841. image = [[UIImage alloc]initWithCGImage:image.CGImage
  2842. scale:1.0
  2843. orientation:UIImageOrientationDown];
  2844. }
  2845. return image;
  2846. } else if (self.currentTgDirection == TgDirectionDown) {
  2847. OperationNodeAIPanorama *aiPan = nil;
  2848. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  2849. aiPan = self.currentOperationNode;
  2850. }
  2851. if (self.mode == SDK_CAPTURE_MODE_PANORAMA || (aiPan && aiPan.AIType == OperationAITypeLongPress)) {
  2852. image = [[UIImage alloc]initWithCGImage:image.CGImage
  2853. scale:1.0
  2854. orientation:UIImageOrientationDown];
  2855. } else {
  2856. image = [[UIImage alloc]initWithCGImage:image.CGImage
  2857. scale:1.0
  2858. orientation:UIImageOrientationLeft];
  2859. }
  2860. return image;
  2861. }
  2862. return image;
  2863. }
  2864. @end