PCSBaseViewController.m 136 KB

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