PCSBaseViewController.m 139 KB

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