PCSBaseViewController.m 135 KB

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