PCSBaseViewController.m 107 KB

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