/
MediaModule.m
2244 lines (1922 loc) Β· 87.7 KB
/
MediaModule.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Titanium SDK
* Copyright TiDev, Inc. 04/07/2022-Present. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#ifdef USE_TI_MEDIA
#import "MediaModule.h"
#import "TiMediaAudioSession.h"
#import "TiMediaItem.h"
#import "TiMediaMusicPlayer.h"
#import <TitaniumKit/Mimetypes.h>
#import <TitaniumKit/Ti2DMatrix.h>
#import <TitaniumKit/TiApp.h>
#import <TitaniumKit/TiBlob.h>
#import <TitaniumKit/TiFile.h>
#import <TitaniumKit/TiUtils.h>
#import <TitaniumKit/TiViewProxy.h>
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetExportSession.h>
#import <AVFoundation/AVFAudio.h>
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVMediaFormat.h>
#import <AudioToolbox/AudioToolbox.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import <Photos/Photos.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIPopoverController.h>
#if defined(USE_TI_MEDIAHASPHOTOGALLERYPERMISSIONS) && !TARGET_OS_MACCATALYST
#import <AssetsLibrary/AssetsLibrary.h>
#endif
#import "TiUIiOSLivePhoto.h"
#ifdef USE_TI_MEDIAVIDEOPLAYER
#import "TiMediaVideoPlayerProxy.h"
#endif
#import <UniformTypeIdentifiers/UTCoreTypes.h>
// by default, we want to make the camera fullscreen and
// these transform values will scale it when we have our own overlay
enum {
MediaModuleErrorUnknown,
MediaModuleErrorBusy,
MediaModuleErrorNoCamera,
MediaModuleErrorNoVideo,
MediaModuleErrorNoMusicPlayer
};
// Have to distinguish between filterable and nonfilterable properties
#if defined(USE_TI_MEDIAOPENMUSICLIBRARY) || defined(USE_TI_MEDIAQUERYMUSICLIBRARY) || defined(USE_TI_MEDIASYSTEMMUSICPLAYER) || defined(USE_TI_MEDIAAPPMUSICPLAYER) || defined(USE_TI_MEDIAGETSYSTEMMUSICPLAYER) || defined(USE_TI_MEDIAGETAPPMUSICPLAYER)
static NSMutableDictionary *TI_itemProperties;
static NSDictionary *TI_filterableItemProperties;
#endif
@interface TiImagePickerController : UIImagePickerController {
@private
BOOL autoRotate;
}
@end
@implementation TiImagePickerController
- (id)initWithProperties:(NSDictionary *)dict_
{
if (self = [self init]) {
autoRotate = [TiUtils boolValue:@"autorotate" properties:dict_ def:YES];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.edgesForExtendedLayout = UIRectEdgeNone;
[self prefersStatusBarHidden];
[self setNeedsStatusBarAppearanceUpdate];
}
- (BOOL)shouldAutorotate
{
return autoRotate;
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (UIViewController *)childViewControllerForStatusBarHidden
{
return nil;
}
- (UIViewController *)childViewControllerForStatusBarStyle
{
return nil;
}
@end
@implementation MediaModule
@synthesize popoverView;
- (void)dealloc
{
[self destroyPicker];
#if defined(USE_TI_MEDIAGETAPPMUSICPLAYER) || defined(USE_TI_MEDIAAPPMUSICPLAYER) || defined(USE_TI_MEDIAGETSYSTEMMUSICPLAYER) || defined(USE_TI_MEDIASYSTEMMUSICPLAYER)
RELEASE_TO_NIL(systemMusicPlayer);
RELEASE_TO_NIL(appMusicPlayer);
#endif
RELEASE_TO_NIL(popoverView);
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
#pragma mark Static Properties
#if defined(USE_TI_MEDIAOPENMUSICLIBRARY) || defined(USE_TI_MEDIAQUERYMUSICLIBRARY) || defined(USE_TI_MEDIASYSTEMMUSICPLAYER) || defined(USE_TI_MEDIAAPPMUSICPLAYER) || defined(USE_TI_MEDIAGETSYSTEMMUSICPLAYER) || defined(USE_TI_MEDIAGETAPPMUSICPLAYER)
+ (NSDictionary *)filterableItemProperties
{
if (TI_filterableItemProperties == nil) {
TI_filterableItemProperties = [[NSDictionary alloc] initWithObjectsAndKeys:MPMediaItemPropertyMediaType, @"mediaType",
MPMediaItemPropertyTitle, @"title",
MPMediaItemPropertyAlbumTitle, @"albumTitle",
MPMediaItemPropertyArtist, @"artist",
MPMediaItemPropertyAlbumArtist, @"albumArtist",
MPMediaItemPropertyGenre, @"genre",
MPMediaItemPropertyComposer, @"composer",
MPMediaItemPropertyIsCompilation, @"isCompilation",
MPMediaItemPropertyPlayCount, @"playCount",
MPMediaItemPropertyPersistentID, @"persistentID",
MPMediaItemPropertyAlbumPersistentID, @"albumPersistentID",
MPMediaItemPropertyAlbumArtistPersistentID, @"albumArtistPersistentID",
MPMediaItemPropertyGenrePersistentID, @"genrePersistentID",
MPMediaItemPropertyComposerPersistentID, @"composerPersistentID",
MPMediaItemPropertyIsCloudItem, @"isCloudItem",
[TiUtils isIOSVersionOrGreater:@"9.2"] ? MPMediaItemPropertyHasProtectedAsset : NO, @"hasProtectedAsset",
MPMediaItemPropertyPodcastTitle, @"podcastTitle",
MPMediaItemPropertyPodcastPersistentID, @"podcastPersistentID",
nil];
}
return TI_filterableItemProperties;
}
+ (NSDictionary *)itemProperties
{
if (TI_itemProperties == nil) {
TI_itemProperties = [[NSMutableDictionary alloc] initWithObjectsAndKeys:MPMediaItemPropertyPlaybackDuration, @"playbackDuration",
MPMediaItemPropertyAlbumTrackNumber, @"albumTrackNumber",
MPMediaItemPropertyAlbumTrackCount, @"albumTrackCount",
MPMediaItemPropertyDiscNumber, @"discNumber",
MPMediaItemPropertyDiscCount, @"discCount",
MPMediaItemPropertyLyrics, @"lyrics",
MPMediaItemPropertySkipCount, @"skipCount",
MPMediaItemPropertyRating, @"rating",
MPMediaItemPropertyAssetURL, @"assetURL",
MPMediaItemPropertyIsExplicit, @"isExplicit",
MPMediaItemPropertyReleaseDate, @"releaseDate",
MPMediaItemPropertyBeatsPerMinute, @"beatsPerMinute",
MPMediaItemPropertyComments, @"comments",
MPMediaItemPropertyLastPlayedDate, @"lastPlayedDate",
MPMediaItemPropertyUserGrouping, @"userGrouping",
MPMediaItemPropertyBookmarkTime, @"bookmarkTime",
nil];
TI_itemProperties[@"dateAdded"] = MPMediaItemPropertyDateAdded;
if ([TiUtils isIOSVersionOrGreater:@"10.3"]) {
TI_itemProperties[@"playbackStoreID"] = MPMediaItemPropertyPlaybackStoreID;
}
}
return TI_itemProperties;
}
#endif
#pragma mark Public Properties
- (NSString *)apiName
{
return @"Ti.Media";
}
#ifdef USE_TI_MEDIAAUDIORECORDER
MAKE_SYSTEM_UINT(AUDIO_FORMAT_LINEAR_PCM, kAudioFormatLinearPCM);
MAKE_SYSTEM_UINT(AUDIO_FORMAT_ULAW, kAudioFormatULaw);
MAKE_SYSTEM_UINT(AUDIO_FORMAT_ALAW, kAudioFormatALaw);
MAKE_SYSTEM_UINT(AUDIO_FORMAT_IMA4, kAudioFormatAppleIMA4);
MAKE_SYSTEM_UINT(AUDIO_FORMAT_ILBC, kAudioFormatiLBC);
MAKE_SYSTEM_UINT(AUDIO_FORMAT_APPLE_LOSSLESS, kAudioFormatAppleLossless);
MAKE_SYSTEM_UINT(AUDIO_FORMAT_AAC, kAudioFormatMPEG4AAC);
MAKE_SYSTEM_UINT(AUDIO_FILEFORMAT_WAVE, kAudioFileWAVEType);
MAKE_SYSTEM_UINT(AUDIO_FILEFORMAT_AIFF, kAudioFileAIFFType);
MAKE_SYSTEM_UINT(AUDIO_FILEFORMAT_MP3, kAudioFileMP3Type);
MAKE_SYSTEM_UINT(AUDIO_FILEFORMAT_MP4, kAudioFileMPEG4Type);
MAKE_SYSTEM_UINT(AUDIO_FILEFORMAT_MP4A, kAudioFileM4AType);
MAKE_SYSTEM_UINT(AUDIO_FILEFORMAT_CAF, kAudioFileCAFType);
MAKE_SYSTEM_UINT(AUDIO_FILEFORMAT_3GPP, kAudioFile3GPType);
MAKE_SYSTEM_UINT(AUDIO_FILEFORMAT_3GP2, kAudioFile3GP2Type);
MAKE_SYSTEM_UINT(AUDIO_FILEFORMAT_AMR, kAudioFileAMRType);
#endif
#ifdef USE_TI_MEDIACAMERA_AUTHORIZATION_AUTHORIZED
MAKE_SYSTEM_UINT(CAMERA_AUTHORIZATION_AUTHORIZED, AVAuthorizationStatusAuthorized);
#endif
#ifdef USE_TI_MEDIACAMERA_AUTHORIZATION_DENIED
MAKE_SYSTEM_UINT(CAMERA_AUTHORIZATION_DENIED, AVAuthorizationStatusDenied);
#endif
#ifdef USE_TI_MEDIACAMERA_AUTHORIZATION_RESTRICTED
MAKE_SYSTEM_UINT(CAMERA_AUTHORIZATION_RESTRICTED, AVAuthorizationStatusRestricted);
#endif
#ifdef USE_TI_MEDIACAMERA_AUTHORIZATION_UNKNOWN
MAKE_SYSTEM_UINT(CAMERA_AUTHORIZATION_UNKNOWN, AVAuthorizationStatusNotDetermined);
#endif
#if defined(USE_TI_MEDIA) && (defined(USE_TI_MEDIAAUDIOPLAYER) || defined(USE_TI_MEDIAVIDEOPLAYER) || defined(USE_TI_MEDIASOUND) || defined(USE_TI_MEDIAAUDIORECORDER))
// Constants for currentRoute
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_LINEIN, AVAudioSessionPortLineIn)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_BUILTINMIC, AVAudioSessionPortBuiltInMic)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_HEADSETMIC, AVAudioSessionPortHeadsetMic)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_LINEOUT, AVAudioSessionPortLineOut)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_HEADPHONES, AVAudioSessionPortHeadphones)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_BLUETOOTHA2DP, AVAudioSessionPortBluetoothA2DP)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_BUILTINRECEIVER, AVAudioSessionPortBuiltInReceiver)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_BUILTINSPEAKER, AVAudioSessionPortBuiltInSpeaker)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_HDMI, AVAudioSessionPortHDMI)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_AIRPLAY, AVAudioSessionPortAirPlay)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_BLUETOOTHHFP, AVAudioSessionPortBluetoothHFP)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_USBAUDIO, AVAudioSessionPortUSBAudio)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_BLUETOOTHLE, AVAudioSessionPortBluetoothLE)
MAKE_SYSTEM_STR(AUDIO_SESSION_PORT_CARAUDIO, AVAudioSessionPortCarAudio)
//Constants for AudioSessions
MAKE_SYSTEM_STR(AUDIO_SESSION_CATEGORY_AMBIENT, AVAudioSessionCategoryAmbient);
MAKE_SYSTEM_STR(AUDIO_SESSION_CATEGORY_SOLO_AMBIENT, AVAudioSessionCategorySoloAmbient);
MAKE_SYSTEM_STR(AUDIO_SESSION_CATEGORY_PLAYBACK, AVAudioSessionCategoryPlayback);
MAKE_SYSTEM_STR(AUDIO_SESSION_CATEGORY_RECORD, AVAudioSessionCategoryRecord);
MAKE_SYSTEM_STR(AUDIO_SESSION_CATEGORY_PLAY_AND_RECORD, AVAudioSessionCategoryPlayAndRecord);
MAKE_SYSTEM_UINT(AUDIO_SESSION_OVERRIDE_ROUTE_NONE, AVAudioSessionPortOverrideNone);
MAKE_SYSTEM_UINT(AUDIO_SESSION_OVERRIDE_ROUTE_SPEAKER, AVAudioSessionPortOverrideSpeaker);
#endif
// Constants for ImageView.scalingMode
MAKE_SYSTEM_PROP(IMAGE_SCALING_AUTO, -1);
MAKE_SYSTEM_PROP(IMAGE_SCALING_NONE, UIViewContentModeCenter);
MAKE_SYSTEM_PROP(IMAGE_SCALING_FILL, UIViewContentModeScaleToFill);
MAKE_SYSTEM_PROP(IMAGE_SCALING_ASPECT_FILL, UIViewContentModeScaleAspectFill);
MAKE_SYSTEM_PROP(IMAGE_SCALING_ASPECT_FIT, UIViewContentModeScaleAspectFit);
// Constants for VideoPlayer.playbackState
MAKE_SYSTEM_PROP(VIDEO_PLAYBACK_STATE_INTERRUPTED, TiVideoPlayerPlaybackStateInterrupted);
MAKE_SYSTEM_PROP(VIDEO_PLAYBACK_STATE_PAUSED, TiVideoPlayerPlaybackStatePaused);
MAKE_SYSTEM_PROP(VIDEO_PLAYBACK_STATE_PLAYING, TiVideoPlayerPlaybackStatePlaying);
MAKE_SYSTEM_PROP(VIDEO_PLAYBACK_STATE_STOPPED, TiVideoPlayerPlaybackStateStopped);
// Constants for AudioPlayer
MAKE_SYSTEM_PROP(AUDIO_STATE_INITIALIZED, TiAudioPlayerStateInitialized);
MAKE_SYSTEM_PROP(AUDIO_STATE_STARTING, TiAudioPlayerStateStartingFileThread);
MAKE_SYSTEM_PROP(AUDIO_STATE_WAITING_FOR_DATA, TiAudioPlayerStateWaitingForData);
MAKE_SYSTEM_PROP(AUDIO_STATE_WAITING_FOR_QUEUE, TiAudioPlayerStateWaitingForQueueToStart);
MAKE_SYSTEM_PROP(AUDIO_STATE_PLAYING, TiAudioPlayerStatePlaying);
MAKE_SYSTEM_PROP(AUDIO_STATE_BUFFERING, TiAudioPlayerStateBuffering);
MAKE_SYSTEM_PROP(AUDIO_STATE_STOPPING, TiAudioPlayerStateStopping);
MAKE_SYSTEM_PROP(AUDIO_STATE_STOPPED, TiAudioPlayerStateStopped);
MAKE_SYSTEM_PROP(AUDIO_STATE_PAUSED, TiAudioPlayerStatePaused);
//Constants for Camera
#if defined(USE_TI_MEDIACAMERA_FRONT) || defined(USE_TI_MEDIACAMERA_REAR) || defined(USE_TI_MEDIACAMERA_FLASH_OFF) || defined(USE_TI_MEDIACAMERA_FLASH_AUTO) || defined(USE_TI_MEDIACAMERA_FLASH_ON)
MAKE_SYSTEM_PROP(CAMERA_FRONT, UIImagePickerControllerCameraDeviceFront);
MAKE_SYSTEM_PROP(CAMERA_REAR, UIImagePickerControllerCameraDeviceRear);
MAKE_SYSTEM_PROP(CAMERA_FLASH_OFF, UIImagePickerControllerCameraFlashModeOff);
MAKE_SYSTEM_PROP(CAMERA_FLASH_AUTO, UIImagePickerControllerCameraFlashModeAuto);
MAKE_SYSTEM_PROP(CAMERA_FLASH_ON, UIImagePickerControllerCameraFlashModeOn);
#endif
//Constants for mediaTypes in openMusicLibrary
#if defined(USE_TI_MEDIAOPENMUSICLIBRARY) || defined(USE_TI_MEDIAQUERYMUSICLIBRARY)
MAKE_SYSTEM_PROP(MUSIC_MEDIA_TYPE_MUSIC, MPMediaTypeMusic);
MAKE_SYSTEM_PROP(MUSIC_MEDIA_TYPE_PODCAST, MPMediaTypePodcast);
MAKE_SYSTEM_PROP(MUSIC_MEDIA_TYPE_AUDIOBOOK, MPMediaTypeAudioBook);
MAKE_SYSTEM_PROP(MUSIC_MEDIA_TYPE_ANY_AUDIO, MPMediaTypeAnyAudio);
- (NSNumber *)MUSIC_MEDIA_TYPE_ALL
{
return NUMUINTEGER(MPMediaTypeAny);
}
//Constants for grouping in queryMusicLibrary
MAKE_SYSTEM_PROP(MUSIC_MEDIA_GROUP_TITLE, MPMediaGroupingTitle);
MAKE_SYSTEM_PROP(MUSIC_MEDIA_GROUP_ALBUM, MPMediaGroupingAlbum);
MAKE_SYSTEM_PROP(MUSIC_MEDIA_GROUP_ARTIST, MPMediaGroupingArtist);
MAKE_SYSTEM_PROP(MUSIC_MEDIA_GROUP_ALBUM_ARTIST, MPMediaGroupingAlbumArtist);
MAKE_SYSTEM_PROP(MUSIC_MEDIA_GROUP_COMPOSER, MPMediaGroupingComposer);
MAKE_SYSTEM_PROP(MUSIC_MEDIA_GROUP_GENRE, MPMediaGroupingGenre);
MAKE_SYSTEM_PROP(MUSIC_MEDIA_GROUP_PLAYLIST, MPMediaGroupingPlaylist);
MAKE_SYSTEM_PROP(MUSIC_MEDIA_GROUP_PODCAST_TITLE, MPMediaGroupingPodcastTitle);
#endif
#if defined(USE_TI_MEDIAGETAPPMUSICPLAYER) || defined(USE_TI_MEDIAAPPMUSICPLAYER) || defined(USE_TI_MEDIAGETSYSTEMMUSICPLAYER) || defined(USE_TI_MEDIASYSTEMMUSICPLAYER)
//Constants for MusicPlayer playback state
MAKE_SYSTEM_PROP(MUSIC_PLAYER_STATE_STOPPED, MPMusicPlaybackStateStopped);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_STATE_PLAYING, MPMusicPlaybackStatePlaying);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_STATE_PAUSED, MPMusicPlaybackStatePaused);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_STATE_INTERRUPTED, MPMusicPlaybackStateInterrupted);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_STATE_SEEK_FORWARD, MPMusicPlaybackStateSeekingForward);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_STATE_SEEK_BACKWARD, MPMusicPlaybackStateSeekingBackward);
//Constants for MusicPlayer repeatMode
MAKE_SYSTEM_PROP(MUSIC_PLAYER_REPEAT_DEFAULT, MPMusicRepeatModeDefault);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_REPEAT_NONE, MPMusicRepeatModeNone);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_REPEAT_ONE, MPMusicRepeatModeOne);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_REPEAT_ALL, MPMusicRepeatModeAll);
//Constants for MusicPlayer shuffleMode
MAKE_SYSTEM_PROP(MUSIC_PLAYER_SHUFFLE_DEFAULT, MPMusicShuffleModeDefault);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_SHUFFLE_NONE, MPMusicShuffleModeOff);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_SHUFFLE_SONGS, MPMusicShuffleModeSongs);
MAKE_SYSTEM_PROP(MUSIC_PLAYER_SHUFFLE_ALBUMS, MPMusicShuffleModeAlbums);
#endif
//Error constants for MediaModule
MAKE_SYSTEM_PROP(UNKNOWN_ERROR, MediaModuleErrorUnknown);
MAKE_SYSTEM_PROP(DEVICE_BUSY, MediaModuleErrorBusy);
MAKE_SYSTEM_PROP(NO_CAMERA, MediaModuleErrorNoCamera);
MAKE_SYSTEM_PROP(NO_VIDEO, MediaModuleErrorNoVideo);
MAKE_SYSTEM_PROP(NO_MUSIC_PLAYER, MediaModuleErrorNoMusicPlayer);
//Constants for mediaTypes in showCamera
#if defined(USE_TI_MEDIASHOWCAMERA) || defined(USE_TI_MEDIAOPENPHOTOGALLERY)
MAKE_SYSTEM_STR(MEDIA_TYPE_VIDEO, kUTTypeMovie);
MAKE_SYSTEM_STR(MEDIA_TYPE_PHOTO, kUTTypeImage);
MAKE_SYSTEM_STR(MEDIA_TYPE_LIVEPHOTO, kUTTypeLivePhoto);
//Constants for videoQuality for Video Editing
MAKE_SYSTEM_PROP(QUALITY_HIGH, UIImagePickerControllerQualityTypeHigh);
MAKE_SYSTEM_PROP(QUALITY_MEDIUM, UIImagePickerControllerQualityTypeMedium);
MAKE_SYSTEM_PROP(QUALITY_LOW, UIImagePickerControllerQualityTypeLow);
MAKE_SYSTEM_PROP(QUALITY_640x480, UIImagePickerControllerQualityType640x480);
MAKE_SYSTEM_PROP(QUALITY_IFRAME_1280x720, UIImagePickerControllerQualityTypeIFrame1280x720);
MAKE_SYSTEM_PROP(QUALITY_IFRAME_960x540, UIImagePickerControllerQualityTypeIFrame960x540);
#endif
// Constants for MediaTypes in VideoPlayer
#ifdef USE_TI_MEDIAVIDEOPLAYER
// Constants for VideoPlayer scalingMode
MAKE_SYSTEM_STR(VIDEO_SCALING_RESIZE, AVLayerVideoGravityResize);
MAKE_SYSTEM_STR(VIDEO_SCALING_RESIZE_ASPECT, AVLayerVideoGravityResizeAspect);
MAKE_SYSTEM_STR(VIDEO_SCALING_RESIZE_ASPECT_FILL, AVLayerVideoGravityResizeAspectFill);
// Constants for VideoPlayer mediaTypes
MAKE_SYSTEM_STR(VIDEO_MEDIA_TYPE_AUDIO, AVMediaTypeAudio);
MAKE_SYSTEM_STR(VIDEO_MEDIA_TYPE_CLOSED_CAPTION, AVMediaTypeClosedCaption);
MAKE_SYSTEM_STR(VIDEO_MEDIA_TYPE_DEPTH_DATA, AVMediaTypeDepthData);
MAKE_SYSTEM_STR(VIDEO_MEDIA_TYPE_METADATA, AVMediaTypeMetadata);
MAKE_SYSTEM_STR(VIDEO_MEDIA_TYPE_METADATA_OBJECT, AVMediaTypeMetadataObject);
MAKE_SYSTEM_STR(VIDEO_MEDIA_TYPE_MUXED, AVMediaTypeMuxed);
MAKE_SYSTEM_STR(VIDEO_MEDIA_TYPE_SUBTITLE, AVMediaTypeSubtitle);
MAKE_SYSTEM_STR(VIDEO_MEDIA_TYPE_TEXT, AVMediaTypeText);
MAKE_SYSTEM_STR(VIDEO_MEDIA_TYPE_TIMECODE, AVMediaTypeTimecode);
MAKE_SYSTEM_STR(VIDEO_MEDIA_TYPE_VIDEO, AVMediaTypeVideo);
// Constants for VideoPlayer loadState
MAKE_SYSTEM_PROP(VIDEO_LOAD_STATE_UNKNOWN, AVPlayerStatusUnknown);
MAKE_SYSTEM_PROP(VIDEO_LOAD_STATE_PLAYABLE, AVPlayerStatusReadyToPlay);
MAKE_SYSTEM_PROP(VIDEO_LOAD_STATE_FAILED, AVPlayerStatusFailed);
MAKE_SYSTEM_PROP(VIDEO_TIME_OPTION_NEAREST_KEYFRAME, VideoTimeOptionNearestKeyFrame);
MAKE_SYSTEM_PROP(VIDEO_TIME_OPTION_EXACT, VideoTimeOptionExact);
MAKE_SYSTEM_PROP(VIDEO_REPEAT_MODE_NONE, VideoRepeatModeNone);
MAKE_SYSTEM_PROP(VIDEO_REPEAT_MODE_ONE, VideoRepeatModeOne);
#endif
#if defined(USE_TI_MEDIAGETAPPMUSICPLAYER) || defined(USE_TI_MEDIAAPPMUSICPLAYER) || defined(USE_TI_MEDIAGETSYSTEMMUSICPLAYER) || defined(USE_TI_MEDIASYSTEMMUSICPLAYER)
- (TiMediaMusicPlayer *)systemMusicPlayer
{
if (systemMusicPlayer == nil) {
if (![NSThread isMainThread]) {
__block id result;
TiThreadPerformOnMainThread(
^{
result = [self systemMusicPlayer];
},
YES);
return result;
}
systemMusicPlayer = [[TiMediaMusicPlayer alloc] _initWithPageContext:[self pageContext] player:[MPMusicPlayerController systemMusicPlayer]];
}
return systemMusicPlayer;
}
- (TiMediaMusicPlayer *)appMusicPlayer
{
if (appMusicPlayer == nil) {
if (![NSThread isMainThread]) {
__block id result;
TiThreadPerformOnMainThread(
^{
result = [self appMusicPlayer];
},
YES);
return appMusicPlayer;
}
appMusicPlayer = [[TiMediaMusicPlayer alloc] _initWithPageContext:[self pageContext] player:[MPMusicPlayerController applicationMusicPlayer]];
}
return appMusicPlayer;
}
#endif
- (void)setAudioSessionCategory:(NSString *)mode
{
[[TiMediaAudioSession sharedSession] setSessionMode:mode];
}
- (NSString *)audioSessionCategory
{
return [[TiMediaAudioSession sharedSession] sessionMode];
}
- (NSNumber *)canRecord
{
return NUMBOOL([[TiMediaAudioSession sharedSession] hasInput]);
}
- (NSNumber *)volume
{
return NUMFLOAT([[TiMediaAudioSession sharedSession] volume]);
}
- (NSNumber *)audioPlaying
{
return NUMBOOL([[TiMediaAudioSession sharedSession] isAudioPlaying]);
}
- (NSDictionary *)currentRoute
{
return [[TiMediaAudioSession sharedSession] currentRoute];
}
- (void)setOverrideAudioRoute:(NSNumber *)mode
{
[[TiMediaAudioSession sharedSession] setRouteOverride:[mode unsignedIntValue]];
}
- (void)_listenerAdded:(NSString *)type count:(int)count
{
if (count == 1 && [type isEqualToString:@"routechange"]) {
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe
[[TiMediaAudioSession sharedSession] startAudioSession]; // Have to start a session to get a listener
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChanged:) name:kTiMediaAudioSessionRouteChange object:[TiMediaAudioSession sharedSession]];
} else if (count == 1 && [type isEqualToString:@"volume"]) {
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
[[TiMediaAudioSession sharedSession] startAudioSession]; // Have to start a session to get a listener
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioVolumeChanged:) name:kTiMediaAudioSessionVolumeChange object:[TiMediaAudioSession sharedSession]];
}
}
- (void)_listenerRemoved:(NSString *)type count:(int)count
{
if (count == 0 && [type isEqualToString:@"routechange"]) {
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
[[TiMediaAudioSession sharedSession] stopAudioSession];
[[NSNotificationCenter defaultCenter] removeObserver:self name:kTiMediaAudioSessionRouteChange object:[TiMediaAudioSession sharedSession]];
} else if (count == 0 && [type isEqualToString:@"volume"]) {
WARN_IF_BACKGROUND_THREAD_OBJ; //NSNotificationCenter is not threadsafe!
[[TiMediaAudioSession sharedSession] stopAudioSession];
[[NSNotificationCenter defaultCenter] removeObserver:self name:kTiMediaAudioSessionVolumeChange object:[TiMediaAudioSession sharedSession]];
}
}
#pragma mark Event Listener Management
- (void)audioRouteChanged:(NSNotification *)note
{
NSDictionary *event = [note userInfo];
[self fireEvent:@"routechange" withObject:event];
}
- (void)audioVolumeChanged:(NSNotification *)note
{
NSDictionary *userInfo = [note userInfo];
if (userInfo != nil) {
[self fireEvent:@"volume" withObject:userInfo];
} else {
NSMutableDictionary *event = [NSMutableDictionary dictionary];
[event setObject:[self volume] forKey:@"volume"];
[self fireEvent:@"volume" withObject:event];
}
}
#if defined(USE_TI_MEDIAAVAILABLECAMERAMEDIATYPES) || defined(USE_TI_MEDIAISMEDIATYPESUPPORTED)
- (NSArray *)availableCameraMediaTypes
{
NSArray *mediaSourceTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
return mediaSourceTypes == nil ? [NSArray arrayWithObject:(NSString *)kUTTypeImage] : mediaSourceTypes;
}
#endif
#if defined(USE_TI_MEDIAAVAILABLEPHOTOMEDIATYPES) || defined(USE_TI_MEDIAISMEDIATYPESUPPORTED)
- (NSArray *)availablePhotoMediaTypes
{
NSArray *photoSourceTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
return photoSourceTypes == nil ? [NSArray arrayWithObject:(NSString *)kUTTypeImage] : photoSourceTypes;
}
#endif
#if defined(USE_TI_MEDIAAVAILABLEPHOTOGALLERYMEDIATYPES) || defined(USE_TI_MEDIAISMEDIATYPESUPPORTED)
- (NSArray *)availablePhotoGalleryMediaTypes
{
NSArray *albumSourceTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
return albumSourceTypes == nil ? [NSArray arrayWithObject:(NSString *)kUTTypeImage] : albumSourceTypes;
}
#endif
#if defined(USE_TI_MEDIAAVAILABLECAMERAS)
- (NSArray *)availableCameras
{
NSMutableArray *types = [NSMutableArray arrayWithCapacity:2];
if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
[types addObject:NUMINT(UIImagePickerControllerCameraDeviceFront)];
}
if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
[types addObject:NUMINT(UIImagePickerControllerCameraDeviceRear)];
}
return types;
}
#endif
#ifdef USE_TI_MEDIACAMERAFLASHMODE
- (id)cameraFlashMode
{
if (picker != nil) {
return NUMINT([picker cameraFlashMode]);
}
return NUMINT(UIImagePickerControllerCameraFlashModeAuto);
}
- (void)setCameraFlashMode:(id)args
{
// Return nothing
ENSURE_SINGLE_ARG(args, NSNumber);
ENSURE_UI_THREAD(setCameraFlashMode, args);
if (picker != nil) {
[picker setCameraFlashMode:[TiUtils intValue:args]];
}
}
#endif
#ifdef USE_TI_MEDIAISCAMERASUPPORTED
- (NSNumber *)isCameraSupported
{
return NUMBOOL([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]);
}
#endif
#if defined(USE_TI_MEDIACAMERAAUTHORIZATION)
- (NSNumber *)cameraAuthorization
{
return NUMINTEGER([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]);
}
#endif
#pragma mark Public Methods
#if defined(USE_TI_MEDIABEEP) || defined(USE_TI_MEDIAVIBRATE)
- (void)beep:(id)unused
{
ENSURE_UI_THREAD(beep, unused);
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
}
- (void)vibrate:(id)args
{
//No pattern support on iOS
[self beep:nil];
}
#endif
/**
Microphone And Recording Support. These make no sense here and should be moved to Audiorecorder
**/
#if defined(USE_TI_MEDIAHASAUDIORECORDERPERMISSIONS) || defined(USE_TI_MEDIASTARTMICROPHONEMONITOR) || defined(USE_TI_MEDIASTOPMICROPHONEMONITOR) || defined(USE_TI_MEDIAPEAKMICROPHONEPOWER) || defined(USE_TI_MEDIAGETPEAKMICROPHONEPOWER) || defined(USE_TI_MEDIAAVERAGEMICROPHONEPOWER) || defined(USE_TI_MEDIAGETAVERAGEMICROPHONEPOWER)
- (id)hasAudioRecorderPermissions:(id)unused
{
NSString *microphonePermission = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSMicrophoneUsageDescription"];
if (!microphonePermission) {
NSLog(@"[ERROR] iOS 10 and later requires the key \"NSMicrophoneUsageDescription\" inside the plist in your tiapp.xml when accessing the native microphone. Please add the key and re-run the application.");
}
return NUMBOOL([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio] == AVAuthorizationStatusAuthorized);
}
#endif
#if defined(USE_TI_MEDIAREQUESTAUDIORECORDERPERMISSIONS)
- (void)requestAudioRecorderPermissions:(id)args
{
ENSURE_SINGLE_ARG(args, KrollCallback);
KrollCallback *callback = args;
TiThreadPerformOnMainThread(
^() {
[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
KrollEvent *invocationEvent = [[KrollEvent alloc] initWithCallback:callback
eventObject:[TiUtils dictionaryWithCode:(granted ? 0 : 1) message:nil]
thisObject:self];
[[callback context] enqueue:invocationEvent];
RELEASE_TO_NIL(invocationEvent);
}];
},
NO);
}
#endif
#if defined(USE_TI_MEDIASTARTMICROPHONEMONITOR) || defined(USE_TI_MEDIASTOPMICROPHONEMONITOR) || defined(USE_TI_MEDIAPEAKMICROPHONEPOWER) || defined(USE_TI_MEDIAGETPEAKMICROPHONEPOWER) || defined(USE_TI_MEDIAAVERAGEMICROPHONEPOWER) || defined(USE_TI_MEDIAGETAVERAGEMICROPHONEPOWER)
- (void)startMicrophoneMonitor:(id)args
{
if (_microphoneRecorder != nil) {
DebugLog(@"[ERROR] Trying to start new microphone monitoring while the old one is still active. Call \"stopMicrophoneMonitor()\" before and try again.");
return;
}
if (![TiUtils boolValue:[self hasAudioRecorderPermissions:nil]]) {
DebugLog(@"[ERROR] Microphone permissions are required to use the microphone monitoring API.");
}
NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:44100.0], AVSampleRateKey,
[NSNumber numberWithInt:kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt:1], AVNumberOfChannelsKey,
[NSNumber numberWithInt:AVAudioQualityMax], AVEncoderAudioQualityKey,
nil];
NSError *error;
_microphoneRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
if (_microphoneRecorder == nil) {
DebugLog(@"[ERROR] Error starting audio monitoring: %@", [error description]);
return;
}
[_microphoneRecorder prepareToRecord];
_microphoneRecorder.meteringEnabled = YES;
[_microphoneRecorder record];
_microphoneTimer = [NSTimer scheduledTimerWithTimeInterval:0.03
target:self
selector:@selector(_microphoneTimerChanged:)
userInfo:nil
repeats:YES];
}
- (void)_microphoneTimerChanged:(NSTimer *)timer
{
[_microphoneRecorder updateMeters];
}
- (void)stopMicrophoneMonitor:(id)args
{
if (_microphoneRecorder == nil) {
DebugLog(@"[ERROR] Trying to stop microphone monitoring which is not active. Call \"startMicrophoneMonitor()\" before and try again.");
return;
}
[_microphoneRecorder stop];
[_microphoneTimer invalidate];
_microphoneTimer = nil;
RELEASE_TO_NIL(_microphoneRecorder);
}
- (NSNumber *)peakMicrophonePower
{
if (_microphoneRecorder != nil && [_microphoneRecorder isRecording]) {
return @([_microphoneRecorder peakPowerForChannel:0]);
}
return @(-1);
}
- (NSNumber *)averageMicrophonePower
{
if (_microphoneRecorder != nil && [_microphoneRecorder isRecording]) {
return @([_microphoneRecorder averagePowerForChannel:0]);
}
return @(-1);
}
#endif
/**
End Microphone and Recording Support
**/
#ifdef USE_TI_MEDIAISMEDIATYPESUPPORTED
- (NSNumber *)isMediaTypeSupported:(id)args
{
ENSURE_ARG_COUNT(args, 2);
NSString *media = [[TiUtils stringValue:[args objectAtIndex:0]] lowercaseString];
NSString *type = [[TiUtils stringValue:[args objectAtIndex:1]] lowercaseString];
NSArray *array = nil;
if ([media isEqualToString:@"camera"]) {
array = [self availableCameraMediaTypes];
} else if ([media isEqualToString:@"photo"]) {
array = [self availablePhotoMediaTypes];
} else if ([media isEqualToString:@"photogallery"]) {
array = [self availablePhotoGalleryMediaTypes];
}
if (array != nil) {
for (NSString *atype in array) {
if ([[atype lowercaseString] isEqualToString:type]) {
return NUMBOOL(YES);
}
}
}
return NUMBOOL(NO);
}
#endif
- (void)takeScreenshot:(id)arg
{
ENSURE_SINGLE_ARG(arg, KrollCallback);
ENSURE_UI_THREAD(takeScreenshot, arg);
// Create a graphics context with the target size
CGSize imageSize = [[UIScreen mainScreen] bounds].size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Iterate over every window from back to front
for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
// -renderInContext: renders in the coordinate space of the layer,
// so we must first apply the layer's geometry to the graphics context
CGContextSaveGState(context);
// Center the context around the window's anchor point
CGContextTranslateCTM(context, [window center].x, [window center].y);
// Apply the window's transform about the anchor point
CGContextConcatCTM(context, [window transform]);
// Offset by the portion of the bounds left of and above the anchor point
CGContextTranslateCTM(context,
-[window bounds].size.width * [[window layer] anchorPoint].x,
-[window bounds].size.height * [[window layer] anchorPoint].y);
// Render the layer hierarchy to the current context
if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
[window drawViewHierarchyInRect:[window bounds] afterScreenUpdates:NO];
} else {
[[window layer] renderInContext:context];
}
// Restore the context
CGContextRestoreGState(context);
}
}
// Retrieve the screenshot image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
TiBlob *blob = [[[TiBlob alloc] initWithImage:image] autorelease];
NSDictionary *event = [NSDictionary dictionaryWithObject:blob forKey:@"media"];
[self _fireEventToListener:@"screenshot" withObject:event listener:arg thisObject:nil];
}
#ifdef USE_TI_MEDIASAVETOPHOTOGALLERY
- (void)saveToPhotoGallery:(id)arg
{
ENSURE_UI_THREAD(saveToPhotoGallery, arg);
NSObject *image = [arg objectAtIndex:0];
ENSURE_TYPE(image, NSObject);
NSDictionary *saveCallbacks = nil;
if ([arg count] > 1) {
saveCallbacks = [arg objectAtIndex:1];
ENSURE_TYPE(saveCallbacks, NSDictionary);
KrollCallback *successCallback = [saveCallbacks valueForKey:@"success"];
ENSURE_TYPE_OR_NIL(successCallback, KrollCallback);
KrollCallback *errorCallback = [saveCallbacks valueForKey:@"error"];
ENSURE_TYPE_OR_NIL(errorCallback, KrollCallback);
}
if ([image isKindOfClass:[TiBlob class]]) {
TiBlob *blob = (TiBlob *)image;
NSString *mime = [blob mimeType];
if (mime == nil || [mime hasPrefix:@"image/"]) {
UIImage *savedImage = [blob image];
if (savedImage == nil)
return;
UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(saveCompletedForImage:error:contextInfo:), [saveCallbacks retain]);
} else if ([mime hasPrefix:@"video/"]) {
NSString *filePath;
switch ([blob type]) {
case TiBlobTypeFile: {
filePath = [blob path];
break;
}
case TiBlobTypeData: {
// In this case, we need to write the blob data to a /tmp file and then load it.
NSArray *typeinfo = [mime componentsSeparatedByString:@"/"];
TiFile *tempFile = [TiUtils createTempFile:[typeinfo objectAtIndex:1]];
filePath = [tempFile path];
NSError *error = nil;
[blob writeTo:filePath error:&error];
if (error != nil) {
NSString *message = [NSString stringWithFormat:@"problem writing to temporary file %@: %@", filePath, [TiUtils messageFromError:error]];
NSMutableDictionary *event = [TiUtils dictionaryWithCode:[error code] message:message];
[self dispatchCallback:[NSArray arrayWithObjects:@"error", event, [saveCallbacks valueForKey:@"error"], nil]];
return;
}
// Have to keep the temp file from being deleted when we leave scope, so add it to the userinfo so it can be cleaned up there
[saveCallbacks setValue:tempFile forKey:@"tempFile"];
break;
}
default: {
NSMutableDictionary *event = [TiUtils dictionaryWithCode:-1 message:@"invalid media format: MIME type was video/, but data is image"];
[self dispatchCallback:[NSArray arrayWithObjects:@"error", event, [saveCallbacks valueForKey:@"error"], nil]];
return;
}
}
UISaveVideoAtPathToSavedPhotosAlbum(filePath, self, @selector(saveCompletedForVideo:error:contextInfo:), [saveCallbacks retain]);
} else {
KrollCallback *errorCallback = [saveCallbacks valueForKey:@"error"];
if (errorCallback != nil) {
NSMutableDictionary *event = [TiUtils dictionaryWithCode:-1 message:[NSString stringWithFormat:@"Invalid mime type: Expected either image/* or video/*, was: %@", mime]];
[self dispatchCallback:[NSArray arrayWithObjects:@"error", event, errorCallback, nil]];
} else {
[self throwException:@"Invalid mime type"
subreason:[NSString stringWithFormat:@"Invalid mime type: Expected either image/* or video/*, was: %@", mime]
location:CODELOCATION];
}
}
} else if ([image isKindOfClass:[TiFile class]]) {
TiFile *file = (TiFile *)image;
NSString *mime = [Mimetypes mimeTypeForExtension:[file path]];
if (mime == nil || [mime hasPrefix:@"image/"]) {
NSData *data = [NSData dataWithContentsOfFile:[file path]];
UIImage *image = [[[UIImage alloc] initWithData:data] autorelease];
UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveCompletedForImage:error:contextInfo:), [saveCallbacks retain]);
} else if ([mime hasPrefix:@"video/"]) {
UISaveVideoAtPathToSavedPhotosAlbum([file path], self, @selector(saveCompletedForVideo:error:contextInfo:), [saveCallbacks retain]);
}
} else {
KrollCallback *errorCallback = [saveCallbacks valueForKey:@"error"];
if (errorCallback != nil) {
NSMutableDictionary *event = [TiUtils dictionaryWithCode:-1 message:[NSString stringWithFormat:@"Invalid media type: Expected either TiBlob or TiFile, was: %@", JavascriptNameForClass([image class])]];
[self dispatchCallback:[NSArray arrayWithObjects:@"error", event, errorCallback, nil]];
} else {
[self throwException:@"Invalid media type"
subreason:[NSString stringWithFormat:@"Expected either TiBlob or TiFile, was: %@", JavascriptNameForClass([image class])]
location:CODELOCATION];
}
}
}
#endif
/**
Camera & Video Capture methods
**/
#ifdef USE_TI_MEDIASHOWCAMERA
- (void)showCamera:(id)args
{
ENSURE_SINGLE_ARG_OR_NIL(args, NSDictionary);
if (![NSThread isMainThread]) {
TiThreadPerformOnMainThread(
^{
[self showCamera:args];
},
NO);
return;
}
[self rememberProxy:[args objectForKey:@"overlay"]];
[self showPicker:args isCamera:YES];
}
#endif
#ifdef USE_TI_MEDIAHIDECAMERA
- (void)hideCamera:(id)args
{
[self destroyPickerCallbacks];
//Hopefully, if we remove the callbacks before going to the main thread, we may reduce deadlock.
ENSURE_UI_THREAD(hideCamera, args);
if (picker != nil) {
if (cameraView != nil) {
[cameraView windowWillClose];
}
[[TiApp app] hideModalController:picker animated:animatedPicker];
[[TiApp controller] repositionSubviews];
if (cameraView != nil) {
[cameraView windowDidClose];
[self forgetProxy:cameraView];
RELEASE_TO_NIL(cameraView);
}
[self destroyPicker];
}
}
#endif
#ifdef USE_TI_MEDIATAKEPICTURE
- (void)takePicture:(id)args
{
// must have a picker, doh
if (picker == nil) {
[self throwException:@"invalid state" subreason:nil location:CODELOCATION];
}
ENSURE_UI_THREAD(takePicture, args);
[picker takePicture];
}
#endif
#ifdef USE_TI_MEDIASTARTVIDEOCAPTURE
- (void)startVideoCapture:(id)args
{
// Return nothing
ENSURE_UI_THREAD(startVideoCapture, args);
// must have a picker, doh
if (picker == nil) {
[self throwException:@"invalid state" subreason:nil location:CODELOCATION];
}
[picker startVideoCapture];
}
#endif
#ifdef USE_TI_MEDIASTOPVIDEOCAPTURE
- (void)stopVideoCapture:(id)args
{
ENSURE_UI_THREAD(stopVideoCapture, args);
// must have a picker, doh
if (picker != nil) {
[picker stopVideoCapture];
}
}
#endif
#ifdef USE_TI_MEDIASWITCHCAMERA
- (void)switchCamera:(id)args
{
ENSURE_TYPE(args, NSArray);
ENSURE_UI_THREAD(switchCamera, args);
// TIMOB-17951
if ([args objectAtIndex:0] == [NSNull null]) {
return;
}
ENSURE_SINGLE_ARG(args, NSNumber);
ENSURE_UI_THREAD(switchCamera, args);
// must have a picker, doh
if (picker == nil) {
[self throwException:@"invalid state" subreason:nil location:CODELOCATION];
}
[picker setCameraDevice:[TiUtils intValue:args]];
}
#endif
//Undocumented property
#ifdef USE_TI_MEDIASHOWCAMERA
- (id)camera
{
if (picker != nil) {
return NUMINT([picker cameraDevice]);
}
return NUMINT(UIImagePickerControllerCameraDeviceRear);
}
#endif
#if defined(USE_TI_MEDIAREQUESTCAMERAPERMISSIONS)
//request camera access. for >= IOS7
- (void)requestCameraPermissions:(id)arg
{
ENSURE_SINGLE_ARG(arg, KrollCallback);
KrollCallback *callback = arg;
TiThreadPerformOnMainThread(
^() {
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
completionHandler:^(BOOL granted) {
NSString *errorMessage = granted ? nil : @"The user denied access to use the camera.";
KrollEvent *invocationEvent = [[KrollEvent alloc] initWithCallback:callback
eventObject:[TiUtils dictionaryWithCode:(granted ? 0 : 1) message:errorMessage]
thisObject:self];