PCSBaseViewController.m 111 KB

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