PCSBaseViewController.m 137 KB

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