PCSBaseViewController.m 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629
  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 "AVCapturePhotoOutput+VersionAdaptor.h"
  12. #import "PCSRoundButton.h"
  13. #import "PCSModeList.h"
  14. #import "UIImage+ext.h"
  15. #import "PCSTools.h"
  16. #import "OperationNodeProtocol.h"
  17. #import "OperationNodeSingle.h"
  18. #import "OperationNodeMultiple.h"
  19. #import "OperationNodePanorama.h"
  20. #import "QuitMultipleModeAlertViewController.h"
  21. #import <CoreMotion/CoreMotion.h>
  22. #import "OperationNodeMovie.h"
  23. #import "SDKParameters.h"
  24. #import "PhotoListViewController.h"
  25. #import "CustomModalViewTransition.h"
  26. #import "MovieListViewController.h"
  27. #import "TimerLabel.h"
  28. #import "MoviePlayerViewController.h"
  29. #import "PanoramaOrientationView.h"
  30. #import "PanoramaGuideView.h"
  31. #import "Renderer.h"
  32. #import "CameraTextureRenderPass.h"
  33. #import "LenzSDKConstant.h"
  34. #import "TensorFlowWrapper.h"
  35. #import "DBManager.h"
  36. #import <Photos/Photos.h>
  37. #import "BaseViewTapGestureDelegate.h"
  38. #import "MovieListCellModel.h"
  39. #import "PreviewSingleViewController.h"
  40. #import "OperationNodeAIPanorama.h"
  41. #import "PhotoAlbumListViewController.h"
  42. #import "PhotoAlbumModel.h"
  43. #import "LenStitcher.h"
  44. #import "LenzDataManager.h"
  45. #import "LenzHeader.h"
  46. #import "LenzCachedResourceModel.h"
  47. #import "LenzDataManager.h"
  48. #import "PCSPreviewViewController.h"
  49. #import "SVProgressHUD.h"
  50. #define MODE_LIST_INDEX_2_MODE_ENUM(x) ((x))
  51. // PCS means panoramic camera sdk
  52. @interface PCSBaseViewController ()<AVCapturePhotoCaptureDelegate,
  53. AVCaptureFileOutputRecordingDelegate,
  54. AVCaptureAudioDataOutputSampleBufferDelegate,
  55. UIViewControllerTransitioningDelegate,
  56. AVCaptureVideoDataOutputSampleBufferDelegate,
  57. PhotoListViewControllerDelegate,
  58. PanoramaOrientationViewDelegate>
  59. @property (nonatomic, assign) CGFloat accX;
  60. @property (nonatomic, nullable, readonly) AVCaptureDevice* currentCamera;
  61. @property (nonatomic, nullable, readonly) AVCaptureDeviceInput* currentCameraInput;
  62. @property (nonatomic, strong) AVCaptureSession* captureSession;
  63. @property (nonatomic, strong) AVCaptureVideoDataOutput* videoDataOutput;
  64. @property (nonatomic, strong) AVCaptureMovieFileOutput* movieFileOutput;
  65. @property (nonatomic, strong) AVCapturePhotoOutput* photoOutput;
  66. @property (nonatomic, strong) AVCapturePhotoSettings* outputSettings;
  67. @property (nonatomic, copy) dispatch_queue_t videoDataQueue;
  68. @property (nonatomic, strong) AVAssetWriter* videoWriter;
  69. @property (nonatomic, strong) AVAssetWriterInput* videoWriterInput;
  70. @property (nonatomic, assign) BOOL cameraPrepared;
  71. @property (nonatomic, assign) BOOL flag;
  72. @property (nonatomic, assign) BOOL hasCache;
  73. @property (nonatomic, strong) UIView* focusView;
  74. @property (nonatomic, strong, nullable) NSTimer* recordTimer;
  75. @property (nonatomic) dispatch_source_t touchSourceTimer;
  76. @property (nonatomic) CGFloat touchTime;
  77. @property (nonatomic, strong, nullable) NSTimer* motionTimer;
  78. @property (nonatomic, strong) BaseViewTapGestureDelegate* tapDelegate;
  79. /**
  80. key: PhotographModeEnum
  81. value: subclass of OperationNodeProtocol
  82. */
  83. @property (nonatomic, strong) NSDictionary<NSNumber*, id<OperationNodeProtocol>>* operationNodes;
  84. @property (nonatomic, strong) NSArray<id<OperationNodeProtocol>>* operationNodesArray;
  85. @property (nonatomic) dispatch_semaphore_t videoStitchSemaphore;
  86. //@property (nonatomic) NSMutableDictionary <NSString * , NSMutableArray *> *resultDict;
  87. //@property (nonatomic) UIImageView *testImageView;
  88. @property (nonatomic) LenzCachedResourceModel *resourceModel;
  89. //@property (nonatomic) dispatch_source_t stitchTimer;
  90. @property (nonatomic) UIView *stitchView;
  91. @property (nonatomic) UIImageView *stitchImageView;
  92. @property (nonatomic) UILabel *stitchLabel;
  93. @property (nonatomic) CABasicAnimation *loadingAnimation;
  94. @property (nonatomic) BOOL isStitchBigImage;
  95. @property (nonatomic) CGFloat brightnessValue;
  96. @property (nonatomic) CMMotionManager *motionManager;
  97. @property (nonatomic) BOOL isTakePhoto;
  98. @property (nonatomic) NSLock *stitchkLock;
  99. @property (nonatomic) LenVideoStitchResult stitchResult;
  100. @property (nonatomic) NSNumber *startPitchX;
  101. @property (nonatomic) NSNumber *startRollY;
  102. @end
  103. @implementation PCSBaseViewController
  104. #pragma mark - Life Circle
  105. - (void)dealloc{
  106. [self stopAllSensors];
  107. [[NSNotificationCenter defaultCenter] removeObserver:self];
  108. // dispatch_semaphore_signal(self.semaphore);
  109. [[LenzDBManager shared] close];
  110. }
  111. - (void)viewDidLayoutSubviews{
  112. [super viewDidLayoutSubviews];
  113. // [self updatePreViewLayer];
  114. // self.previewLayer.frame = self.view.layer.bounds;
  115. }
  116. - (void)awakeFromNib{
  117. [super awakeFromNib];
  118. [self setup];
  119. }
  120. - (void)viewDidLoad {
  121. [super viewDidLoad];
  122. // Do any additional setup after loading the view.
  123. // [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
  124. [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
  125. [SVProgressHUD setMinimumDismissTimeInterval:1.5];
  126. [SVProgressHUD setMaximumDismissTimeInterval:3];
  127. [SVProgressHUD setFont:[UIFont systemFontOfSize:14]];
  128. self.stitchkLock = [[NSLock alloc]init];
  129. self.totalArray = [[NSMutableArray alloc]init];
  130. self.cachesArray = [[NSMutableArray alloc]init];
  131. self.typeArray = [[NSMutableArray alloc]init];
  132. self.resourceModel = [[LenzCachedResourceModel alloc]init];
  133. self.motionManager = [[CMMotionManager alloc]init];
  134. self.motionManager.deviceMotionUpdateInterval = 1/5;
  135. // self.resultDict = [NSMutableDictionary dictionary];
  136. if (!JK_IS_IPHONE_X) {
  137. self.safeBottom.constant = 25;
  138. self.safeTop.constant = 15;
  139. }else{
  140. self.safeBottom.constant = 0;
  141. }
  142. [self.timerLabel updateWith:100];
  143. self.albumButton.layer.cornerRadius = 6;
  144. self.albumButton.clipsToBounds = YES;
  145. switch ([SDKParameters shared].flashMode) {
  146. case SDK_FLASH_MODE_AUTO:{
  147. self.outputSettings.flashMode = AVCaptureFlashModeAuto;
  148. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-auto-btn"] forState:UIControlStateNormal];
  149. break;
  150. }
  151. case SDK_FLASH_MODE_ON:{
  152. self.outputSettings.flashMode = AVCaptureFlashModeOn;
  153. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-btn"] forState:UIControlStateNormal];
  154. break;
  155. }
  156. case SDK_FLASH_MODE_OFF:{
  157. self.outputSettings.flashMode = AVCaptureFlashModeOff;
  158. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-disable-btn"] forState:UIControlStateNormal];
  159. break;
  160. }
  161. default:
  162. break;
  163. }
  164. [PCSMotionManager shared];
  165. __weak typeof(self) weakself = self;
  166. [self.modeList reloadWith:self.operationNodesArray];
  167. self.modeList.indexChangedHandler = ^BOOL(NSUInteger newIndex, NSUInteger oldIndex) {
  168. __strong typeof(weakself) strongSelf = weakself;
  169. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_CLEAR) {
  170. BOOL needAlert = NO;
  171. switch (self.mode) {
  172. case SDK_CAPTURE_MODE_CONTINUOUS:
  173. needAlert = self.resourceModel.continousArray.count;
  174. break;
  175. case SDK_CAPTURE_MODE_SINGLE:
  176. needAlert = self.resourceModel.singleArray.count;
  177. break;
  178. case SDK_CAPTURE_MODE_MOVIE:
  179. needAlert = self.resourceModel.movieArray.count;
  180. break;
  181. case SDK_CAPTURE_MODE_PANORAMA:
  182. needAlert = self.resourceModel.panoramArray.count;
  183. break;
  184. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  185. needAlert = self.resourceModel.aiPanoramArray.count;
  186. break;
  187. default:
  188. break;
  189. }
  190. if (needAlert) {
  191. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"切换模式会清除已拍摄数据,请确认" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  192. [alertController dismissViewControllerAnimated:NO completion:^{}];
  193. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  194. switch (self.mode) {
  195. case SDK_CAPTURE_MODE_CONTINUOUS: {
  196. [self.resourceModel.continousArray removeAllObjects];
  197. [self updateViewStatus];
  198. }
  199. break;
  200. case SDK_CAPTURE_MODE_SINGLE: {
  201. [self.resourceModel.singleArray removeAllObjects];
  202. [self updateViewStatus];
  203. }
  204. break;
  205. case SDK_CAPTURE_MODE_MOVIE:
  206. {
  207. [self.resourceModel.movieArray removeAllObjects];
  208. [self updateViewStatus];
  209. }
  210. break;
  211. case SDK_CAPTURE_MODE_PANORAMA:
  212. {
  213. [self.resourceModel.panoramArray removeAllObjects];
  214. [self updateViewStatus];
  215. }
  216. break;
  217. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  218. {
  219. [self.resourceModel.aiPanoramArray removeAllObjects];
  220. [self updateViewStatus];
  221. }
  222. break;
  223. default:
  224. break;
  225. }
  226. self.modeList.index = newIndex;
  227. [self.modeList updateItemsConstraints];
  228. [strongSelf modeWillChange:newIndex oldIndex:oldIndex];
  229. id<OperationNodeProtocol> oldModelNode = strongSelf.currentOperationNode;
  230. PhotographModeEnum mode = (PhotographModeEnum)MODE_LIST_INDEX_2_MODE_ENUM(newIndex);
  231. strongSelf.mode = mode;
  232. self.ai_fullView.hidden = !(mode == SDK_CAPTURE_MODE_PANORAMA);
  233. [strongSelf modeDidChange:newIndex oldIndex:oldIndex];
  234. if([oldModelNode respondsToSelector:@selector(didQuit)]){
  235. [oldModelNode didQuit];
  236. }
  237. [alertController dismissViewControllerAnimated:NO completion:^{}];
  238. }];
  239. return NO;
  240. }
  241. // return YES;
  242. }
  243. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_RETAIN) {
  244. //保留模式无单拍
  245. if (newIndex > 0) {
  246. newIndex += 1;
  247. }
  248. if (oldIndex > 0) {
  249. oldIndex += 1;
  250. }
  251. }
  252. [strongSelf modeWillChange:newIndex oldIndex:oldIndex];
  253. id<OperationNodeProtocol> oldModelNode = strongSelf.currentOperationNode;
  254. PhotographModeEnum mode = (PhotographModeEnum)MODE_LIST_INDEX_2_MODE_ENUM(newIndex);
  255. strongSelf.mode = mode;
  256. self.ai_fullView.hidden = !(mode == SDK_CAPTURE_MODE_PANORAMA);
  257. [strongSelf modeDidChange:newIndex oldIndex:oldIndex];
  258. if([oldModelNode respondsToSelector:@selector(didQuit)]){
  259. [oldModelNode didQuit];
  260. }
  261. return YES;
  262. };
  263. [self modeWillChange:[SDKParameters shared].modeIndex oldIndex:0lu];
  264. self.modeList.mode = [SDKParameters shared].modeIndex;
  265. self.mode = [SDKParameters shared].modeIndex;
  266. // dispatch_async(dispatch_get_main_queue(), ^{
  267. [self modeDidChange:[SDKParameters shared].modeIndex oldIndex:0lu];
  268. // });
  269. UIVisualEffectView* effectView = [[UIVisualEffectView alloc] initWithEffect: [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
  270. effectView.alpha = 0.8;
  271. effectView.effect = nil;
  272. self.effectView = effectView;
  273. [self.view insertSubview:self.effectView belowSubview:self.backButton];
  274. [self.effectView mas_makeConstraints:^(MASConstraintMaker *make) {
  275. make.edges.equalTo(self.view);
  276. }];
  277. if(!self.cameraPrepared){
  278. [self prepareCamera];
  279. }
  280. self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];
  281. [self.view addGestureRecognizer:self.panGesture];
  282. // self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
  283. // self.tapGesture.delegate = self.tapDelegate;
  284. // [self.view addGestureRecognizer:self.tapGesture];
  285. UIImageView* loadingImageView = [[UIImageView alloc] initWithImage:[UIImage sdkImageNamed:@"loading"]];
  286. self.loadingIndicator = loadingImageView;
  287. self.loadingIndicator.hidden = YES;
  288. [self.view addSubview:self.loadingIndicator];
  289. [loadingImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
  290. make.center.equalTo(self.view);
  291. }];
  292. self.savePhotoButton.titleLabel.textColor = [UIColor whiteColor];
  293. self.discardPhotoButton.titleLabel.textColor = [UIColor whiteColor];
  294. // [self.takePhotoButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  295. // make.centerX.equalTo(self.view);
  296. // make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
  297. // }];
  298. [self updateUIByMode];
  299. self.panoramOrientationGuideView.delegate = self;
  300. [self.view addSubview:self.panoramaGuideView];
  301. [self panoramaOrientationViewslt:(PanoramaOrientationViewLeft)];
  302. self.panoramaGuideView.hidden = YES;
  303. self.ablumImageView = [[UIImageView alloc]init];
  304. [self.view addSubview:self.ablumImageView];
  305. self.ablumImageView.layer.cornerRadius = 6;
  306. self.ablumImageView.layer.masksToBounds = YES;
  307. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showPreview:)];
  308. [self.ablumImageView addGestureRecognizer:tap];
  309. self.ablumImageView.userInteractionEnabled = YES;
  310. self.ablumImageView.hidden = YES;
  311. // self.ablumImageView.backgroundColor = [UIColor redColor];
  312. self.ablumImageView.contentMode = UIViewContentModeScaleAspectFill;
  313. [self.ablumImageView mas_makeConstraints:^(MASConstraintMaker *make) {
  314. make.centerY.mas_equalTo(self.takePhotoButton);
  315. make.left.mas_equalTo(20);
  316. make.width.height.mas_equalTo(60);
  317. // make.top.left.mas_equalTo(50);
  318. // make.width.height.mas_equalTo(300);
  319. }];
  320. UILongPressGestureRecognizer *ges = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressGes:)];
  321. // ges.numberOfTapsRequired = 1;
  322. ges.minimumPressDuration = 1;
  323. [self.takePhotoButton addGestureRecognizer:ges];
  324. self.timerLabel.layer.cornerRadius = 6;
  325. self.timerLabel.layer.masksToBounds = YES;
  326. [self.ai_fullView addTarget:self action:@selector(alFullViewAction:) forControlEvents:UIControlEventTouchUpInside];
  327. [self.view addSubview:self.stitchView];
  328. [self.stitchView mas_makeConstraints:^(MASConstraintMaker *make) {
  329. make.centerY.mas_equalTo(self.view);
  330. make.centerX.mas_equalTo(self.view);
  331. make.width.mas_offset(200);
  332. make.height.mas_offset(200);
  333. }];
  334. }
  335. - (void)viewWillAppear:(BOOL)animated{
  336. [super viewWillAppear:animated];
  337. self.panGesture.enabled = YES;
  338. if([self.currentOperationNode respondsToSelector:@selector(updateUI)])
  339. [self.currentOperationNode updateUI];
  340. }
  341. - (void)viewDidAppear:(BOOL)animated{
  342. [super viewDidAppear:animated];
  343. if(self.cameraPrepared){
  344. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) {
  345. case AVAuthorizationStatusAuthorized:
  346. [self startCaptureSession];
  347. [[PCSMotionManager shared] startAccelerometerUpdates];
  348. break;
  349. case AVAuthorizationStatusNotDetermined:{
  350. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  351. if(granted){
  352. [self startCaptureSession];
  353. [[PCSMotionManager shared] startAccelerometerUpdates];
  354. }
  355. else{
  356. [[NSNotificationCenter defaultCenter] postNotificationName:CameraNotificationNotPermission object:self];
  357. }
  358. }];
  359. break;
  360. }
  361. case AVAuthorizationStatusDenied:{
  362. [[NSNotificationCenter defaultCenter] postNotificationName:CameraNotificationNotPermission object:self];
  363. break;
  364. }
  365. case AVAuthorizationStatusRestricted:
  366. break;
  367. default:
  368. break;
  369. }
  370. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
  371. case AVAuthorizationStatusAuthorized:
  372. [self setupMicrophone];
  373. break;
  374. case AVAuthorizationStatusNotDetermined:{
  375. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
  376. if(granted){
  377. [self setupMicrophone];
  378. }
  379. else{
  380. [[NSNotificationCenter defaultCenter] postNotificationName:MicrophoneNotificationNotPermission object:self];
  381. }
  382. }];
  383. break;
  384. }
  385. case AVAuthorizationStatusDenied:{
  386. [[NSNotificationCenter defaultCenter] postNotificationName:MicrophoneNotificationNotPermission object:self];
  387. break;
  388. }
  389. case AVAuthorizationStatusRestricted:
  390. break;
  391. default:
  392. break;
  393. }
  394. }
  395. }
  396. - (void)viewWillDisappear:(BOOL)animated{
  397. [super viewWillDisappear:animated];
  398. [self stopCaptureSession];
  399. [[PCSMotionManager shared] stopAccelerometerUpdates];
  400. }
  401. - (UIView *)stitchView {
  402. if (!_stitchView) {
  403. _stitchView = [[UIView alloc]init];
  404. [_stitchView addSubview:self.stitchImageView];
  405. [self.stitchImageView mas_makeConstraints:^(MASConstraintMaker *make) {
  406. make.centerX.mas_equalTo(_stitchView);
  407. make.top.mas_equalTo(0);
  408. make.width.height.mas_equalTo(68);
  409. }];
  410. [_stitchView addSubview:self.stitchLabel];
  411. [self.stitchLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  412. make.top.mas_equalTo(self.stitchImageView.mas_bottom).mas_offset(20);
  413. make.centerX.mas_equalTo(self.stitchImageView);
  414. }];
  415. _stitchView.hidden = YES;
  416. }
  417. return _stitchView;
  418. }
  419. - (UIImageView *)stitchImageView {
  420. if (!_stitchImageView) {
  421. _stitchImageView = [[UIImageView alloc]init];
  422. _stitchImageView.image = [UIImage loadNamed:@"loading"];
  423. }
  424. return _stitchImageView;
  425. }
  426. - (CABasicAnimation *)loadingAnimation {
  427. if (!_loadingAnimation) {
  428. _loadingAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
  429. _loadingAnimation.fromValue = [NSNumber numberWithFloat:0.f];
  430. _loadingAnimation.toValue = [NSNumber numberWithFloat: M_PI *2];
  431. _loadingAnimation.duration = 3;
  432. _loadingAnimation.autoreverses = NO;
  433. _loadingAnimation.fillMode = kCAFillModeForwards;
  434. _loadingAnimation.repeatCount = MAXFLOAT;
  435. }
  436. return _loadingAnimation;
  437. }
  438. - (UILabel *)stitchLabel {
  439. if (!_stitchLabel) {
  440. _stitchLabel = [[UILabel alloc]init];
  441. _stitchLabel.text = @"正在拼接中,请稍等";
  442. _stitchLabel.font = [UIFont systemFontOfSize:12];
  443. _stitchLabel.textColor = [UIColor whiteColor];
  444. }
  445. return _stitchLabel;
  446. }
  447. #pragma mark - Private Method
  448. //+ (instancetype)makeViewController{
  449. // UIStoryboard* sb = [UIStoryboard storyboardWithName:[PCSTools shared].mainStoryboardName bundle:[PCSTools sdkBundle]];
  450. // return ;
  451. //}
  452. - (void)alFullViewAction:(UIButton *)button {
  453. // self.currentOperationNode.needHiddenDir = !self.currentOperationNode.needHiddenDir;
  454. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  455. OperationNodePanorama *pan = nil;
  456. if ([self.currentOperationNode isKindOfClass:[OperationNodePanorama class]]) {
  457. pan = self.currentOperationNode;
  458. pan.needHiddenDir = !pan.needHiddenDir;
  459. }
  460. self.panoramOrientationGuideView.hidden = pan.needHiddenDir;
  461. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  462. OperationNodeAIPanorama *aiPan = nil;
  463. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  464. aiPan = self.currentOperationNode;
  465. aiPan.needHiddenDir = !aiPan.needHiddenDir;
  466. }
  467. self.panoramOrientationGuideView.hidden = aiPan.needHiddenDir;
  468. }
  469. }
  470. - (void)showPreview:(UITapGestureRecognizer *)tap {
  471. if (self.ablumImageView.hidden) {
  472. return;
  473. }
  474. if(self.mode != SDK_CAPTURE_MODE_SINGLE) {
  475. PCSPreviewViewController *vc = [[PCSPreviewViewController alloc]init];
  476. vc.model = self.resourceModel;
  477. vc.dataChangeBlock = ^{
  478. [self updateViewStatus];
  479. };
  480. [self presentViewController:vc animated:YES completion:nil];
  481. } else {
  482. PreviewSingleViewController* dst = [[PreviewSingleViewController alloc]init];
  483. dst.singleModeNode = self.currentOperationNode;
  484. if (self.resourceModel.singleArray.count > 0) {
  485. LenzResourceItemModel *model = self.resourceModel.singleArray.firstObject;
  486. dst.image = model.image;
  487. }
  488. [self presentViewController:dst animated:YES completion:nil];
  489. }
  490. }
  491. + (instancetype)initWithParams:(NSDictionary *)params complete:(PCSBaseVCCompleteBLock)complete {
  492. [self parser:params];
  493. UIStoryboard* sb = [UIStoryboard storyboardWithName:[PCSTools shared].mainStoryboardName bundle:[PCSTools sdkBundle]];
  494. PCSBaseViewController *vc = (PCSBaseViewController *)[sb instantiateViewControllerWithIdentifier:@"sample"];
  495. vc.completeBlock = complete;
  496. return vc;
  497. }
  498. #pragma mark - Config param
  499. + (void)parser: (NSDictionary*)params{
  500. SDKParameters* sdkParams = [SDKParameters shared];
  501. NSString* retainedMode = params[@"dataRetainedMode"];
  502. if(retainedMode != nil){
  503. if([retainedMode isEqual:@"retain"]){
  504. sdkParams.retainedMode = SDK_DATA_RETAINED_RETAIN;
  505. }
  506. else if([retainedMode isEqual:@"clear"]){
  507. sdkParams.retainedMode = SDK_DATA_RETAINED_CLEAR;
  508. }
  509. // if([retainedMode isEqual:@"userConfirm"]){
  510. // sdkParams.retainedMode = SDK_DATA_RETAINED_USER_CONFIRM;
  511. // }
  512. }
  513. NSArray* arr = params[@"cameraMode"];
  514. if(arr != nil){
  515. NSDictionary<NSString*, NSNumber*>* table = @{
  516. @"continuous": @(SDK_CAPTURE_MODE_CONTINUOUS),
  517. @"single" : @(SDK_CAPTURE_MODE_SINGLE),
  518. @"video" : @(SDK_CAPTURE_MODE_MOVIE),
  519. @"panorama" : @(SDK_CAPTURE_MODE_PANORAMA),
  520. @"panoramaPlus" : @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)
  521. };
  522. NSMutableArray<NSNumber*>* modeIndiciesTable = [NSMutableArray arrayWithArray:@[
  523. @(SDK_CAPTURE_MODE_CONTINUOUS),
  524. @(SDK_CAPTURE_MODE_SINGLE),
  525. @(SDK_CAPTURE_MODE_MOVIE),
  526. @(SDK_CAPTURE_MODE_PANORAMA),
  527. @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA),
  528. ]];
  529. NSMutableDictionary<NSNumber*, NSNumber*>* modes = [NSMutableDictionary dictionary];
  530. [arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  531. if(table[obj] != nil){
  532. modes[table[obj]] = @(YES);
  533. }
  534. }];
  535. [modeIndiciesTable enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  536. if(modes[obj] == nil){
  537. [modeIndiciesTable removeObject:obj];
  538. }
  539. }];
  540. sdkParams.modeIndices = [modeIndiciesTable copy];
  541. if(table[arr.firstObject] != nil){
  542. sdkParams.modeIndex = (SDKCaptureModeIndex)[table[arr.firstObject] unsignedIntegerValue];
  543. }
  544. else{
  545. sdkParams.modeIndex = (SDKCaptureModeIndex)[sdkParams.modeIndices.firstObject unsignedIntegerValue];
  546. }
  547. }
  548. NSString* cameraPosition = params[@"type"];
  549. if(cameraPosition != nil){
  550. if([cameraPosition isEqual:@"back"]){
  551. sdkParams.cameraPosition = SDK_CAMERA_PISITION_BACK;
  552. sdkParams.cameraPositionString = cameraPosition;
  553. }
  554. else if([cameraPosition isEqual:@"front"]){
  555. sdkParams.cameraPosition = SDK_CAMERA_PISITION_FRONT;
  556. sdkParams.cameraPositionString = cameraPosition;
  557. }
  558. }
  559. NSNumber* recTime = params[@"recTime"];
  560. if(recTime != nil){
  561. sdkParams.limitRecordTime = [recTime integerValue];
  562. }
  563. sdkParams.keyFrame = params[@"keyframe"];
  564. NSString* flashMode = params[@"flashMode"];
  565. if(flashMode != nil){
  566. sdkParams.flashModeString = flashMode;
  567. if([flashMode isEqualToString:@"auto"]){
  568. sdkParams.flashMode = SDK_FLASH_MODE_AUTO;
  569. }
  570. else if([flashMode isEqualToString:@"on"]){
  571. sdkParams.flashMode = SDK_FLASH_MODE_ON;
  572. }
  573. else if([flashMode isEqualToString:@"off"]){
  574. sdkParams.flashMode = SDK_FLASH_MODE_OFF;
  575. }
  576. }
  577. NSNumber* videoQualityNum = params[@"videoQuality"];
  578. if(videoQualityNum != nil){
  579. NSInteger videoQuality = [videoQualityNum integerValue];
  580. if(videoQuality == 480){
  581. sdkParams.videoQuality = SDK_VIDEO_QUALITY_480;
  582. }
  583. else if(videoQuality == 720){
  584. sdkParams.videoQuality = SDK_VIDEO_QUALITY_720;
  585. }
  586. else if(videoQuality == 1080){
  587. sdkParams.videoQuality = SDK_VIDEO_QUALITY_1080;
  588. }
  589. else if(videoQuality == 2160){
  590. sdkParams.videoQuality = SDK_VIDEO_QUALITY_2160;
  591. }
  592. }
  593. NSNumber* showPreviewForPanorama = params[@"showPreview"];
  594. if(showPreviewForPanorama != nil){
  595. sdkParams.showPreviewForPanorama = [showPreviewForPanorama boolValue];
  596. }
  597. }
  598. // 拍照界面
  599. - (void)showPreviewView: (BOOL)show{
  600. self.previewLayer.hidden = !show;
  601. self.takePhotoButton.enabled = show;
  602. self.resultImageView.hidden = show;
  603. self.backButton.hidden = !show;
  604. self.flashButton.hidden = !show;
  605. self.switchButton.hidden = !show;
  606. self.discardPhotoButton.hidden = show;
  607. self.savePhotoButton.hidden = show;
  608. }
  609. - (void)setup{
  610. // 打开数据库
  611. [[LenzDBManager shared] openSqlDataBase];
  612. [LenzDataManager creatDirectory];
  613. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  614. [[PCSTools shared] cleanDiskCache];
  615. });
  616. _mode = SDK_CAPTURE_MODE_CONTINUOUS;
  617. _captureSession = [[AVCaptureSession alloc] init];
  618. _captureSession.sessionPreset = AVCaptureSessionPresetInputPriority;
  619. _movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
  620. _movieFileOutput.maxRecordedDuration = CMTimeMake(self.parameters.limitRecordTime, 1);
  621. // setup video data output for panoramic
  622. _videoDataQueue = dispatch_queue_create("video data", DISPATCH_QUEUE_SERIAL);
  623. _videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
  624. _videoDataOutput.alwaysDiscardsLateVideoFrames = YES;
  625. _videoDataOutput.videoSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
  626. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  627. _photoOutput = [[AVCapturePhotoOutput alloc] init];
  628. NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
  629. _outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
  630. [_photoOutput setPhotoSettingsForSceneMonitoring:_outputSettings];
  631. _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
  632. NSMutableArray* nodesArr = [NSMutableArray array];
  633. NSMutableDictionary* nodesDic = [NSMutableDictionary dictionary];
  634. NSDictionary<NSNumber*, Class>* nodeClsTable = @{
  635. @(SDK_CAPTURE_MODE_CONTINUOUS): [OperationNodeMultiple class],
  636. @(SDK_CAPTURE_MODE_SINGLE): [OperationNodeSingle class],
  637. @(SDK_CAPTURE_MODE_MOVIE): [OperationNodeMovie class],
  638. @(SDK_CAPTURE_MODE_PANORAMA): [OperationNodePanorama class],
  639. @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA): [OperationNodeAIPanorama class],
  640. };
  641. [[SDKParameters shared].modeIndices enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  642. //
  643. // if(nodeClsTable[obj] != nil){
  644. // id node = [[nodeClsTable[obj] alloc] initWithController: self];
  645. // [nodesArr addObject: node];
  646. // nodesDic[obj] = node;
  647. // }
  648. if(nodeClsTable[obj] != nil){
  649. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_RETAIN && obj.intValue == SDK_CAPTURE_MODE_SINGLE) {
  650. return;
  651. } else {
  652. id node = [[nodeClsTable[obj] alloc] initWithController: self];
  653. if ([node isKindOfClass:[OperationNodeVideoBase class]]) {
  654. OperationNodeVideoBase *base = (OperationNodeVideoBase *)node;
  655. base.recTime = [SDKParameters shared].limitRecordTime;
  656. }
  657. [nodesArr addObject: node];
  658. nodesDic[obj] = node;
  659. }
  660. }
  661. }];
  662. _operationNodesArray = [nodesArr copy];
  663. _operationNodes = [nodesDic copy];
  664. // _operationNodes = @{
  665. // @(SDK_CAPTURE_MODE_SINGLE): [[OperationNodeSingle alloc] initWithController:self],
  666. // @(SDK_CAPTURE_MODE_CONTINUOUS): [[OperationNodeMultiple alloc] initWithController:self],
  667. // @(SDK_CAPTURE_MODE_MOVIE): [[OperationNodeMovie alloc] initWithController:self],
  668. // @(SDK_CAPTURE_MODE_PANORAMA): [[OperationNodePanorama alloc] initWithController:self],
  669. // @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA): [[OperationNodeAIPanorama alloc] initWithController:self],
  670. // };
  671. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
  672. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
  673. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationWillChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
  674. }
  675. - (void)startMotion {
  676. if (self.motionManager.deviceMotionAvailable) {
  677. __weak typeof(self)wearSelf = self;
  678. [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
  679. if (!self.startPitchX && !self.startRollY) {
  680. self.startPitchX = @(motion.attitude.pitch * 100);
  681. self.startRollY = @(motion.attitude.roll *100);
  682. }
  683. double x = self.startPitchX.doubleValue - motion.attitude.pitch * 100;
  684. double y = self.startRollY.doubleValue - motion.attitude.roll * 100;
  685. LenVideoStitchDirction dir = (LenVideoStitchDirction)wearSelf.panoramOrientationGuideView.selectedItemIndex;
  686. if (dir == LenVideoStitchDirctionLeft || dir == LenVideoStitchDirctionRight) {
  687. if (fabs(x) < 3) {
  688. // NSLog(@"~~~~~~~~~~水平");
  689. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  690. } else {
  691. if (x > 0) {
  692. // NSLog(@"~~~~~~~~~~向下");
  693. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirDown dir:dir];
  694. } else {
  695. // NSLog(@"~~~~~~~~~~向上");
  696. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirUp dir:dir];
  697. }
  698. }
  699. } else if (dir == LenVideoStitchDirctionUp || dir == LenVideoStitchDirctionDown) {
  700. if (fabs(y) < 3) {
  701. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  702. } else {
  703. if (y > 0) {
  704. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirLeft dir:dir];
  705. } else {
  706. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirRight dir:dir];
  707. }
  708. }
  709. }
  710. }];
  711. }
  712. }
  713. - (void)stopMotion {
  714. [self.motionManager stopDeviceMotionUpdates];
  715. self.startPitchX = nil;
  716. self.startRollY = nil;
  717. LenVideoStitchDirction dir = (LenVideoStitchDirction)self.panoramOrientationGuideView.selectedItemIndex;
  718. [self.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  719. }
  720. #pragma mark - Lazy Load
  721. - (BaseViewTapGestureDelegate *)tapDelegate{
  722. if(_tapDelegate == nil){
  723. _tapDelegate = [[BaseViewTapGestureDelegate alloc] init];
  724. _tapDelegate.controller = self;
  725. }
  726. return _tapDelegate;
  727. }
  728. - (AVCaptureDevice *)currentCamera{
  729. __block AVCaptureDevice* camera = nil;
  730. [self.captureSession.inputs enumerateObjectsUsingBlock:^(__kindof AVCaptureInput * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  731. AVCaptureDeviceInput* inputDevice = obj;
  732. if([inputDevice.device hasMediaType:AVMediaTypeVideo]){
  733. camera = inputDevice.device;
  734. *stop = YES;
  735. }
  736. }];
  737. return self.currentCameraInput.device;
  738. }
  739. - (AVCaptureDeviceInput*)currentCameraInput{
  740. __block AVCaptureDeviceInput* cameraInput = nil;
  741. [self.captureSession.inputs enumerateObjectsUsingBlock:^(__kindof AVCaptureInput * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  742. AVCaptureDeviceInput* inputDevice = obj;
  743. if([inputDevice.device hasMediaType:AVMediaTypeVideo]){
  744. cameraInput = inputDevice;
  745. *stop = YES;
  746. }
  747. }];
  748. return cameraInput;
  749. }
  750. - (SDKParameters *)parameters{
  751. return [SDKParameters shared];
  752. }
  753. #pragma mark - Action
  754. - (void)focusOn: (CGPoint)point{
  755. CGPoint pt = [self.previewLayer captureDevicePointOfInterestForPoint:point];
  756. AVCaptureDevice* curr = self.currentCamera;
  757. [[CameraManager shared] focusOn:pt device:curr];
  758. [self showFocusViewAt:point];
  759. }
  760. - (void)showFocusViewAt: (CGPoint)point{
  761. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideFocusView) object:nil];
  762. if(self.focusView == nil){
  763. UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 42, 42)];
  764. imgView.image = [UIImage sdkImageNamed:@"focus"];
  765. imgView.contentMode = UIViewContentModeScaleAspectFit;
  766. self.focusView = imgView;
  767. [self.view addSubview:self.focusView];
  768. }
  769. self.focusView.hidden = NO;
  770. CABasicAnimation* flash = [CABasicAnimation animationWithKeyPath:@"opacity"];
  771. flash.duration = 0.2;
  772. flash.fromValue = @(1);
  773. flash.toValue = @(0.1);
  774. flash.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  775. flash.autoreverses = YES;
  776. flash.repeatCount = 3;
  777. [self.focusView.layer removeAnimationForKey:@"flash"];
  778. [self.focusView.layer addAnimation:flash forKey:@"flash"];
  779. self.focusView.frame = CGRectMake(point.x - 21, point.y - 21, 42, 42);
  780. [self performSelector:@selector(hideFocusView) withObject:nil afterDelay:3];
  781. }
  782. - (void)hideFocusView{
  783. [self.focusView.layer removeAnimationForKey:@"flash"];
  784. self.focusView.hidden = YES;
  785. }
  786. - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
  787. if(error != nil){
  788. return;
  789. }
  790. if(self.mode == SDK_CAPTURE_MODE_SINGLE){
  791. [self dismissViewControllerAnimated:YES completion:^{}];
  792. }
  793. else{
  794. [self startCaptureSession];
  795. [self showPreviewView:YES];
  796. }
  797. }
  798. - (AVCaptureVideoOrientation)videoOrientation{
  799. UIDeviceOrientation curr = UIDeviceOrientationUnknown;
  800. return [self videoOrientation:&curr];
  801. }
  802. - (AVCaptureVideoOrientation)videoOrientation:(UIDeviceOrientation*)currentDeviceOrientation{
  803. return [[PCSMotionManager shared] videoOrientation:currentDeviceOrientation];;
  804. }
  805. - (void)takeStillPhoto:(AVCaptureVideoPreviewLayer*)previewLayer {
  806. AVCaptureConnection *connection = [self.photoOutput connectionWithMediaType:AVMediaTypeVideo];
  807. if(connection == nil){
  808. [self showAlertForAuthorization];
  809. return;
  810. }
  811. if (connection.supportsVideoOrientation) {
  812. // 根据motion设置照片方向
  813. AVCaptureVideoOrientation videoOrientation = [self videoOrientation];
  814. connection.videoMirrored = self.currentCamera == [CameraManager shared].front;
  815. connection.videoOrientation = videoOrientation;
  816. }
  817. // 创建 AVCapturePhotoSettings
  818. AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettings];
  819. if ([self.photoOutput.availablePhotoCodecTypes containsObject:AVVideoCodecTypeJPEG]) {
  820. NSDictionary *format = @{AVVideoCodecKey: AVVideoCodecTypeJPEG};
  821. photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:format];
  822. // NSLog(@"-----:%ld",(long)self.currentCameraInput.device.position);
  823. if (self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  824. photoSettings.flashMode = self.outputSettings.flashMode;
  825. }
  826. photoSettings.previewPhotoFormat = @{
  827. (NSString*)kCVPixelBufferPixelFormatTypeKey : photoSettings.availablePreviewPhotoPixelFormatTypes.firstObject,
  828. (NSString*)kCVPixelBufferWidthKey: @(160),
  829. (NSString*)kCVPixelBufferHeightKey: @(160),
  830. };
  831. }
  832. photoSettings.autoStillImageStabilizationEnabled = YES;
  833. // 拍照
  834. [self.photoOutput capturePhotoWithSettings:photoSettings delegate:self];
  835. }
  836. #pragma mark - Notification
  837. - (void)orientationWillChange: (NSNotification*)noti{
  838. NSLog(@"orientationWillChange");
  839. }
  840. - (void)willEnterForeground: (NSNotification*)noti{
  841. // if(self.broken){
  842. // [self.player play];
  843. // self.broken = NO;
  844. // }
  845. }
  846. //UIBackgroundTaskIdentifier _bgTaskToken;
  847. - (void)willEnterBackground: (NSNotification*)noti{
  848. if([self.currentOperationNode conformsToProtocol:@protocol(OperationNodeBackgroundProtocol)]){
  849. id<OperationNodeBackgroundProtocol> obj = self.currentOperationNode;
  850. if ([obj respondsToSelector:@selector(willEnterBackground:)]) {
  851. [obj willEnterBackground:noti];
  852. }
  853. }
  854. }
  855. - (void)orientationDidChange: (NSNotification*)noti{
  856. NSLog(@"orientationDidChange");
  857. if([self.currentOperationNode respondsToSelector:@selector(stop)])
  858. [self.currentOperationNode stop];
  859. }
  860. #pragma mark - alert
  861. - (void)showAlertForAuthorizationWithText: (NSString*)text{
  862. [QuitMultipleModeAlertViewController show:self title:@"" text:text leftBtnTitle:@"取消" rightBtnTitle:@"确认" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  863. [alertController dismissViewControllerAnimated:YES completion:^{
  864. // [self dismissViewControllerAnimated:YES completion:^{
  865. //
  866. // }];
  867. }];
  868. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  869. [alertController dismissViewControllerAnimated:YES completion:^{
  870. NSURL* url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  871. if(url != nil){
  872. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
  873. // NSLog(succ)
  874. }];
  875. }
  876. }];
  877. }];
  878. }
  879. - (void)showAlertForAuthorization{
  880. [self showAlertForAuthorizationWithText:@"请在系统设置里打开摄像机访问权限后重试"];
  881. }
  882. #pragma mark - Capture
  883. - (void)takeStillPhoto{
  884. [self takeStillPhoto:self.previewLayer];
  885. }
  886. - (BOOL)startRecording{
  887. if(self.movieFileOutput.isRecording){
  888. return NO;
  889. }
  890. self.movieFileOutput.maxRecordedDuration = CMTimeMake([SDKParameters shared].limitRecordTime, 1);
  891. [self.recordTimer invalidate];
  892. dispatch_async(dispatch_get_main_queue(), ^{
  893. self.recordTimer = [NSTimer timerWithTimeInterval:0.2 repeats:YES block:^(NSTimer * _Nonnull timer) {
  894. [self.timerLabel updateWith:self.movieFileOutput.recordedDuration.value / self.movieFileOutput.recordedDuration.timescale];
  895. }];
  896. [[NSRunLoop currentRunLoop] addTimer:self.recordTimer forMode:NSDefaultRunLoopMode];
  897. });
  898. NSURL* tmpMovieFileUrl = [NSURL fileURLWithPath:[LenzDataManager moviePath]];
  899. AVCaptureConnection* connection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
  900. if(connection == nil){
  901. [self showAlertForAuthorization];
  902. return NO;
  903. }
  904. UIDeviceOrientation currOrientation = UIDeviceOrientationUnknown;
  905. connection.videoOrientation = [self videoOrientation:&currOrientation];
  906. AVCaptureDevice* camera = self.currentCamera;
  907. [camera lockForConfiguration:nil];
  908. if ([camera hasFlash] && self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  909. if (self.outputSettings.flashMode == AVCaptureFlashModeOff) {
  910. [camera setTorchMode:AVCaptureTorchModeOff];
  911. } else if (self.outputSettings.flashMode == AVCaptureFlashModeOn) {
  912. [camera setTorchMode:AVCaptureTorchModeOn];
  913. } else {
  914. [camera setTorchMode:AVCaptureTorchModeAuto];
  915. }
  916. }
  917. [camera unlockForConfiguration];
  918. self.thumbnailOritaionByCurrentVideoOrientation = [UIImage imageOrientationByDeviceOrientation:currOrientation isFrontCamera:camera == [CameraManager shared].front];
  919. [self.movieFileOutput startRecordingToOutputFileURL: tmpMovieFileUrl recordingDelegate:self];
  920. return YES;
  921. }
  922. - (void)stopRecording{
  923. [self.movieFileOutput stopRecording];
  924. AVCaptureDevice* camera = self.currentCamera;
  925. [camera lockForConfiguration:nil];
  926. if ([camera hasFlash] && self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  927. [camera setTorchMode:AVCaptureTorchModeOff];
  928. }
  929. [camera unlockForConfiguration];
  930. [self.recordTimer invalidate];
  931. self.recordTimer = nil;
  932. }
  933. - (BOOL)startVideoDataOutputing{
  934. [[NSNotificationCenter defaultCenter] removeObserver:self name:PCS_NotificationNameOrientationDidChange object:nil];
  935. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:PCS_NotificationNameOrientationDidChange object:nil];
  936. UIDeviceOrientation deviceOrientation = UIDeviceOrientationPortrait;
  937. AVCaptureVideoOrientation orientation = [self videoOrientation:&deviceOrientation];
  938. CGFloat degree = 0;
  939. AVCaptureDevice* camera = self.currentCamera;
  940. CameraManager* cameraMgr = [CameraManager shared];
  941. BOOL isFront = camera == cameraMgr.front;
  942. BOOL isLandscape = NO;
  943. // 前摄像头需要镜像一下
  944. CGAffineTransform originalMat = isFront ? CGAffineTransformMakeScale(-1, 1) : CGAffineTransformIdentity;
  945. switch (deviceOrientation) {
  946. case UIDeviceOrientationPortrait:
  947. // self.panoramOrientationGuideView.selectedItemIndex = PanoramaOrientationViewUp;
  948. degree = 0;
  949. break;
  950. case UIDeviceOrientationLandscapeRight:
  951. // self.panoramOrientationGuideView.selectedItemIndex = PanoramaOrientationViewRight;
  952. degree = isFront ? 90 : -90;
  953. isLandscape = YES;
  954. break;
  955. case UIDeviceOrientationPortraitUpsideDown:
  956. // self.panoramOrientationGuideView.selectedItemIndex = PanoramaOrientationViewDown;
  957. degree = 180;
  958. break;
  959. case UIDeviceOrientationLandscapeLeft:
  960. // self.panoramOrientationGuideView.selectedItemIndex = PanoramaOrientationViewLeft;
  961. degree = isFront ? -90 : 90;
  962. isLandscape = YES;
  963. break;
  964. default:
  965. break;
  966. }
  967. __block BOOL ret = NO;
  968. dispatch_sync(self.videoDataQueue, ^{
  969. if(self.videoDataOutput.sampleBufferDelegate != nil){
  970. return;
  971. }
  972. if([self configureVideoWritter]){
  973. AVCaptureConnection *connection = [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo];
  974. if(connection == nil){
  975. [self showAlertForAuthorization];
  976. return;
  977. }
  978. [connection setVideoOrientation:orientation];
  979. // self.panoramaGuideView.transform = CGAffineTransformRotate(originalMat, dgree_2_rad(degree));
  980. // 设置小预览框高宽比
  981. CGFloat aspect = isFront ? cameraMgr.frontAspect : cameraMgr.backAspect;
  982. aspect = isLandscape ? 1.0 / aspect : aspect;
  983. // [self.panoramaGuideView updatePreviewAspect: aspect];
  984. // self.panoramOrientationGuideView.transform = self.panoramaGuideView.transform;
  985. [self.videoDataOutput setSampleBufferDelegate:self queue:self.videoDataQueue];
  986. ret = YES;
  987. }
  988. });
  989. return ret;
  990. }
  991. - (PanoramaGuideView *)panoramaGuideView{
  992. if (_panoramaGuideView == nil) {
  993. _panoramaGuideView = [[PanoramaGuideView alloc]init];
  994. _panoramaGuideView.hidden = YES;
  995. }
  996. return _panoramaGuideView;;
  997. }
  998. - (void)stopVideoDataOutputing{
  999. [self.motionTimer invalidate];
  1000. self.motionTimer = nil;
  1001. [[NSNotificationCenter defaultCenter] removeObserver:self name:PCS_NotificationNameOrientationDidChange object:nil];
  1002. dispatch_async(self.videoDataQueue, ^{
  1003. [self.videoDataOutput setSampleBufferDelegate:nil queue:nil];
  1004. [Renderer shared].cameraPass.texture = nil;
  1005. });
  1006. [self stopMotion];
  1007. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  1008. }
  1009. - (void)updateViewStatusWhenStitchSave:(BOOL)isSaveIng {
  1010. dispatch_async(dispatch_get_main_queue(), ^{
  1011. self.stitchView.hidden = !isSaveIng;
  1012. if (self.stitchView.hidden) {
  1013. [self.stitchImageView.layer removeAnimationForKey:@"loadingAnimation"];
  1014. } else {
  1015. [self.stitchImageView.layer addAnimation:self.loadingAnimation forKey:@"loadingAnimation"];
  1016. }
  1017. self.flashButton.hidden = isSaveIng;
  1018. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1019. self.panoramOrientationGuideView.hidden = YES;
  1020. self.ai_fullView.hidden = YES;
  1021. } else {
  1022. self.panoramOrientationGuideView.hidden = isSaveIng;
  1023. self.ai_fullView.hidden = isSaveIng;
  1024. }
  1025. self.panoramaGuideView.hidden = isSaveIng;
  1026. self.modeList.hidden = isSaveIng;
  1027. self.savePhotoButton.hidden = isSaveIng;
  1028. self.takePhotoButton.hidden = isSaveIng;
  1029. // self.switchButton.hidden = isSaveIng;
  1030. self.discardPhotoButton.hidden = isSaveIng;
  1031. self.backButton.hidden = !isSaveIng;
  1032. self.ablumImageView.hidden = isSaveIng;
  1033. // self.timerLabel.hidden = isSaveIng;
  1034. });
  1035. }
  1036. - (void)updateViewStatusWhenStitchFail {
  1037. dispatch_async(dispatch_get_main_queue(), ^{
  1038. self.stitchView.hidden = YES;
  1039. self.flashButton.hidden = NO;
  1040. self.modeList.hidden = NO;
  1041. self.savePhotoButton.hidden = NO;
  1042. self.takePhotoButton.hidden = NO;
  1043. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1044. self.ai_fullView.hidden = YES;
  1045. self.panoramOrientationGuideView.hidden = YES;
  1046. self.panoramaGuideView.hidden = YES;
  1047. } else {
  1048. self.ai_fullView.hidden = NO;
  1049. self.panoramOrientationGuideView.hidden = NO;
  1050. self.panoramaGuideView.hidden = NO;
  1051. }
  1052. // self.switchButton.hidden = isSaveIng;
  1053. self.discardPhotoButton.hidden = NO;
  1054. self.backButton.hidden = YES;
  1055. self.ablumImageView.hidden = NO;
  1056. [self.takePhotoButton setImage:[UIImage loadNamed:@"take-photo-btn"] forState:UIControlStateNormal];
  1057. // self.timerLabel.hidden = isSaveIng;
  1058. });
  1059. }
  1060. - (BOOL)getStitchBigImageIfNeed {
  1061. BOOL isSuccess = NO;
  1062. NSString *s = [LenStitcher getCurrentPanoramaShow];
  1063. if (s.length) {
  1064. isSuccess = YES;
  1065. }
  1066. return isSuccess;
  1067. }
  1068. - (BOOL)configureVideoWritter{
  1069. // setup asset writter for the video data output
  1070. NSURL* tmpMovieFileUrl = [NSURL fileURLWithPath:[[PCSTools shared].tmpPath stringByAppendingPathComponent:@"video-data-tmp-file.mov"] isDirectory:NO];
  1071. NSError* err = nil;
  1072. [[NSFileManager defaultManager] removeItemAtURL:tmpMovieFileUrl error:nil];
  1073. self.videoWriter = [[AVAssetWriter alloc] initWithURL:tmpMovieFileUrl fileType:AVFileTypeQuickTimeMovie error:&err];
  1074. if(err != nil){
  1075. NSLog(@"%@", err);
  1076. self.videoWriter = nil;
  1077. return NO;
  1078. }
  1079. SDKParameters* params = [SDKParameters shared];
  1080. NSDictionary* settings = [NSDictionary dictionaryWithObjectsAndKeys:
  1081. AVVideoCodecTypeH264, AVVideoCodecKey,
  1082. [NSNumber numberWithInteger: params.resolution.width], AVVideoWidthKey,
  1083. [NSNumber numberWithInteger: params.resolution.height], AVVideoHeightKey,
  1084. nil];
  1085. self.videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:settings];
  1086. self.videoWriterInput.expectsMediaDataInRealTime = YES;
  1087. [self.videoWriter addInput:self.videoWriterInput];
  1088. return YES;
  1089. }
  1090. - (void)prepareCamera{
  1091. if (self.cameraPrepared) {
  1092. return;
  1093. }
  1094. AVCaptureDevice* device = [SDKParameters shared].cameraPosition == SDK_CAMERA_PISITION_BACK ? [CameraManager shared].back : [CameraManager shared].front;
  1095. if (device == nil) {
  1096. self.cameraPrepared = false;
  1097. return;
  1098. }
  1099. NSError* error;
  1100. AVCaptureDeviceInput* input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
  1101. if(error != nil){
  1102. self.cameraPrepared = false;
  1103. return;
  1104. }
  1105. [self.captureSession beginConfiguration];
  1106. if([self.captureSession canAddInput:input]){
  1107. [self.captureSession addInput:input];
  1108. }
  1109. else{
  1110. return;
  1111. }
  1112. self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
  1113. self.previewLayer.frame = self.view.layer.bounds;
  1114. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  1115. [self.view.layer insertSublayer:self.previewLayer atIndex:0u];
  1116. if([self.captureSession canAddOutput:self.photoOutput]){
  1117. [self.captureSession addOutput:self.photoOutput];
  1118. }
  1119. if([self.captureSession canAddOutput:self.movieFileOutput]){
  1120. [self.captureSession addOutput:self.movieFileOutput];
  1121. }
  1122. [self.captureSession commitConfiguration];
  1123. self.cameraPrepared = YES;
  1124. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:self.parameters.resolution.height];
  1125. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:self.parameters.resolution.height];
  1126. [self updatePreViewLayer];
  1127. }
  1128. #pragma mark - Gesture
  1129. - (void)tapGestureHandler: (UITapGestureRecognizer*)gesture{
  1130. switch(gesture.state){
  1131. case UIGestureRecognizerStateBegan:{
  1132. break;
  1133. }
  1134. case UIGestureRecognizerStateChanged:{
  1135. break;
  1136. }
  1137. case UIGestureRecognizerStateEnded:{
  1138. CGPoint pt = [gesture locationInView:self.view];
  1139. [self focusOn:pt];
  1140. break;
  1141. }
  1142. case UIGestureRecognizerStateCancelled:{
  1143. break;
  1144. }
  1145. default:
  1146. break;
  1147. }
  1148. }
  1149. - (void)panGestureHandler: (UIPanGestureRecognizer*)gesture{
  1150. switch(gesture.state){
  1151. case UIGestureRecognizerStateBegan:{
  1152. break;
  1153. }
  1154. case UIGestureRecognizerStateChanged:{
  1155. if(self.flag){
  1156. return;
  1157. }
  1158. self.flag = YES;
  1159. CGPoint translation = [gesture translationInView:self.view];
  1160. [self.modeList updateIndexByTanslation:translation];
  1161. break;
  1162. }
  1163. case UIGestureRecognizerStateEnded:{
  1164. self.flag = NO;
  1165. break;
  1166. }
  1167. case UIGestureRecognizerStateCancelled:{
  1168. self.flag = NO;
  1169. break;
  1170. }
  1171. default:
  1172. self.flag = NO;
  1173. break;
  1174. }
  1175. }
  1176. #pragma mark - orientation
  1177. - (UIInterfaceOrientationMask)supportedInterfaceOrientations{
  1178. return UIInterfaceOrientationMaskPortrait;
  1179. }
  1180. - (void)updateUIByMode{
  1181. self.albumButton.hidden = YES;
  1182. self.numberOfImagesLabel.hidden = YES;
  1183. self.modeLabel.text = self.currentOperationNode.modeTitleString;
  1184. self.ai_fullView.hidden = !(self.mode == SDK_CAPTURE_MODE_PANORAMA);
  1185. self.panGesture.enabled = YES;
  1186. // self.controller.savePhotoButton.hidden = !self.hasCache;
  1187. // self.controller.discardPhotoButton.hidden = !self.hasCache;
  1188. //
  1189. // self.controller.albumButton.hidden = !self.hasCache;
  1190. // self.controller.backButton.hidden = self.hasCache;
  1191. if([self.currentOperationNode respondsToSelector:@selector(updateUI)]){
  1192. [self.currentOperationNode updateUI];
  1193. }
  1194. [self updatePreViewLayer];
  1195. }
  1196. - (void)updatePreViewLayer {
  1197. CGFloat width = [UIScreen mainScreen].bounds.size.width;
  1198. CGFloat height = [UIScreen mainScreen].bounds.size.height;
  1199. switch (self.mode) {
  1200. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1201. self.switchButton.hidden = NO;
  1202. self.panoramaGuideView.hidden = YES;
  1203. self.panoramOrientationGuideView.hidden = YES;
  1204. self.previewLayer.frame = CGRectMake(0, (height - width*4/3)/2, width, width*4/3);
  1205. }
  1206. break;
  1207. case SDK_CAPTURE_MODE_SINGLE: {
  1208. self.switchButton.hidden = NO;
  1209. self.panoramaGuideView.hidden = YES;
  1210. self.panoramOrientationGuideView.hidden = YES;
  1211. self.previewLayer.frame = CGRectMake(0, (height - width*4/3)/2, width, width*4/3);
  1212. }
  1213. break;
  1214. case SDK_CAPTURE_MODE_MOVIE: {
  1215. self.switchButton.hidden = NO;
  1216. self.panoramaGuideView.hidden = YES;
  1217. self.panoramOrientationGuideView.hidden = YES;
  1218. self.previewLayer.frame = self.view.layer.bounds;
  1219. }
  1220. break;
  1221. case SDK_CAPTURE_MODE_PANORAMA: {
  1222. self.switchButton.hidden = YES;
  1223. self.panoramaGuideView.hidden = NO;
  1224. self.panoramOrientationGuideView.hidden = NO;
  1225. self.previewLayer.frame = self.view.layer.bounds;
  1226. }
  1227. break;
  1228. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  1229. self.switchButton.hidden = YES;
  1230. self.panoramaGuideView.hidden = YES;
  1231. self.panoramOrientationGuideView.hidden = YES;
  1232. self.previewLayer.frame = self.view.layer.bounds;
  1233. }
  1234. break;
  1235. default:
  1236. break;
  1237. }
  1238. }
  1239. - (void)modeWillChange: (NSUInteger)newIndex oldIndex: (NSUInteger)oldIndex{
  1240. if(newIndex >= INT_MAX){
  1241. return;
  1242. }
  1243. [self.currentOperationNode willQuitOnCompletion:^() {}];
  1244. }
  1245. - (void)modeDidChange: (NSUInteger)newIndex oldIndex: (NSUInteger)oldIndex{
  1246. if(newIndex >= INT_MAX){
  1247. return;
  1248. }
  1249. // self.modeList.userInteractionEnabled = NO;
  1250. // [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]
  1251. if(self.effectView.superview != nil){
  1252. // self.effectView.effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
  1253. [UIView animateWithDuration:0.5 animations:^{
  1254. self.effectView.effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
  1255. }];
  1256. }
  1257. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  1258. if(newIndex == SDK_CAPTURE_MODE_SINGLE || newIndex == SDK_CAPTURE_MODE_CONTINUOUS){
  1259. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:self.parameters.resolution.height];
  1260. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:self.parameters.resolution.height];
  1261. }
  1262. else{
  1263. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:self.parameters.videoResolution.height];
  1264. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:self.parameters.videoResolution.height];
  1265. }
  1266. PhotographModeEnum oldModeEnum = (PhotographModeEnum)(oldIndex);
  1267. if((self.mode == SDK_CAPTURE_MODE_PANORAMA || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)
  1268. && oldModeEnum != SDK_CAPTURE_MODE_PANORAMA
  1269. && oldModeEnum != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA){
  1270. if([self.captureSession canAddOutput:self.videoDataOutput]){
  1271. [self.captureSession addOutput:self.videoDataOutput];
  1272. [self.captureSession removeOutput:self.movieFileOutput];
  1273. }
  1274. }
  1275. else if((self.mode == SDK_CAPTURE_MODE_MOVIE)
  1276. && (oldModeEnum == SDK_CAPTURE_MODE_PANORAMA
  1277. || oldModeEnum == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)){
  1278. if([self.captureSession canAddOutput:self.movieFileOutput]){
  1279. [self.captureSession addOutput:self.movieFileOutput];
  1280. [self.captureSession removeOutput:self.videoDataOutput];
  1281. }
  1282. }
  1283. dispatch_sync(dispatch_get_main_queue(), ^{
  1284. // self.modeList.userInteractionEnabled = YES;
  1285. self.effectView.effect = nil;
  1286. });
  1287. });
  1288. [self updateUIByMode];
  1289. [self switchDevicePositionBack];
  1290. [self updateNumberLabel];
  1291. }
  1292. - (void)setupMicrophone{
  1293. NSError* audioError = nil;
  1294. AVCaptureDevice* audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
  1295. AVCaptureDeviceInput* audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&audioError];
  1296. if(audioError == nil){
  1297. AVCaptureAudioDataOutput* audioOutput = [[AVCaptureAudioDataOutput alloc] init];
  1298. [audioOutput setSampleBufferDelegate:self queue:dispatch_get_global_queue(0, 0)];
  1299. if([self.captureSession canAddInput:audioInput]){
  1300. [self.captureSession addInput:audioInput];
  1301. }
  1302. if([self.captureSession canAddOutput:audioOutput]){
  1303. [self.captureSession addOutput:audioOutput];
  1304. }
  1305. }
  1306. }
  1307. - (UIStatusBarStyle)preferredStatusBarStyle{
  1308. return UIStatusBarStyleLightContent;
  1309. }
  1310. #pragma mark 方向调用的代理
  1311. - (void)panoramaOrientationViewslt:(PanoramaOrientationViewDirectionEnum)direction{
  1312. // NSLog(@"方向%ld",direction);
  1313. self.panoramaGuideView.hidden = NO;
  1314. // [LenStitcher videoResetPath];
  1315. [UIView animateWithDuration:0.25 animations:^{
  1316. [self.panoramaGuideView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1317. switch (direction) {
  1318. case PanoramaOrientationViewLeft:
  1319. case PanoramaOrientationViewRight:
  1320. {
  1321. make.left.right.offset(0);
  1322. make.centerY.mas_equalTo(self.view);
  1323. make.height.mas_equalTo(PanoramaGuideViewWOrH);
  1324. }
  1325. break;
  1326. case PanoramaOrientationViewUp:
  1327. case PanoramaOrientationViewDown:
  1328. {
  1329. make.centerX.mas_equalTo(self.view);
  1330. make.width.mas_equalTo(PanoramaGuideViewWOrH);
  1331. make.bottom.mas_equalTo(self.panoramOrientationGuideView.mas_top).offset(-25);
  1332. make.top.mas_equalTo(self.timerLabel.mas_bottom).offset(15);
  1333. }
  1334. break;
  1335. case PanoramaOrientationViewAny: {
  1336. self.panoramaGuideView.hidden = YES;
  1337. }
  1338. break;
  1339. default:
  1340. break;
  1341. }
  1342. }];
  1343. if (self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1344. [self.panoramaGuideView setNeedsLayout];
  1345. [self.panoramaGuideView layoutIfNeeded];
  1346. }
  1347. } completion:^(BOOL finished) {
  1348. [self.panoramaGuideView direction:direction];
  1349. }];
  1350. }
  1351. - (void)stopAllSensors{
  1352. [self.captureSession stopRunning];
  1353. [[PCSMotionManager shared] stopAccelerometerUpdates];
  1354. }
  1355. #pragma mark - session
  1356. - (void)turnTorchOff{
  1357. AVCaptureDevice* currentDevice = self.currentCamera;
  1358. if(currentDevice == nil || !currentDevice.hasTorch){
  1359. return;
  1360. }
  1361. NSError* error;
  1362. if(error == nil){
  1363. [currentDevice lockForConfiguration:&error];
  1364. currentDevice.torchMode = AVCaptureTorchModeOff;
  1365. [currentDevice unlockForConfiguration];
  1366. }
  1367. }
  1368. - (void)stopCaptureSession{
  1369. [self turnTorchOff];
  1370. if (self.captureSession.isRunning) {
  1371. [self.captureSession stopRunning];
  1372. }
  1373. }
  1374. - (void)startCaptureSession{
  1375. if (!self.cameraPrepared) {
  1376. [self prepareCamera];
  1377. }
  1378. if (self.cameraPrepared && (!self.captureSession.isRunning)) {
  1379. [self.captureSession startRunning];
  1380. }
  1381. }
  1382. #pragma mark - Btn call back
  1383. -(IBAction)switchCameraTapped:(id)sender
  1384. {
  1385. if(self.captureSession == nil){
  1386. return;
  1387. }
  1388. AVCaptureDeviceInput* currInput = self.currentCameraInput;
  1389. if(currInput == nil){
  1390. return;
  1391. }
  1392. AVCaptureDevice* currentDevice = currInput.device;
  1393. AVCaptureDevice *newCamera = nil;
  1394. if(currentDevice.position == AVCaptureDevicePositionBack){
  1395. newCamera = [CameraManager shared].front;
  1396. }
  1397. else if(currentDevice.position == AVCaptureDevicePositionFront){
  1398. newCamera = [CameraManager shared].back;
  1399. }
  1400. else{
  1401. return;
  1402. }
  1403. [self.captureSession beginConfiguration];
  1404. if(currentDevice.hasTorch){
  1405. NSError* error;
  1406. [currentDevice lockForConfiguration:&error];
  1407. currentDevice.torchMode = AVCaptureTorchModeOff;
  1408. [currentDevice unlockForConfiguration];
  1409. }
  1410. [self.captureSession removeInput:currInput];
  1411. self.flashButton.hidden = !newCamera.hasFlash;
  1412. NSError *err = nil;
  1413. AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
  1414. if(newVideoInput == nil || err != nil){
  1415. NSLog(@"Error creating capture device input: %@", err.localizedDescription);
  1416. }
  1417. else if([self.captureSession canAddInput:newVideoInput]){
  1418. [self.captureSession addInput:newVideoInput];
  1419. }
  1420. [self.captureSession commitConfiguration];
  1421. }
  1422. - (void)switchDevicePositionBack {
  1423. if(self.captureSession == nil ||
  1424. (self.mode != SDK_CAPTURE_MODE_PANORAMA && self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)){
  1425. return;
  1426. }
  1427. AVCaptureDeviceInput* currInput = self.currentCameraInput;
  1428. if(currInput == nil){
  1429. return;
  1430. }
  1431. AVCaptureDevice* currentDevice = currInput.device;
  1432. AVCaptureDevice *newCamera = nil;
  1433. if(currentDevice.position == AVCaptureDevicePositionBack){
  1434. return;
  1435. }
  1436. if(currentDevice.position == AVCaptureDevicePositionFront){
  1437. newCamera = [CameraManager shared].back;
  1438. }
  1439. [self.captureSession beginConfiguration];
  1440. if(currentDevice.hasTorch){
  1441. NSError* error;
  1442. [currentDevice lockForConfiguration:&error];
  1443. currentDevice.torchMode = AVCaptureTorchModeOff;
  1444. [currentDevice unlockForConfiguration];
  1445. }
  1446. [self.captureSession removeInput:currInput];
  1447. NSError *err = nil;
  1448. AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
  1449. if(newVideoInput == nil || err != nil){
  1450. NSLog(@"Error creating capture device input: %@", err.localizedDescription);
  1451. } else if([self.captureSession canAddInput:newVideoInput]){
  1452. [self.captureSession addInput:newVideoInput];
  1453. }
  1454. [self.captureSession commitConfiguration];
  1455. }
  1456. - (void)takePhotoButtonTouchUpInside:(id)sender{
  1457. self.takePhotoButton.enabled = NO;
  1458. if (self.outputSettings.flashMode == AVCaptureFlashModeOn && (self.mode == SDK_CAPTURE_MODE_SINGLE || self.mode == SDK_CAPTURE_MODE_CONTINUOUS || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)) {
  1459. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1460. self.takePhotoButton.enabled = YES;
  1461. });
  1462. } else {
  1463. dispatch_async(dispatch_get_main_queue(), ^{
  1464. self.takePhotoButton.enabled = YES;
  1465. });
  1466. }
  1467. if(![self.currentOperationNode respondsToSelector:@selector(enable)] || self.currentOperationNode.enable){
  1468. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1469. // [LenStitcher videoResetPath];
  1470. // LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1471. // [self.resourceModel.aiPanoramArray addObject:itemModel];
  1472. OperationNodeAIPanorama *aiPan = nil;
  1473. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  1474. aiPan = self.currentOperationNode;
  1475. if (!aiPan.isRecording) {
  1476. aiPan.AIType = OperationAITypeTap;
  1477. }
  1478. }
  1479. // [self startMotion];
  1480. // if (self.isVideoStitchStopedWhenRecording) {
  1481. //
  1482. //
  1483. //
  1484. // return;
  1485. // }
  1486. }
  1487. [self.currentOperationNode takePhotoButtonTouched];
  1488. if (self.mode == SDK_CAPTURE_MODE_PANORAMA && !self.isVideoStitchStopedWhenRecording) {
  1489. [LenStitcher videoResetPath];
  1490. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1491. [self.resourceModel.panoramArray addObject:itemModel];
  1492. [self startMotion];
  1493. // self.videoStitchSemaphore = dispatch_semaphore_create(1);
  1494. }
  1495. // if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1496. //
  1497. // OperationNodeAIPanorama *aiPan = nil;
  1498. // if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  1499. // aiPan = self.currentOperationNode;
  1500. // aiPan.AIType = OperationAITypeTap;
  1501. // }
  1502. //
  1503. // }
  1504. }
  1505. }
  1506. - (void)longPressGes:(UILongPressGestureRecognizer *)ges {
  1507. switch (ges.state) {
  1508. case UIGestureRecognizerStateBegan:
  1509. {
  1510. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1511. OperationNodeAIPanorama *aiPan = nil;
  1512. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  1513. // self.videoStitchSemaphore = dispatch_semaphore_create(1);
  1514. [LenStitcher videoResetPath];
  1515. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1516. [self.resourceModel.aiPanoramArray addObject:itemModel];
  1517. [self startMotion];
  1518. aiPan = self.currentOperationNode;
  1519. // self.touchTime = 0;
  1520. aiPan.AIType = OperationAITypeLongPress;
  1521. [self.currentOperationNode takePhotoButtonTouched];
  1522. }
  1523. }
  1524. }
  1525. break;
  1526. case UIGestureRecognizerStateEnded:
  1527. break;
  1528. default:
  1529. break;
  1530. }
  1531. }
  1532. - (void)takePhotoButtonTouchDownInside:(id)sender{
  1533. }
  1534. - (void)flashButtonTouchUpInside:(id)sender{
  1535. AVCaptureDevice* currentDevice = self.currentCamera;
  1536. if(currentDevice == nil || !currentDevice.hasFlash){
  1537. return;
  1538. }
  1539. NSError* error = nil;
  1540. [currentDevice lockForConfiguration:&error];
  1541. if(error != nil){
  1542. return;
  1543. }
  1544. if(self.outputSettings.flashMode == AVCaptureFlashModeOn){
  1545. self.outputSettings.flashMode = AVCaptureFlashModeAuto;
  1546. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-auto-btn"] forState:UIControlStateNormal];
  1547. }
  1548. else if(self.outputSettings.flashMode == AVCaptureFlashModeAuto){
  1549. self.outputSettings.flashMode = AVCaptureFlashModeOff;
  1550. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-disable-btn"] forState:UIControlStateNormal];
  1551. }
  1552. else{
  1553. self.outputSettings.flashMode = AVCaptureFlashModeOn;
  1554. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-btn"] forState:UIControlStateNormal];
  1555. }
  1556. [currentDevice unlockForConfiguration];
  1557. }
  1558. - (void)backButtonTouchUpInside:(id)sender{
  1559. if (!self.stitchView.hidden) {
  1560. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"图片拼接中,返回会清空正在拼接的数据" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1561. [alertController dismissViewControllerAnimated:NO completion:^{}];
  1562. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1563. [self updateViewStatusWhenStitchSave:NO];
  1564. [alertController dismissViewControllerAnimated:NO completion:^{
  1565. // [self dismissViewControllerAnimated:YES completion:^{}];
  1566. }];
  1567. }];
  1568. } else {
  1569. [self dismissViewControllerAnimated:YES completion:^{}];
  1570. }
  1571. }
  1572. - (void)makeResData:(NSMutableArray <LenzResourceItemModel *> *)array {
  1573. [array enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1574. }];
  1575. }
  1576. - (void)savePhotoButtonTouchUpInside:(id)sender{
  1577. //待优化
  1578. NSMutableArray *res = [NSMutableArray array];
  1579. __block NSInteger idIndex = 1;
  1580. [self.resourceModel.singleArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1581. idIndex += idx;
  1582. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1583. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1584. dict[@"path"] = obj.path;
  1585. dict[@"cameraMode"] = obj.cameraMode;
  1586. dict[@"cameraType"] = obj.cameraType;
  1587. dict[@"isRemake"] = @(obj.isRemake);
  1588. [res addObject:dict];
  1589. }];
  1590. [self.resourceModel.continousArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1591. idIndex += idx;
  1592. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1593. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1594. dict[@"path"] = obj.path;
  1595. dict[@"cameraMode"] = obj.cameraMode;
  1596. dict[@"cameraType"] = obj.cameraType;
  1597. dict[@"isRemake"] = @(obj.isRemake);
  1598. [res addObject:dict];
  1599. }];
  1600. [self.resourceModel.movieArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1601. idIndex += idx;
  1602. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1603. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1604. dict[@"path"] = obj.path;
  1605. dict[@"cameraMode"] = obj.cameraMode;
  1606. dict[@"cameraType"] = obj.cameraType;
  1607. dict[@"isRemake"] = @(obj.isRemake);
  1608. [res addObject:dict];
  1609. }];
  1610. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1611. if (obj.path.length) {
  1612. idIndex += idx;
  1613. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1614. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1615. dict[@"path"] = obj.path;
  1616. dict[@"cameraMode"] = obj.cameraMode;
  1617. dict[@"cameraType"] = obj.cameraType;
  1618. dict[@"isRemake"] = @(obj.isRemake);
  1619. NSMutableArray *keyFrame = [NSMutableArray array];
  1620. [obj.keyFrame enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1621. [keyFrame addObject:obj];
  1622. }];
  1623. dict[@"keyFrame"] = keyFrame;
  1624. [res addObject:dict];
  1625. }
  1626. }];
  1627. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1628. if (obj.path.length) {
  1629. idIndex += idx;
  1630. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1631. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1632. dict[@"path"] = obj.path;
  1633. dict[@"cameraMode"] = obj.cameraMode;
  1634. dict[@"cameraType"] = obj.cameraType;
  1635. dict[@"isRemake"] = @(obj.isRemake);
  1636. NSMutableArray *keyFrame = [NSMutableArray array];
  1637. [obj.keyFrame enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1638. [keyFrame addObject:obj];
  1639. }];
  1640. dict[@"keyFrame"] = keyFrame;
  1641. [res addObject:dict];
  1642. }
  1643. }];
  1644. if (self.completeBlock) {
  1645. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1646. dict[@"code"] = @(200);
  1647. dict[@"message"] = @"成功";
  1648. dict[@"data"] = res;
  1649. self.completeBlock(dict);
  1650. [self dismissViewControllerAnimated:YES completion:^{
  1651. }];
  1652. }
  1653. // self.panGesture.enabled = YES;
  1654. // // Access has not been determined.
  1655. // [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  1656. //
  1657. // dispatch_async(dispatch_get_main_queue(), ^{
  1658. // if (status == PHAuthorizationStatusAuthorized) {
  1659. // // Access has been granted.
  1660. // [self.currentOperationNode save];
  1661. // }
  1662. // else {
  1663. // // Access has been denied.
  1664. // [self showAlertForAuthorizationWithText:@"请设置相册权限后重试"];
  1665. // }
  1666. // });
  1667. // }];
  1668. }
  1669. - (void)discardPhotoResultButtonTouchUpInside:(id)sender{
  1670. self.panGesture.enabled = YES;
  1671. // if([self.currentOperationNode respondsToSelector:@selector(discardPhotoResultButtonTouchUpInside)]){
  1672. // [self.currentOperationNode discardPhotoResultButtonTouchUpInside];
  1673. // }
  1674. NSString *title = @"返回会清空已拍摄数据,请确认!";
  1675. // if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  1676. // title = @"返回会清空已拍摄视频,请确认!";
  1677. // } else if (self.mode == SDK_CAPTURE_MODE_PANORAMA || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1678. // title = @"返回会清空已拼接图片,请确认!";
  1679. // }
  1680. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:title leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1681. [alertController dismissViewControllerAnimated:NO completion:^{}];
  1682. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1683. // if (self.mode == SDK_CAPTURE_MODE_CONTINUOUS) {
  1684. [self.resourceModel.continousArray removeAllObjects];
  1685. // } else if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  1686. [self.resourceModel.movieArray removeAllObjects];
  1687. // } else if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  1688. [self.resourceModel.panoramArray removeAllObjects];
  1689. // } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1690. [self.resourceModel.aiPanoramArray removeAllObjects];
  1691. // }
  1692. [self updateViewStatus];
  1693. [alertController dismissViewControllerAnimated:NO completion:^{
  1694. }];
  1695. }];
  1696. }
  1697. - (void)albumButtonTouchUpInside:(id)sender{
  1698. [self performSegueWithIdentifier:@"show-photoalbum" sender:nil];
  1699. // if([self.currentOperationNode respondsToSelector:@selector(segueForAlbum)]){
  1700. // [self performSegueWithIdentifier:self.currentOperationNode.segueForAlbum sender:nil];
  1701. // }
  1702. }
  1703. - (__kindof id<OperationNodeProtocol>)currentOperationNode{
  1704. // NSLog(@"======:%u",self.mode);
  1705. // NSLog(@"------:%@",self.operationNodes);
  1706. return self.operationNodes[@(self.mode)];
  1707. }
  1708. - (void)updateNumberLabel {
  1709. switch (self.mode) {
  1710. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1711. if (self.resourceModel.continousArray.count > 0) {
  1712. self.numberOfImagesLabel.hidden = NO;
  1713. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已连拍%ld张", self.resourceModel.continousArray.count];
  1714. } else {
  1715. self.numberOfImagesLabel.hidden = YES;
  1716. }
  1717. }
  1718. break;
  1719. case SDK_CAPTURE_MODE_MOVIE:{
  1720. if (self.resourceModel.movieArray.count > 0) {
  1721. self.numberOfImagesLabel.hidden = NO;
  1722. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍视频%ld条", self.resourceModel.movieArray.count];
  1723. } else {
  1724. self.numberOfImagesLabel.hidden = YES;
  1725. }
  1726. }
  1727. break;
  1728. case SDK_CAPTURE_MODE_PANORAMA:
  1729. {
  1730. if (self.resourceModel.panoramArray.count > 0) {
  1731. self.numberOfImagesLabel.hidden = NO;
  1732. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拼接%ld张", self.resourceModel.panoramArray.count];
  1733. } else {
  1734. self.numberOfImagesLabel.hidden = YES;
  1735. }
  1736. }
  1737. break;
  1738. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  1739. {
  1740. if (self.resourceModel.aiPanoramArray.count > 0) {
  1741. self.numberOfImagesLabel.hidden = NO;
  1742. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍摄%ld张", self.resourceModel.aiPanoramArray.count];
  1743. } else {
  1744. self.numberOfImagesLabel.text = @"单击拍摄,长按拼接";
  1745. self.numberOfImagesLabel.hidden = NO;
  1746. }
  1747. }
  1748. break;
  1749. default:
  1750. self.numberOfImagesLabel.hidden = YES;
  1751. break;
  1752. }
  1753. }
  1754. #pragma mark 相机单拍,和连拍的代理
  1755. - (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
  1756. NSData* imageData = [photo fileDataRepresentation];
  1757. if (imageData == nil){
  1758. NSLog(@"%s", "unable to create image data");
  1759. return;
  1760. }
  1761. NSString *path = [LenzDataManager saveImageWith:imageData mode:self.mode];
  1762. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1763. itemModel.path = path;
  1764. itemModel.cameraType = [SDKParameters shared].cameraPositionString;
  1765. itemModel.mode = self.mode;
  1766. UIImage *image = [[UIImage alloc] initWithData:imageData];
  1767. itemModel.image = image;
  1768. float value = [image checkRemake];
  1769. itemModel.isRemake = value > 0.95;
  1770. // [self.resourceModel.lastShowArray addObject:image];
  1771. switch (self.mode) {
  1772. case SDK_CAPTURE_MODE_CONTINUOUS:{
  1773. [self.resourceModel.continousArray addObject:itemModel];
  1774. }
  1775. break;
  1776. case SDK_CAPTURE_MODE_SINGLE: {
  1777. [self.resourceModel.singleArray addObject:itemModel];
  1778. }
  1779. break;
  1780. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  1781. [self.resourceModel.aiPanoramArray addObject:itemModel];
  1782. }
  1783. break;
  1784. default:
  1785. break;
  1786. }
  1787. self.resourceModel.lastIndex = self.mode;
  1788. [self updateViewStatus];
  1789. // [self.cachesArray addObject:image];
  1790. //
  1791. // [self.typeArray addObject:@"photo"];
  1792. //
  1793. // [self.totalArray addObject:image];
  1794. //
  1795. // self.capturedImage = image;
  1796. [self.currentOperationNode triggered];
  1797. if(self.mode == SDK_CAPTURE_MODE_SINGLE){
  1798. // self.panGesture.enabled = NO;
  1799. [self stopCaptureSession];
  1800. [self performSegueWithIdentifier:@"preview_single" sender:nil];
  1801. // [self showPreviewView:NO];
  1802. }
  1803. else if(self.mode == SDK_CAPTURE_MODE_CONTINUOUS){
  1804. self.discardPhotoButton.hidden = NO;
  1805. self.savePhotoButton.hidden = NO;
  1806. }
  1807. self.resultImageView.image = image;
  1808. // [self updateNumberLabel];
  1809. }
  1810. - (void)updateViewStatus {
  1811. dispatch_async(dispatch_get_main_queue(), ^{
  1812. UIImage *image = nil;
  1813. switch (self.resourceModel.lastIndex) {
  1814. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1815. if (self.resourceModel.continousArray.count > 0) {
  1816. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1817. image = model.image;
  1818. } else {
  1819. if (self.resourceModel.singleArray.count > 0) {
  1820. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1821. image = model.image;
  1822. } else if (self.resourceModel.movieArray.count > 0) {
  1823. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1824. image = model.image;
  1825. } else if (self.resourceModel.panoramArray.count > 0) {
  1826. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1827. image = model.image;
  1828. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1829. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1830. image = model.image;
  1831. }
  1832. }
  1833. }
  1834. break;
  1835. case SDK_CAPTURE_MODE_SINGLE:{
  1836. if (self.resourceModel.singleArray.count > 0) {
  1837. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1838. image = model.image;
  1839. } else {
  1840. if (self.resourceModel.continousArray.count > 0) {
  1841. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1842. image = model.image;
  1843. } else if (self.resourceModel.movieArray.count > 0) {
  1844. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1845. image = model.image;
  1846. } else if (self.resourceModel.panoramArray.count > 0) {
  1847. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1848. image = model.image;
  1849. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1850. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1851. image = model.image;
  1852. }
  1853. }
  1854. }
  1855. break;
  1856. case SDK_CAPTURE_MODE_MOVIE:{
  1857. if (self.resourceModel.movieArray.count > 0) {
  1858. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1859. image = model.image;
  1860. } else {
  1861. if (self.resourceModel.singleArray.count > 0) {
  1862. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1863. image = model.image;
  1864. } else if (self.resourceModel.continousArray.count > 0) {
  1865. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1866. image = model.image;
  1867. } else if (self.resourceModel.panoramArray.count > 0) {
  1868. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1869. image = model.image;
  1870. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1871. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1872. image = model.image;
  1873. }
  1874. }
  1875. }
  1876. break;
  1877. case SDK_CAPTURE_MODE_PANORAMA:{
  1878. if (self.resourceModel.panoramArray.count > 0) {
  1879. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1880. image = model.image;
  1881. } else {
  1882. if (self.resourceModel.singleArray.count > 0) {
  1883. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1884. image = model.image;
  1885. } else if (self.resourceModel.movieArray.count > 0) {
  1886. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1887. image = model.image;
  1888. } else if (self.resourceModel.continousArray.count > 0) {
  1889. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1890. image = model.image;
  1891. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  1892. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1893. image = model.image;
  1894. }
  1895. }
  1896. }
  1897. break;
  1898. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:{
  1899. if (self.resourceModel.aiPanoramArray.count > 0) {
  1900. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  1901. image = model.image;
  1902. } else {
  1903. if (self.resourceModel.singleArray.count > 0) {
  1904. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  1905. image = model.image;
  1906. } else if (self.resourceModel.movieArray.count > 0) {
  1907. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  1908. image = model.image;
  1909. } else if (self.resourceModel.panoramArray.count > 0) {
  1910. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  1911. image = model.image;
  1912. } else if (self.resourceModel.continousArray.count > 0) {
  1913. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  1914. image = model.image;
  1915. }
  1916. }
  1917. }
  1918. break;
  1919. default:
  1920. break;
  1921. }
  1922. if (image) {
  1923. self.ablumImageView.image = image;
  1924. self.ablumImageView.hidden = NO;
  1925. self.discardPhotoButton.hidden = NO;
  1926. self.savePhotoButton.hidden = NO;
  1927. self.backButton.hidden = YES;
  1928. } else {
  1929. self.ablumImageView.image = nil;
  1930. self.ablumImageView.hidden = YES;
  1931. self.discardPhotoButton.hidden = YES;
  1932. self.savePhotoButton.hidden = YES;
  1933. self.backButton.hidden = NO;
  1934. }
  1935. [self updateNumberLabel];
  1936. });
  1937. }
  1938. #pragma mark - AVCaptureFileOutputRecordingDelegate
  1939. - (void)captureOutput:(AVCaptureFileOutput *)output didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections error:(NSError *)error{
  1940. //视频录制
  1941. BOOL recordedSuccessfully = YES;
  1942. // A problem occurred: Find out if the recording was successful.
  1943. if(error.code == AVErrorMaximumDurationReached){
  1944. NSLog(@"%@", [error localizedDescription]);
  1945. }
  1946. else if (error.code == AVErrorDiskFull){
  1947. NSLog(@"%@", [error localizedDescription]);
  1948. dispatch_async(dispatch_get_main_queue(), ^{
  1949. [[NSNotificationCenter defaultCenter] postNotificationName:LenzSDKNotificationDiskIsFull object:error];
  1950. });
  1951. }
  1952. else if (error.code == AVErrorSessionWasInterrupted){
  1953. NSLog(@"%@", [error localizedDescription]);
  1954. }
  1955. id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
  1956. if (value) {
  1957. recordedSuccessfully = [value boolValue];
  1958. [self.recordTimer invalidate];
  1959. self.recordTimer = nil;
  1960. }
  1961. if(!recordedSuccessfully){
  1962. return;
  1963. }
  1964. OperationNodeMovie *node = nil;
  1965. if ([self.currentOperationNode isKindOfClass:[OperationNodeMovie class]]) {
  1966. node = (OperationNodeMovie *)self.currentOperationNode;
  1967. if (node.isRecording) {
  1968. [self.currentOperationNode takePhotoButtonTouched];
  1969. }
  1970. }
  1971. // NSString *path = [LenzDataManager saveVideoUrl:outputFileURL model:self.mode];
  1972. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1973. itemModel.path = outputFileURL.absoluteString;
  1974. itemModel.cameraType = [SDKParameters shared].cameraPositionString;
  1975. itemModel.mode = self.mode;
  1976. itemModel.image = [self videoFrameImageWith:outputFileURL];
  1977. [self.resourceModel.movieArray addObject:itemModel];
  1978. self.resourceModel.lastIndex = self.mode;
  1979. // self.recordedFileUrl = outputFileURL;
  1980. // [self.typeArray addObject:@"movie"];
  1981. [self updateViewStatus];
  1982. [self.timerLabel updateWith:0];
  1983. dispatch_async(dispatch_get_main_queue(), ^{
  1984. [self.currentOperationNode triggered];
  1985. self.thumbnailOritaionByCurrentVideoOrientation = UIImageOrientationUp;
  1986. });
  1987. }
  1988. - (BOOL)encodeFrame:(CMSampleBufferRef) sampleBuffer{
  1989. if (CMSampleBufferDataIsReady(sampleBuffer)) {
  1990. if (self.videoWriter.status == AVAssetWriterStatusUnknown) {
  1991. CMTime startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
  1992. [self.videoWriter startWriting];
  1993. [self.videoWriter startSessionAtSourceTime:startTime];
  1994. }
  1995. if (self.videoWriter.status == AVAssetWriterStatusFailed) {
  1996. NSLog(@"writer error %@", self.videoWriter.error.localizedDescription);
  1997. return NO;
  1998. }
  1999. if (self.videoWriterInput.readyForMoreMediaData) {
  2000. [self.videoWriterInput appendSampleBuffer:sampleBuffer];
  2001. return YES;
  2002. }
  2003. }
  2004. return NO;
  2005. }
  2006. #pragma mark - AVCaptureAudioDataOutputSampleBufferDelegate
  2007. #pragma mark - UIViewControllerTransitioningDelegate
  2008. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
  2009. return [[CustomModalViewTransitionPresent alloc] init];
  2010. }
  2011. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
  2012. return [[CustomModalViewTransitionDismiss alloc] init];
  2013. }
  2014. #pragma mark - PhotoListViewControllerDelegate
  2015. //删除视频
  2016. - (void)deleteMovie: (MovieListCellModel*)model completion: (DeleteImageCompletionCallBackType)completion{
  2017. for (int i = 0; i < self.totalArray.count; i ++) {
  2018. UIImage *image = self.totalArray[i];
  2019. if (image == (UIImage *)model.movieModel.thumbnail) {
  2020. [self.totalArray removeObjectAtIndex:i];
  2021. [self.typeArray removeObjectAtIndex:i];
  2022. break;;
  2023. }
  2024. }
  2025. // id<OperationNodeProtocol> curr = self.currentOperationNode;
  2026. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2027. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2028. [curr deleteCacheForKey:model.movieModel.fileUrl.path completion:completion];
  2029. }
  2030. }
  2031. //连拍删除
  2032. - (void)deleteImage:(UIImage *)image completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2033. // id<OperationNodeProtocol> curr = self.currentOperationNode;
  2034. for (int i = 0; i < self.totalArray.count; i ++) {
  2035. UIImage *img = self.totalArray[i];
  2036. if (img == image) {
  2037. [self.totalArray removeObjectAtIndex:i];
  2038. [self.typeArray removeObjectAtIndex:i];
  2039. break;;
  2040. }
  2041. }
  2042. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2043. if([curr respondsToSelector:@selector(deleteCacheForImage:completion:)]){
  2044. [curr deleteCacheForImage:image completion:completion];
  2045. }
  2046. }
  2047. - (void)deleteImageWithName:(NSString *)name completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2048. id<OperationNodeProtocol> curr = self.currentOperationNode;
  2049. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2050. [curr deleteCacheForKey:name completion:completion];
  2051. }
  2052. }
  2053. #pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate
  2054. - (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
  2055. @autoreleasepool {
  2056. if (connection == [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo]) {
  2057. NSLog(@"11111");
  2058. [self.stitchkLock lock];
  2059. // dispatch_semaphore_wait(self.videoStitchSemaphore, DISPATCH_TIME_FOREVER);
  2060. OperationNodeVideoBase *base = nil;
  2061. if ([self.currentOperationNode isKindOfClass:[OperationNodeVideoBase class]]) {
  2062. base = (OperationNodeVideoBase *)self.currentOperationNode;
  2063. }
  2064. NSLog(@"2222");
  2065. if (self.isVideoStitchStopedWhenRecording &&
  2066. (self.stitchResult != LenVideoStitchResultFail && self.stitchResult != LenVideoStitchResultStitchFail)) {
  2067. [self updateViewStatusWhenStitchSave:YES];
  2068. self.isStitchBigImage = YES;
  2069. }
  2070. [LenStitcher videoStitchWith:sampleBuffer
  2071. dirction:(LenVideoStitchDirction)self.panoramOrientationGuideView.selectedItemIndex
  2072. isStop:self.isVideoStitchStopedWhenRecording
  2073. complete:^(LenVideoStitchResult result, LenVideoStitchNeedSave needSave) {
  2074. self.stitchResult = result;
  2075. NSLog(@"333");
  2076. self.isVideoStitchStopedWhenRecording = NO;
  2077. UIImage *image = [LenStitcher getCurrentPanoramaShowImage];
  2078. LenzResourceItemModel *model = nil;
  2079. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2080. model = self.resourceModel.panoramArray.lastObject;
  2081. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2082. model = self.resourceModel.aiPanoramArray.lastObject;
  2083. }
  2084. if (!image || !model) {
  2085. [self.stitchkLock unlock];
  2086. return;
  2087. }
  2088. if (result == LenVideoStitchResultSuccess) {
  2089. dispatch_async(dispatch_get_main_queue(), ^{
  2090. if (self.isStitchBigImage) {
  2091. //保存大图拼接路径
  2092. model.cameraType = [SDKParameters shared].cameraPositionString;
  2093. model.mode = self.mode;
  2094. if ([LenStitcher getCurrentPanoramaShow]) {
  2095. model.image = image;
  2096. model.path = [LenStitcher getCurrentPanoramaShow];
  2097. }
  2098. [self updateViewStatusWhenStitchSave:NO];
  2099. self.isStitchBigImage = NO;
  2100. [self.panoramaGuideView clearImage];
  2101. [self updateViewStatus];
  2102. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  2103. } else {
  2104. if (base.isRecording) {
  2105. if (needSave && [SDKParameters shared].keyFrame.boolValue) {
  2106. NSString *path = [LenzDataManager saveImageWith:UIImageJPEGRepresentation(image, .6) mode:self.mode];
  2107. // itemModel.path = path;
  2108. if (path) {
  2109. [model.keyFrame addObject:path];
  2110. }
  2111. }
  2112. if (self.panoramOrientationGuideView.selectedItemIndex != PanoramaOrientationViewAny) {
  2113. [self.panoramaGuideView showImageWith:image dir:self.panoramOrientationGuideView.selectedItemIndex];
  2114. } else {
  2115. self.ablumImageView.hidden = NO;
  2116. self.ablumImageView.image = image;
  2117. }
  2118. }
  2119. }
  2120. self.resourceModel.lastIndex = self.mode;
  2121. });
  2122. } else {
  2123. if (!base.isRecording) {
  2124. // [self removeLastStich];
  2125. //停止拼接,移除保存中 非success数据
  2126. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2127. NSMutableArray *array = [NSMutableArray array];
  2128. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2129. if (obj.path.length) {
  2130. [array addObject:obj];
  2131. }
  2132. }];
  2133. self.resourceModel.panoramArray = array;
  2134. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2135. NSMutableArray *array = [NSMutableArray array];
  2136. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2137. if (obj.path.length) {
  2138. [array addObject:obj];
  2139. }
  2140. }];
  2141. self.resourceModel.aiPanoramArray = array;
  2142. }
  2143. [self updateViewStatus];
  2144. [self.stitchkLock unlock];
  2145. return;
  2146. }
  2147. if (result == LenVideoStitchResultFail || result == LenVideoStitchResultStitchFail) {
  2148. if (result == LenVideoStitchResultFail) {
  2149. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接失败,流程结束"];
  2150. } else {
  2151. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接大图失败,流程结束"];
  2152. }
  2153. self.isVideoStitchStopedWhenRecording = NO;
  2154. // base.isRecording = NO;
  2155. dispatch_async(dispatch_get_main_queue(), ^{
  2156. [base takePhotoButtonTouched];
  2157. [self stopMotion];
  2158. [self takePhotoButtonTouchUpInside:[NSObject new]];
  2159. [self removeLastStich];
  2160. [self updateViewStatusWhenStitchFail];
  2161. [self.panoramaGuideView clearImage];
  2162. [self updateViewStatus];
  2163. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  2164. });
  2165. [SVProgressHUD dismissWithDelay:3 completion:^{
  2166. }];
  2167. } else if(result == LenVideoStitchResultSlowMore) {
  2168. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"特征点变少,放慢速度"];
  2169. } else if (result == LenVideoStitchResultSlow) {
  2170. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"特征点极少,即将失败"];
  2171. } else {
  2172. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"请勿往反方向移动"];
  2173. }
  2174. }
  2175. [self.stitchkLock unlock];
  2176. // dispatch_semaphore_signal(self.videoStitchSemaphore);
  2177. }];
  2178. }
  2179. }
  2180. }
  2181. - (void)removeLastStich {
  2182. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2183. if (self.resourceModel.panoramArray.count > 0) {
  2184. [self.resourceModel.panoramArray removeLastObject];
  2185. }
  2186. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2187. if (self.resourceModel.aiPanoramArray.count > 0) {
  2188. [self.resourceModel.aiPanoramArray removeLastObject];
  2189. }
  2190. }
  2191. }
  2192. //*
  2193. #pragma mark - Navigation
  2194. // In a storyboard-based application, you will often want to do a little preparation before navigation
  2195. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  2196. // Get the new view controller using [segue destinationViewController].
  2197. // Pass the selected object to the new view controller.
  2198. if([segue.identifier isEqualToString:@"show-photos"]){
  2199. if([segue.destinationViewController isKindOfClass:[PhotoListViewController class]]){
  2200. PhotoListViewController* dst = segue.destinationViewController;
  2201. OperationNodeMultiple* node = self.currentOperationNode;
  2202. dst.transitioningDelegate = self;
  2203. [dst setImagesInMemory:node.cachesInMemory andImageNamesOnDisk:node.cachesOnDisk];
  2204. dst.delegate = self;
  2205. }
  2206. }
  2207. else if([segue.identifier isEqualToString:@"show-movies"]){
  2208. if([segue.destinationViewController isKindOfClass:[MovieListViewController class]]){
  2209. MovieListViewController* dst = segue.destinationViewController;
  2210. OperationNodeMovie* node = self.currentOperationNode;
  2211. dst.transitioningDelegate = self;
  2212. dst.movieModels = node.cachedMovies;
  2213. dst.delegate = self;
  2214. }
  2215. }
  2216. else if([segue.identifier isEqualToString:@"preview_single"]){
  2217. PreviewSingleViewController* dst = segue.destinationViewController;
  2218. dst.singleModeNode = self.currentOperationNode;
  2219. if (self.resourceModel.singleArray.count > 0) {
  2220. LenzResourceItemModel *model = self.resourceModel.singleArray.firstObject;
  2221. dst.image = model.image;
  2222. }
  2223. // dst.image = self.capturedImage;
  2224. }else if ([segue.identifier isEqualToString:@"show-photoalbum"]){
  2225. PhotoAlbumListViewController *dst = segue.destinationViewController;
  2226. dst.typeArray = self.typeArray;
  2227. //图片数据
  2228. NSString *typeStr = self.typeArray.lastObject;
  2229. // if ([typeStr isEqualToString:@"photo"]) {
  2230. OperationNodeMultiple* node = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2231. // OperationNodeMultiple* node = self.currentOperationNode;
  2232. dst.node = node;
  2233. dst.photoListVC.transitioningDelegate = self;
  2234. [dst.photoListVC setImagesInMemory:node.cachesInMemory andImageNamesOnDisk:node.cachesOnDisk];
  2235. dst.photoListVC.delegate = self;
  2236. // }else if ([typeStr isEqualToString:@"movie"]) {
  2237. OperationNodeMovie* movieNode = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2238. dst.movieListVC.transitioningDelegate = self;
  2239. dst.movieListVC.movieModels = movieNode.cachedMovies;
  2240. dst.movieListVC.delegate = self;
  2241. // }
  2242. //视频数据
  2243. }
  2244. }
  2245. //*/
  2246. - (void)clearSingleData {
  2247. [self.resourceModel.singleArray removeAllObjects];
  2248. [self updateViewStatus];
  2249. }
  2250. - (UIImage *)videoFrameImageWith:(NSURL *)url {
  2251. AVURLAsset* asset = [[AVURLAsset alloc] initWithURL:url options:nil];
  2252. AVAssetImageGenerator *generateImg = [[AVAssetImageGenerator alloc] initWithAsset:asset];
  2253. NSError *err = NULL;
  2254. CMTime time = CMTimeMake(1, 65);
  2255. CGImageRef refImg = [generateImg copyCGImageAtTime:time actualTime:NULL error:&err];
  2256. UIImage *frameImage= [[UIImage alloc] initWithCGImage:refImg scale:1.0 orientation:self.thumbnailOritaionByCurrentVideoOrientation];
  2257. return frameImage;
  2258. }
  2259. @end