PCSBaseViewController.m 136 KB

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