This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
/
camera.js
1471 lines (1256 loc) · 45.6 KB
/
camera.js
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
'use strict';
var loader = LazyLoader;
// Utility functions
function padLeft(num, length) {
var r = String(num);
while (r.length < length) {
r = '0' + r;
}
return r;
}
// This handles the logic pertaining to the naming of files according
// to the Design rule for Camera File System
// * http://en.wikipedia.org/wiki/Design_rule_for_Camera_File_system
var DCFApi = (function() {
var api = {};
var dcfConfigLoaded = false;
var deferredArgs = null;
var defaultSeq = {file: 1, dir: 100};
var dcfConfig = {
key: 'dcf_key',
seq: null,
postFix: 'MZLLA',
prefix: {video: 'VID_', image: 'IMG_'},
ext: {video: '3gp', image: 'jpg'}
};
api.init = function() {
asyncStorage.getItem(dcfConfig.key, function(value) {
dcfConfigLoaded = true;
dcfConfig.seq = value ? value : defaultSeq;
// We have a previous call to createDCFFilename that is waiting for
// a response, fire it again
if (deferredArgs) {
var args = deferredArgs;
api.createDCFFilename(args.storage, args.type, args.callback);
deferredArgs = null;
}
});
};
api.createDCFFilename = function(storage, type, callback) {
// We havent loaded the current counters from indexedDB yet, defer
// the call
if (!dcfConfigLoaded) {
deferredArgs = {storage: storage, type: type, callback: callback};
return;
}
var filepath = 'DCIM/' + dcfConfig.seq.dir + dcfConfig.postFix + '/';
var filename = dcfConfig.prefix[type] +
padLeft(dcfConfig.seq.file, 4) + '.' +
dcfConfig.ext[type];
// A file with this name may have been written by the user or
// our indexeddb sequence tracker was cleared, check we wont overwrite
// anything
var req = storage.get(filepath + filename);
// A file existed, we bump the directory then try to generate a
// new filename
req.onsuccess = function() {
dcfConfig.seq.file = 1;
dcfConfig.seq.dir += 1;
asyncStorage.setItem(dcfConfig.key, dcfConfig.seq, function() {
api.createDCFFilename(storage, type, callback);
});
};
// No file existed, we are good to go
req.onerror = function() {
if (dcfConfig.seq.file < 9999) {
dcfConfig.seq.file += 1;
} else {
dcfConfig.seq.file = 1;
dcfConfig.seq.dir += 1;
}
asyncStorage.setItem(dcfConfig.key, dcfConfig.seq, function() {
callback(filepath, filename);
});
};
};
return api;
})();
var screenLock = null;
var returnToCamera = true;
var Camera = {
_initialised: false,
_cameras: null,
_cameraNumber: 0,
_captureMode: null,
_recording: false,
// In secure mode the user cannot browse to the gallery
_secureMode: window.parent !== window,
_currentOverlay: null,
CAMERA: 'camera',
VIDEO: 'video',
_videoTimer: null,
_videoStart: null,
_videoPath: null, // file path relative to video root directory
_videoRootDir: null, // video root directory string
_autoFocusSupported: 0,
_manuallyFocused: false,
_timeoutId: 0,
_cameraObj: null,
_photosTaken: [],
_cameraProfile: null,
_resumeViewfinderTimer: null,
_styleSheet: document.styleSheets[0],
_orientationRule: null,
_phoneOrientation: 0,
_pictureStorage: null,
_videoStorage: null,
_storageState: null,
STORAGE_INIT: 0,
STORAGE_AVAILABLE: 1,
STORAGE_NOCARD: 2,
STORAGE_UNMOUNTED: 3,
STORAGE_CAPACITY: 4,
_pictureSize: null,
_previewConfig: null,
_previewPaused: false,
_previewActive: false,
PREVIEW_PAUSE: 500,
// We can recieve multiple FileSizeLimitReached events
// when recording, since we stop recording on this event
// only show one alert per recording
_sizeLimitAlertActive: false,
FILMSTRIP_DURATION: 5000, // show filmstrip for 5s before fading
_flashState: {
camera: {
supported: false,
modes: ['off', 'auto', 'on'],
currentMode: 1 // default flash mode is 'auto'
},
video: {
supported: false,
modes: ['off', 'torch'],
currentMode: 0
}
},
_config: {
fileFormat: 'jpeg'
},
_videoProfile: {},
preferredRecordingSizes: null,
_shutterKey: 'camera.shutter.enabled',
_shutterSound: null,
_shutterSoundEnabled: true,
PROMPT_DELAY: 2000,
_watchId: null,
_position: null,
_pendingPick: null,
_savedMedia: null,
// The minimum available disk space to start recording a video.
RECORD_SPACE_MIN: 1024 * 1024 * 2,
// Number of bytes left on disk to let us stop recording.
RECORD_SPACE_PADDING: 1024 * 1024 * 1,
// An estimated JPEG file size is caluclated from 90% quality 24bit/pixel
ESTIMATED_JPEG_FILE_SIZE: 300 * 1024,
get overlayTitle() {
return document.getElementById('overlay-title');
},
get overlayText() {
return document.getElementById('overlay-text');
},
get overlay() {
return document.getElementById('overlay');
},
get viewfinder() {
return document.getElementById('viewfinder');
},
get switchButton() {
return document.getElementById('switch-button');
},
get captureButton() {
return document.getElementById('capture-button');
},
get galleryButton() {
return document.getElementById('gallery-button');
},
get videoTimer() {
return document.getElementById('video-timer');
},
get focusRing() {
return document.getElementById('focus-ring');
},
get toggleButton() {
return document.getElementById('toggle-camera');
},
get toggleFlashBtn() {
return document.getElementById('toggle-flash');
},
get cancelPickButton() {
return document.getElementById('cancel-pick');
},
get overlayCloseButton() {
return document.getElementById('overlay-close-button');
},
get overlayMenuGroup() {
return document.getElementById('overlay-menu-group');
},
// We have seperated init and delayedInit as we want to make sure
// that on first launch we dont interfere and load the camera
// previewStream as fast as possible, once the previewStream is
// active we do the rest of the initialisation.
init: function() {
// We dont want to initialise until we know what type of activity
// we are handling
var hasMessage = navigator.mozHasPendingMessage('activity');
navigator.mozSetMessageHandler('activity', this.handleActivity.bind(this));
if (hasMessage) {
return;
}
// The activity may have defined a captureMode, otherwise
// be default we use the camera
if (this._captureMode === null) {
this.setCaptureMode(this.CAMERA);
}
this.loadCameraPreview(this._cameraNumber, function() {
var files = [
'style/filmstrip.css',
'style/confirm.css',
'style/VideoPlayer.css',
'/shared/js/async_storage.js',
'/shared/js/blobview.js',
'/shared/js/media/jpeg_metadata_parser.js',
'/shared/js/media/get_video_rotation.js',
'/shared/js/media/video_player.js',
'/shared/js/media/media_frame.js',
'/shared/js/gesture_detector.js',
'js/panzoom.js',
'js/filmstrip.js',
'js/confirm.js'
];
loader.load(files, function() {
Camera.delayedInit();
});
});
},
delayedInit: function camera_delayedInit() {
if (!this._pendingPick) {
this.galleryButton.classList.remove('hidden');
this.switchButton.classList.remove('hidden');
}
this.enableButtons();
// Dont let the phone go to sleep while the camera is
// active, user must manually close it
this.screenWakeLock();
this.setToggleCameraStyle();
// We lock the screen orientation and deal with rotating
// the icons manually
var css = '#switch-button span, #capture-button span, #toggle-flash, ' +
'#toggle-camera, #gallery-button span { -moz-transform: rotate(0deg); }';
var insertId = this._styleSheet.cssRules.length - 1;
this._orientationRule = this._styleSheet.insertRule(css, insertId);
window.addEventListener('deviceorientation', this.orientChange.bind(this));
this.toggleButton.addEventListener('click', this.toggleCamera.bind(this));
this.toggleFlashBtn.addEventListener('click', this.toggleFlash.bind(this));
this.viewfinder.addEventListener('click', this.toggleFilmStrip.bind(this));
this.switchButton
.addEventListener('click', this.toggleModePressed.bind(this));
this.captureButton
.addEventListener('click', this.capturePressed.bind(this));
this.galleryButton
.addEventListener('click', this.galleryBtnPressed.bind(this));
this.cancelPickButton
.addEventListener('click', this.cancelPick.bind(this));
this.overlayCloseButton
.addEventListener('click', this.cancelPick.bind(this));
if (!navigator.mozCameras) {
this.captureButton.setAttribute('disabled', 'disabled');
return;
}
if (this._secureMode) {
this.galleryButton.setAttribute('disabled', 'disabled');
}
this._shutterSound = new Audio('./resources/sounds/shutter.ogg');
this._shutterSound.mozAudioChannelType = 'notification';
if ('mozSettings' in navigator) {
var req = navigator.mozSettings.createLock().get(this._shutterKey);
req.onsuccess = (function onsuccess() {
this._shutterSoundEnabled = req.result[this._shutterKey];
}).bind(this);
navigator.mozSettings.addObserver(this._shutterKey, (function(e) {
this._shutterSoundEnabled = e.settingValue;
}).bind(this));
this.getPreferredSizes();
}
this._storageState = this.STORAGE_INIT;
this._pictureStorage = navigator.getDeviceStorage('pictures');
this._videoStorage = navigator.getDeviceStorage('videos'),
this._pictureStorage
.addEventListener('change', this.deviceStorageChangeHandler.bind(this));
this.checkStorageSpace();
this.previewEnabled();
this._initialised = true;
DCFApi.init();
},
handleActivity: function camera_handleActivity(activity) {
// default to allow both photos and videos
var types = activity.source.data.type || ['image/*', 'video/*'];
var mode = this.CAMERA;
if (activity.source.name === 'pick') {
// When inside an activity the user cannot switch between
// the gallery or video recording.
this._pendingPick = activity;
// Hide the gallery and switch buttons, leaving only the shutter
this.galleryButton.classList.add('hidden');
this.switchButton.classList.add('hidden');
// Display the cancel button, and make sure it's enabled
this.cancelPickButton.classList.remove('hidden');
this.cancelPickButton.removeAttribute('disabled');
if (typeof types === 'string') {
types = [types];
}
var allowedTypes = { 'image': false, 'video': false};
types.forEach(function(type) {
var typePrefix = type.split('/')[0];
allowedTypes[typePrefix] = true;
});
if (allowedTypes.image && allowedTypes.video) {
this.switchButton.classList.remove('hidden');
this.switchButton.removeAttribute('disabled');
} else if (allowedTypes.video) {
mode = this.VIDEO;
}
} else { // record
if (types === 'videos') {
mode = this.VIDEO;
}
}
if (!this._initialised) {
this.setCaptureMode(mode);
this.init();
} else if (this._captureMode !== mode) {
// I dont think it is currently possible to get a pick activity
// with an initialised camera, but it may be in the future
this.changeMode(mode);
}
},
screenTimeout: function camera_screenTimeout() {
if (screenLock && !returnToCamera) {
screenLock.unlock();
screenLock = null;
}
},
screenWakeLock: function camera_screenWakeLock() {
if (!screenLock && returnToCamera) {
screenLock = navigator.requestWakeLock('screen');
}
},
setReturnToCamera: function camera_setReturnToCamera() {
returnToCamera = true;
},
resetReturnToCamera: function camera_resetReturnToCamera() {
returnToCamera = false;
},
enableButtons: function camera_enableButtons() {
this.captureButton.removeAttribute('disabled');
this.switchButton.removeAttribute('disabled');
if (this._pendingPick) {
this.cancelPickButton.removeAttribute('disabled', 'disabled');
}
},
disableButtons: function camera_disableButtons() {
this.switchButton.setAttribute('disabled', 'disabled');
this.captureButton.setAttribute('disabled', 'disabled');
if (this._pendingPick) {
this.cancelPickButton.setAttribute('disabled', 'disabled');
}
},
cancelPick: function camera_cancelPick() {
if (this._pendingPick) {
this._pendingPick.postError('pick cancelled');
}
this._pendingPick = null;
},
toggleModePressed: function camera_toggleCaptureMode(e) {
if (e.target.getAttribute('disabled')) {
return;
}
var newMode = (this._captureMode === this.CAMERA) ?
this.VIDEO : this.CAMERA;
this.changeMode(newMode);
},
changeMode: function(mode) {
this.disableButtons();
this.setCaptureMode(mode);
this.updateFlashUI();
function gotPreviewStream(stream) {
this.viewfinder.mozSrcObject = stream;
this.viewfinder.play();
}
Camera._cameraObj.onPreviewStateChange = function(state) {
// We disabled the buttons above. Now we wait for the preview
// stream to actually start up before we enable them again. If we
// do this in the getPreviewStream() callback it might be too early
// and we can still cause deadlock in the camera hardware.
// See Bug 890427.
if (state === 'started') {
Camera.enableButtons();
// Only do this once
Camera._cameraObj.onPreviewStateChange = null;
}
};
if (this._captureMode === this.CAMERA) {
this._cameraObj.getPreviewStream(this._previewConfig,
gotPreviewStream.bind(this));
} else {
this._videoProfile.rotation = this._phoneOrientation;
this._cameraObj.getPreviewStreamVideoMode(this._videoProfile,
gotPreviewStream.bind(this));
}
},
toggleCamera: function camera_toggleCamera() {
this._cameraNumber = 1 - this._cameraNumber;
// Disable the buttons so the user can't use them while we're switching.
this.disableButtons();
this.loadCameraPreview(this._cameraNumber, this.enableButtons.bind(this));
this.setToggleCameraStyle();
},
setToggleCameraStyle: function camera_setToggleCameraStyle() {
var modeName = this._cameraNumber === 0 ? 'back' : 'front';
this.toggleButton.setAttribute('data-mode', modeName);
},
updateFlashUI: function camera_updateFlashUI() {
var flash = this._flashState[this._captureMode];
if (flash.supported) {
this.setFlashMode();
this.toggleFlashBtn.classList.remove('hidden');
} else {
this.toggleFlashBtn.classList.add('hidden');
}
},
toggleFlash: function camera_toggleFlash() {
var flash = this._flashState[this._captureMode];
flash.currentMode = (flash.currentMode + 1) % flash.modes.length;
this.setFlashMode();
},
setFlashMode: function camera_setFlashMode() {
var flash = this._flashState[this._captureMode];
var flashModeName = flash.modes[flash.currentMode];
this.toggleFlashBtn.setAttribute('data-mode', flashModeName);
this._cameraObj.flashMode = flashModeName;
},
toggleRecording: function camera_toggleRecording() {
if (this._recording) {
this.stopRecording();
return;
}
// Hide the filmstrip to prevent the users from
// entering the preview mode after Camera starts recording button pressed
if (Filmstrip.isShown())
Filmstrip.hide();
this.startRecording();
},
startRecording: function camera_startRecording() {
this._sizeLimitAlertActive = false;
var captureButton = this.captureButton;
var switchButton = this.switchButton;
var onerror = function() {
handleError('error-recording');
};
var onsuccess = (function onsuccess() {
document.body.classList.add('capturing');
captureButton.removeAttribute('disabled');
this._recording = true;
this.startRecordingTimer();
// User closed app while recording was trying to start
if (document.mozHidden) {
this.stopRecording();
}
}).bind(this);
var handleError = (function handleError(id) {
this.enableButtons();
alert(navigator.mozL10n.get(id + '-title') + '. ' +
navigator.mozL10n.get(id + '-text'));
}).bind(this);
this.disableButtons();
var startRecording = (function startRecording(freeBytes) {
if (freeBytes < this.RECORD_SPACE_MIN) {
handleError('nospace');
return;
}
var config = {
rotation: this._phoneOrientation,
maxFileSizeBytes: freeBytes - this.RECORD_SPACE_PADDING
};
if (this._pendingPick && this._pendingPick.source.data.maxFileSizeBytes) {
var maxFileSizeBytes = this._pendingPick.source.data.maxFileSizeBytes;
config.maxFileSizeBytes = Math.min(config.maxFileSizeBytes,
maxFileSizeBytes);
}
this._cameraObj.startRecording(config,
this._videoStorage, this._videoPath,
onsuccess, onerror);
}).bind(this);
DCFApi.createDCFFilename(this._videoStorage,
'video',
(function(path, name) {
this._videoPath = path + name;
// The CameraControl API will not automatically create directories
// for the new file if they do not exist, so write a dummy file
// to the same directory via DeviceStorage to ensure that the directory
// exists before recording starts.
var dummyblob = new Blob([''], {type: 'video/3gpp'});
var dummyfilename = path + '.' + name;
var req = this._videoStorage.addNamed(dummyblob, dummyfilename);
req.onerror = onerror;
req.onsuccess = (function fileCreated(e) {
// Extract video root directory string
var absolutePath = e.target.result;
var rootDirLength = absolutePath.length - dummyfilename.length;
this._videoRootDir = absolutePath.substring(0, rootDirLength);
this._videoStorage.delete(absolutePath); // No need to wait for success
// Determine the number of bytes available on disk.
var spaceReq = this._videoStorage.freeSpace();
spaceReq.onerror = onerror;
spaceReq.onsuccess = function() {
startRecording(spaceReq.result);
};
}).bind(this);
}).bind(this));
},
startRecordingTimer: function camera_startRecordingTimer() {
this._videoStart = new Date().getTime();
this.videoTimer.textContent = this.formatTimer(0);
this._videoTimer =
window.setInterval(this.updateVideoTimer.bind(this), 1000);
},
updateVideoTimer: function camera_updateVideoTimer() {
var videoLength =
Math.round((new Date().getTime() - this._videoStart) / 1000);
this.videoTimer.textContent = this.formatTimer(videoLength);
},
stopRecording: function camera_stopRecording() {
var self = this;
this._cameraObj.stopRecording();
this._recording = false;
// Register a listener for writing completion of current video file
(function(videoStorage, videofile) {
videoStorage.addEventListener('change', function changeHandler(e) {
// Regard the modification as video file writing completion if e.path
// matches current video filename. Note e.path is absolute path.
if (e.reason === 'modified' && e.path === videofile) {
// Un-register the listener itself
videoStorage.removeEventListener('change', changeHandler);
// Now that the video file has been saved, save a poster
// image to match it. The Gallery app depends on this.
self.saveVideoPosterImage(videofile, function(video, poster, data) {
if (self._pendingPick) {
self._savedMedia = {
video: video,
poster: poster
};
ConfirmDialog.confirmVideo(video, poster,
data.width, data.height, data.rotation,
self.selectPressed.bind(self),
self.retakePressed.bind(self));
} else {
Filmstrip.addVideo(videofile, video, poster,
data.width, data.height, data.rotation);
Filmstrip.show(Camera.FILMSTRIP_DURATION);
}
});
}
});
})(this._videoStorage, this._videoRootDir + this._videoPath);
window.clearInterval(this._videoTimer);
this.enableButtons();
document.body.classList.remove('capturing');
},
saveVideoPosterImage: function saveVideoPosterImage(filename, callback) {
// Given the filename of a newly recorded video, create a poster
// image for it, and save that poster as a jpeg file. When done,
// pass the video blob and the poster blob to the callback function
// along with the video dimensions and rotation.
var getreq = this._videoStorage.get(filename);
getreq.onerror = function() {
console.warn('saveVideoPosterImage:', filename, request.error.name);
};
getreq.onsuccess = function() {
var videoblob = getreq.result;
getVideoRotation(videoblob, function(rotation) {
if (typeof rotation !== 'number') {
console.warn('Unexpected rotation:', rotation);
rotation = 0;
}
var offscreenVideo = document.createElement('video');
var url = URL.createObjectURL(videoblob);
offscreenVideo.preload = 'metadata';
offscreenVideo.src = url;
offscreenVideo.onerror = function() {
URL.revokeObjectURL(url);
offscreenVideo.removeAttribute('src');
offscreenVideo.load();
console.warn('not a video file', filename);
};
offscreenVideo.onloadedmetadata = function() {
var videowidth = offscreenVideo.videoWidth;
var videoheight = offscreenVideo.videoHeight;
// First, create a full-size unrotated poster image
var postercanvas = document.createElement('canvas');
var postercontext = postercanvas.getContext('2d');
postercanvas.width = videowidth;
postercanvas.height = videoheight;
postercontext.drawImage(offscreenVideo, 0, 0);
// We're done with the offscreen video element now
URL.revokeObjectURL(url);
offscreenVideo.removeAttribute('src');
offscreenVideo.load();
// Save the poster image to storage, then call the callback
// The Gallery app depends on this poster image being saved here
postercanvas.toBlob(function savePoster(poster) {
var posterfile = filename.replace('.3gp', '.jpg');
Camera._pictureStorage.addNamed(poster, posterfile);
callback(videoblob, poster, {
width: videowidth,
height: videoheight,
rotation: rotation
});
}, 'image/jpeg');
};
});
};
},
formatTimer: function camera_formatTimer(time) {
var minutes = Math.floor(time / 60);
var seconds = Math.round(time % 60);
if (minutes < 60) {
return padLeft(minutes, 2) + ':' + padLeft(seconds, 2);
} else {
var hours = Math.floor(minutes / 60);
minutes = Math.round(minutes % 60);
return hours + ':' + padLeft(minutes, 2) + ':' + padLeft(seconds, 2);
}
return '';
},
capturePressed: function camera_doCapture(e) {
if (e.target.getAttribute('disabled')) {
return;
}
if (this._captureMode === this.CAMERA) {
this.prepareTakePicture();
} else {
this.toggleRecording();
}
},
galleryBtnPressed: function camera_galleryBtnPressed() {
// Can't launch the gallery if the lockscreen is locked.
// The button shouldn't even be visible in this case, but
// let's be really sure here.
if (this._secureMode)
return;
// Launch the gallery with an activity
var a = new MozActivity({
name: 'browse',
data: {
type: 'photos'
}
});
},
orientChange: function camera_orientChange(e) {
// Orientation is 0 starting at 'natural portrait' increasing
// going clockwise
var orientation = (e.beta > 45) ? 180 :
(e.beta < -45) ? 0 :
(e.gamma < -45) ? 90 :
(e.gamma > 45) ? 270 : 0;
if (orientation !== this._phoneOrientation) {
var rule = this._styleSheet.cssRules[this._orientationRule];
// PLEASE DO SOMETHING KITTENS ARE DYING
// Setting MozRotate to 90 or 270 causes element to disappear
rule.style.MozTransform = 'rotate(' + -(orientation + 1) + 'deg)';
this._phoneOrientation = orientation;
Filmstrip.setOrientation(orientation);
}
},
setCaptureMode: function camera_setCaptureMode(mode) {
if (this._captureMode) {
document.body.classList.remove(this._captureMode);
}
this._captureMode = mode;
document.body.classList.add(mode);
},
toggleFilmStrip: function camera_toggleFilmStrip(ev) {
// We will just ignore
// because the filmstrip shouldn't be shown
// while Camera is recording
if (this._recording || this._pendingPick)
return;
if (Filmstrip.isShown())
Filmstrip.hide();
else
Filmstrip.show();
},
loadCameraPreview: function camera_loadCameraPreview(cameraNumber, callback) {
this.viewfinder.mozSrcObject = null;
this._timeoutId = 0;
this._cameras = navigator.mozCameras.getListOfCameras();
var options = {camera: this._cameras[cameraNumber]};
function gotPreviewScreen(stream) {
this.viewfinder.mozSrcObject = stream;
this.viewfinder.play();
this._previewActive = true;
if (callback) {
// Even though we have the stream now, the camera hardware hasn't
// started displaying it yet. We need to wait until the preview
// has actually started displaying before calling the callback.
// See Bug 890427.
Camera._cameraObj.onPreviewStateChange = function(state) {
if (state === 'started') {
Camera._cameraObj.onPreviewStateChange = null;
callback();
}
};
}
}
function gotCamera(camera) {
this._cameraObj = camera;
this._autoFocusSupported =
camera.capabilities.focusModes.indexOf('auto') !== -1;
this._pictureSize =
this.pickPictureSize(camera.capabilities.pictureSizes);
this.getPreferredSizes((function() {
this._videoProfile =
this.pickVideoProfile(camera.capabilities.recorderProfiles);
if (this._captureMode === this.VIDEO) {
this._videoProfile.rotation = this._phoneOrientation;
this._cameraObj.getPreviewStreamVideoMode(
this._videoProfile, gotPreviewScreen.bind(this));
}
}).bind(this));
this.setPreviewSize(camera);
this.enableCameraFeatures(camera.capabilities);
camera.onShutter = (function() {
if (this._shutterSoundEnabled) {
this._shutterSound.play();
}
}).bind(this);
camera.onRecorderStateChange = this.recordingStateChanged.bind(this);
if (this._captureMode === this.CAMERA) {
camera.getPreviewStream(this._previewConfig,
gotPreviewScreen.bind(this));
}
}
// If there is already a camera, we would have to release it first.
if (this._cameraObj) {
this.release(function camera_release_callback() {
navigator.mozCameras.getCamera(options, gotCamera.bind(this));
});
} else {
navigator.mozCameras.getCamera(options, gotCamera.bind(this));
}
},
setPreviewSize: function(camera) {
var viewfinder = this.viewfinder;
var style = viewfinder.style;
// Switch screen dimensions to landscape
var screenWidth = document.body.clientHeight;
var screenHeight = document.body.clientWidth;
var pictureAspectRatio = this._pictureSize.height / this._pictureSize.width;
var screenAspectRatio = screenHeight / screenWidth;
// Previews should match the aspect ratio and not be smaller than the screen
var validPreviews = camera.capabilities.previewSizes.filter(function(res) {
var isLarger = res.height >= screenHeight && res.width >= screenWidth;
var aspectRatio = res.height / res.width;
var matchesRatio = Math.abs(aspectRatio - pictureAspectRatio) < 0.05;
return matchesRatio && isLarger;
});
// We should always have a valid preview size, but just in case
// we dont, pick the first provided.
if (validPreviews.length) {
// Pick the smallest valid preview
this._previewConfig = validPreviews.sort(function(a, b) {
return a.width * a.height - b.width * b.height;
}).shift();
} else {
this._previewConfig = camera.capabilities.previewSizes[0];
}
var transform = 'rotate(90deg)';
var width, height;
// The preview should be larger than the screen, shrink it so that as
// much as possible is on screen.
if (screenAspectRatio < pictureAspectRatio) {
width = screenWidth;
height = screenWidth * pictureAspectRatio;
} else {
width = screenHeight / pictureAspectRatio;
height = screenHeight;
}
if (this._cameraNumber == 1) {
/* backwards-facing camera */
transform += ' scale(-1, 1)';
}
// Counter the position due to the rotation
// This translation goes after the rotation so the element is shifted up
// before it is rotated 90 degress clockwise.
transform += ' translate(0, -' + height + 'px)';
// Now add another translation at to center the viewfinder on the screen.
// We put this at the start of the transform, which means it is applied
// last, after the rotation, so width and height are reversed.
var dx = -(height - screenHeight) / 2;
var dy = -(width - screenWidth) / 2;
transform = 'translate(' + dx + 'px,' + dy + 'px) ' + transform;
style.transform = transform;
style.width = width + 'px';
style.height = height + 'px';
},
recordingStateChanged: function(msg) {
if (msg === 'FileSizeLimitReached' && !this.sizeLimitAlertActive) {
this.stopRecording();
this.sizeLimitAlertActive = true;
var alertText = this._pendingPick ? 'activity-size-limit-reached' :
'size-limit-reached';
alert(navigator.mozL10n.get(alertText));
this.sizeLimitAlertActive = false;
}
},
enableCameraFeatures: function camera_enableCameraFeatures(capabilities) {
if (this._cameras.length > 1) {
this.toggleButton.classList.remove('hidden');
} else {
this.toggleButton.classList.add('hidden');
}
// For checking flash support
function isSubset(subset, set) {
for (var i = 0; i < subset.length; i++) {
if (set.indexOf(subset[i]) == -1)
return false;
}
return true;
}
var flashModes = capabilities.flashModes;
if (flashModes) {
// Check camera flash support
var flash = this._flashState[this.CAMERA];
flash.supported = isSubset(flash.modes, flashModes);
// Check video flash support
flash = this._flashState[this.VIDEO];
flash.supported = isSubset(flash.modes, flashModes);
this.updateFlashUI();
} else {