This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
video.js
1284 lines (1104 loc) · 39.5 KB
/
video.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';
// Layout Mode Transition:
// list <-> selection
// list <-> fullscreen player
// Note: the mode text is also used as css style.
const LAYOUT_MODE = {
list: 'layout-list',
selection: 'layout-selection',
fullscreenPlayer: 'layout-fullscreen-player'
};
var dom = {};
var ids = ['thumbnail-list-view', 'thumbnails-bottom', 'thumbnail-list-title',
'thumbnails', 'thumbnails-video-button', 'thumbnails-select-button',
'thumbnail-select-view',
'thumbnails-delete-button', 'thumbnails-share-button',
'thumbnails-select-top', 'thumbnails-number-selected',
'player-view', 'fullscreen-button', 'spinner-overlay',
'thumbnails-single-delete-button', 'thumbnails-single-share-button',
'thumbnails-single-info-button', 'info-view', 'info-close-button',
'player', 'overlay', 'overlay-title', 'overlay-text',
'overlay-menu', 'overlay-action-button', 'player-header',
'video-container', 'videoControls', 'videoBar', 'videoControlBar',
'close', 'play', 'playHead', 'timeSlider', 'elapsedTime',
'video-title', 'duration-text', 'elapsed-text', 'bufferedTime',
'slider-wrapper', 'throbber', 'picker-close', 'picker-title',
'picker-header', 'picker-done', 'options', 'options-view',
'options-cancel-button', 'seek-backward', 'seek-forward'];
ids.forEach(function createElementRef(name) {
dom[toCamelCase(name)] = document.getElementById(name);
});
dom.player.mozAudioChannelType = 'content';
function $(id) { return document.getElementById(id); }
var playing = false;
// if this is true then the video tag is showing
// if false, then the gallery is showing
var playerShowing = false;
// keep the screen on when playing
var endedTimer;
// same thing for the controls
var controlShowing = false;
var controlFadeTimeout = null;
// In thumbnailSelectView, we allow the user to select thumbnails.
// These variables hold the names of the selected files, and map those
// names to the corresponding File objects
var selectedFileNames = [];
var selectedFileNamesToBlobs = {};
var videodb;
var currentVideo; // The data for the currently playing video
var currentVideoBlob; // The blob for the currently playing video
var firstScanEnded = false;
var THUMBNAIL_WIDTH;
var THUMBNAIL_HEIGHT;
// Enumerating the readyState for html5 video api
var HAVE_NOTHING = 0;
var storageState;
var currentOverlay;
var dragging = false;
// touch start id is the identifier of touch event. we only need to process
// events related to this id.
var touchStartID = null;
var isPausedWhileDragging;
var sliderRect;
var thumbnailList;
var pendingPick;
// This app uses deprecated-hwvideo permission to access video decoding hardware
// But Camera and Gallery also need to use that hardware, and those three apps
// may only have one video playing at a time among them. So we need to be
// careful to relinquish the hardware when we are not visible.
var restoreTime = null;
var isPhone;
var isPortrait;
var currentLayoutMode;
// When user entering fullscreen mode and rotate the screen, the text overflow
// calculation of video title should not be invoked. We pend this request when
// leaving fullscreen mode.
var pendingUpdateTitleText = false;
// Videos recorded by our own camera have filenames of this form
var FROMCAMERA = /DCIM\/\d{3}MZLLA\/VID_\d{4}\.3gp$/;
var videoControlsAutoHidingMsOverride;
// Pause on visibility change
document.addEventListener('visibilitychange', function visibilityChange() {
if (document.hidden) {
stopParsingMetadata();
if (playing) {
pause();
}
}
else {
if (playerShowing) {
setControlsVisibility(true);
} else {
// We only start parsing metadata when player is not shown.
startParsingMetadata();
}
}
});
navigator.mozL10n.once(function() {
// Tell performance monitors that our chrome is visible
window.dispatchEvent(new CustomEvent('moz-chrome-dom-loaded'));
init();
// Tell performance monitors that our chrome is ready to interact with.
window.dispatchEvent(new CustomEvent('moz-chrome-interactive'));
});
// we don't need to wait for l10n ready to have correct css layout.
initLayout();
initThumbnailSize();
if (!isPhone) {
navigator.mozL10n.ready(function localizeThumbnailListTitle() {
// reload the thumbnail list title field for tablet which is the app name.
var req = navigator.mozApps.getSelf();
req.onsuccess = function() {
var manifest = new ManifestHelper(req.result.manifest);
dom.thumbnailListTitle.textContent = manifest.name;
};
});
}
function init() {
thumbnailList = new ThumbnailList(ThumbnailDateGroup, dom.thumbnails);
// configure the template id for template group and view.
ThumbnailDateGroup.Template = new Template('thumbnail-group-header');
ThumbnailItem.Template = new Template('thumbnail-template');
ThumbnailItem.titleMaxLines = isPhone ? 2 : (isPortrait ? 4 : 2);
initDB();
// if video is not start with activity mode, we need to wire all event
// handlers.
if (!navigator.mozHasPendingMessage('activity')) {
// options button only needed by normal mode. if we are under pick activity,
// there is only pick view enabled that is enabled at showPickView();
initOptionsButtons();
}
initPlayerControls();
ForwardRewindController.init(dom.player, dom.seekForward, dom.seekBackward);
// We get headphoneschange event when the headphones is plugged or unplugged
var acm = navigator.mozAudioChannelManager;
if (acm) {
acm.addEventListener('headphoneschange', function onheadphoneschange() {
if (!acm.headphones && playing) {
setVideoPlaying(false);
}
});
}
navigator.mozSetMessageHandler('activity', handleActivityEvents);
// the overlay action button may be used in both normal mode and activity
// mode, we need to wire its event handler here.
dom.overlayActionButton.addEventListener('click', function() {
if (pendingPick) {
cancelPick();
} else if (currentOverlay === 'empty') {
launchCameraApp();
}
});
}
function initThumbnailSize() {
// use devicePixelRatio as the scale ratio for thumbnail creation.
if (isPhone) {
THUMBNAIL_WIDTH = 210 * window.devicePixelRatio;
THUMBNAIL_HEIGHT = 120 * window.devicePixelRatio;
} else {
var shortEdge = Math.min(window.innerWidth, window.innerHeight);
THUMBNAIL_WIDTH = 424 * window.devicePixelRatio * shortEdge / 800;
THUMBNAIL_HEIGHT = Math.round(THUMBNAIL_WIDTH * 4 / 7);
}
}
function initLayout() {
ScreenLayout.watch('portrait', '(orientation: portrait)');
isPhone = ScreenLayout.getCurrentLayout('tiny');
isPortrait = ScreenLayout.getCurrentLayout('portrait');
// We need to disable video playing and show a loading spinner when the first
// startup under tablet and landscape mode.
if (isPhone || isPortrait) {
dom.spinnerOverlay.classList.add('hidden');
dom.playerView.classList.remove('disabled');
} else {
dom.spinnerOverlay.classList.remove('hidden');
dom.playerView.classList.add('disabled');
}
// We handle the isPortrait calculation here, because window dispatches
// multiple resize event with different width and height in Firefox nightly.
window.addEventListener('screenlayoutchange', handleScreenLayoutChange);
switchLayout(LAYOUT_MODE.list);
}
function initPlayerControls() {
// slider dragging
dom.sliderWrapper.addEventListener('touchstart', handleSliderTouchStart);
// handles slider dragging
dom.sliderWrapper.addEventListener('touchmove', handleSliderTouchMove);
dom.sliderWrapper.addEventListener('touchend', handleSliderTouchEnd);
// handle video player
dom.player.addEventListener('timeupdate', timeUpdated);
dom.player.addEventListener('seeked', updateVideoControlSlider);
dom.player.addEventListener('ended', playerEnded);
// handle user tapping events
dom.videoControls.addEventListener('click', toggleVideoControls, true);
dom.play.addEventListener('click', handlePlayButtonClick);
dom.playerHeader.addEventListener('action', handleCloseButtonClick);
dom.pickerDone.addEventListener('click', postPickResult);
dom.options.addEventListener('click', showOptionsView);
}
function initOptionsButtons() {
// button to switch to camera
dom.thumbnailsVideoButton.addEventListener('click', launchCameraApp);
// buttons for entering/exiting selection mode
dom.thumbnailsSelectButton.addEventListener('click', showSelectView);
dom.thumbnailsSelectTop.addEventListener('action', hideSelectView);
// action buttons for selection mode
dom.thumbnailsDeleteButton.addEventListener('click', deleteSelectedItems);
dom.thumbnailsShareButton.addEventListener('click', shareSelectedItems);
// info buttons
dom.infoCloseButton.addEventListener('click', hideInfoView);
// option button cancel
dom.optionsCancelButton.addEventListener('click', hideOptionsView);
// fullscreen player
dom.fullscreenButton.addEventListener('click', toggleFullscreenPlayer);
// fullscreen toolbar
addEventListeners('.single-delete-button', 'click', deleteCurrentVideo);
addEventListeners('.single-share-button', 'click', shareCurrentVideo);
addEventListeners('.single-info-button', 'click', showInfoView);
}
function addEventListeners(selector, type, listener) {
var elements = document.body.querySelectorAll(selector);
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener(type, listener);
}
}
function toggleFullscreenPlayer(e) {
if (currentLayoutMode === LAYOUT_MODE.list) {
switchLayout(LAYOUT_MODE.fullscreenPlayer);
scheduleVideoControlsAutoHiding();
} else {
switchLayout(LAYOUT_MODE.list);
}
VideoUtils.fitContainer(dom.videoContainer, dom.player,
currentVideo.metadata.rotation || 0);
}
function toggleVideoControls(e) {
// When we change the visibility state of video controls, we need to check the
// timeout of auto hiding.
if (controlFadeTimeout) {
clearTimeout(controlFadeTimeout);
controlFadeTimeout = null;
}
// We cannot change the visibility state of video contorls when we are in
// picking mode.
if (!pendingPick) {
if (!controlShowing) {
// If control not shown, tap any place to show it.
setControlsVisibility(true);
e.cancelBubble = true;
} else if (e.originalTarget === dom.videoControls) {
// If control is shown, only tap the empty area should show it.
setControlsVisibility(false);
}
}
}
function handleScreenLayoutChange() {
// When resizing, we need to check the orientation change.
isPortrait = ScreenLayout.getCurrentLayout('portrait');
if (!isPhone) {
// In tablet, the landscape mode will show player and list at the same time.
// To keep only one hardware codec be used, we shows loading icon at the
// player view before first batch of files scanned and all their metadata
// are parsed.
if (!isPortrait && (!firstScanEnded || processingQueue)) {
// landscape mode and everything is waiting.
dom.spinnerOverlay.classList.remove('hidden');
dom.playerView.classList.add('disabled');
} else {
dom.spinnerOverlay.classList.add('hidden');
dom.playerView.classList.remove('disabled');
}
// We need to hide player when rotating to portrait which release video
// element and load the video into player when rotating to landscape.
if (currentLayoutMode === LAYOUT_MODE.list) {
if (isPortrait) {
hidePlayer(true);
} else {
showPlayer(currentVideo, false, /* autoPlay */
false, /* enterFullscreen */
true); /* keepControls */
}
}
// the maximum lines of title field is different in portrait or landscape
// mode.
ThumbnailItem.titleMaxLines = isPortrait ? 4 : 2;
}
// When layout mode is list or selection mode, we need to update all title
// text to have correct ellipsis position. Otherwise, we update them when
// leaving fullscreen mode.
if (currentLayoutMode !== LAYOUT_MODE.fullscreenPlayer) {
// XXX: to workaround bug 961636 which fires two resize event at the app
// start-up,we need to check the existence of thumbnailList before using
// it.
if (!thumbnailList) {
return;
}
thumbnailList.updateAllThumbnailTitle();
} else {
pendingUpdateTitleText = true;
}
// Rescale when window size changes. This should get called when
// screen orientation changes
if (dom.player.readyState !== HAVE_NOTHING) {
VideoUtils.fitContainer(dom.videoContainer, dom.player,
currentVideo.metadata.rotation || 0);
}
}
function switchLayout(mode) {
var oldMode = currentLayoutMode;
if (oldMode) {
document.body.classList.remove(currentLayoutMode);
}
currentLayoutMode = mode;
document.body.classList.add(currentLayoutMode);
// Update title text when leaving fullscreen mode with pending task.
if (oldMode === LAYOUT_MODE.fullscreenPlayer && pendingUpdateTitleText) {
pendingUpdateTitleText = false;
thumbnailList.updateAllThumbnailTitle();
}
}
function handleActivityEvents(a) {
var activityName = a.source.name;
if (activityName === 'pick') {
pendingPick = a;
showPickView();
}
}
function showInfoView() {
hideOptionsView();
//Get the length of the playing video
var length = isFinite(currentVideo.metadata.duration) ?
MediaUtils.formatDuration(currentVideo.metadata.duration) : '';
//Get the video size
var size = isFinite(currentVideo.size) ?
MediaUtils.formatSize(currentVideo.size) : '';
//Check if video type has prefix 'video/' e.g. video/mp4
var type = currentVideo.type;
if (type) {
var index = currentVideo.type.indexOf('/');
type = index > -1 ?
currentVideo.type.slice(index + 1) : currentVideo.type;
}
//Get the resolution of the playing video
var resolution = (currentVideo.metadata.width &&
currentVideo.metadata.height) ? currentVideo.metadata.width + 'x' +
currentVideo.metadata.height : '';
//Create data object to fill in the fields of info overlay view
var data = {
'info-name': currentVideo.metadata.title,
'info-length': length,
'info-size': size,
'info-type': type,
'info-date': MediaUtils.formatDate(currentVideo.date),
'info-resolution': resolution
};
//Populate info overlay view
MediaUtils.populateMediaInfo(data);
// We need to disable NFC sharing when showing info view
setNFCSharing(false);
//Show the video info view
dom.infoView.classList.remove('hidden');
}
function hideInfoView() {
// Enable NFC sharing when user hides info and returns to fullscreen mode
setNFCSharing(true);
dom.infoView.classList.add('hidden');
}
function showSelectView() {
// In tablet landscape mode, the video player may be playing. When entering
// selection mode, we need to hide player.
hidePlayer(true, function() {
switchLayout(LAYOUT_MODE.selection);
// styling for select view
thumbnailList.setSelectMode(true);
clearSelection();
});
}
function hideSelectView() {
clearSelection();
thumbnailList.setSelectMode(false);
switchLayout(LAYOUT_MODE.list);
if (!isPhone && !isPortrait && currentVideo) {
// We need to load the video while restoring to list mode
showPlayer(currentVideo, false, /* autoPlay */
false, /* enterFullscreen */
true); /* keepControls */
}
}
function showOptionsView() {
dom.optionsView.classList.remove('hidden');
}
function hideOptionsView() {
dom.optionsView.classList.add('hidden');
}
function clearSelection() {
// Clear the selection, if there is one
Array.forEach(selectedFileNames, function(name) {
thumbnailList.thumbnailMap[name].htmlNode.classList.remove('selected');
});
selectedFileNames = [];
selectedFileNamesToBlobs = {};
dom.thumbnailsDeleteButton.classList.add('disabled');
dom.thumbnailsShareButton.classList.add('disabled');
dom.thumbnailsNumberSelected.textContent =
navigator.mozL10n.get('number-selected2', { n: 0 });
}
// When we enter thumbnail selection mode, or when the selection changes
// we call this function to update the message the top of the screen and to
// enable or disable the Delete and Share buttons
function updateSelection(videodata) {
var thumbnail = thumbnailList.thumbnailMap[videodata.name];
var selected;
// First, update the visual appearance of the element
if (thumbnail.htmlNode.classList.contains('selected')) {
thumbnail.htmlNode.classList.remove('selected');
selected = false;
} else {
thumbnail.htmlNode.classList.add('selected');
selected = true;
}
// Now update the list of selected filenames and filename->blob map
// based on whether we selected or deselected the thumbnail
var filename = videodata.name;
if (selected) {
selectedFileNames.push(filename);
videodb.getFile(filename, function(blob) {
selectedFileNamesToBlobs[filename] = blob;
});
}
else {
delete selectedFileNamesToBlobs[filename];
var i = selectedFileNames.indexOf(filename);
if (i !== -1)
selectedFileNames.splice(i, 1);
}
// Now update the UI based on the number of selected thumbnails
var numSelected = selectedFileNames.length;
dom.thumbnailsNumberSelected.textContent =
navigator.mozL10n.get('number-selected2', { n: numSelected });
if (numSelected === 0) {
dom.thumbnailsDeleteButton.classList.add('disabled');
dom.thumbnailsShareButton.classList.add('disabled');
}
else {
dom.thumbnailsDeleteButton.classList.remove('disabled');
dom.thumbnailsShareButton.classList.remove('disabled');
}
}
function launchCameraApp() {
var a = new MozActivity({
name: 'record',
data: {
type: 'videos'
}
});
}
// We need to call resetCurrentVideo before deleting a video. The variable
// currentVideo is used as the last or current playing video. We need to change
// the current video to preview one, next one or null.
function resetCurrentVideo() {
// no currentVideo means there is no video in the list, we don't need to focus
// any one.
if (!currentVideo) {
return;
}
var currentThumbnail = thumbnailList.thumbnailMap[currentVideo.name];
currentThumbnail.htmlNode.classList.remove('focused');
var nextThumbnail = thumbnailList.findNextThumbnail(currentVideo.name);
if (nextThumbnail) {
// set focused to current thumbnail and update current video
currentVideo = nextThumbnail.data;
nextThumbnail.htmlNode.classList.add('focused');
} else {
// no more videos and a dialog will be shown when we delete the video.
currentVideo = null;
}
}
function deleteSelectedItems() {
if (selectedFileNames.length === 0)
return;
LazyLoader.load('shared/style/confirm.css', function() {
Dialogs.confirm({
messageId: 'delete-n-items?',
messageArgs: {n: selectedFileNames.length},
cancelId: 'cancel',
confirmId: 'delete',
danger: true
}, function() { // onSuccess
// deleteFile is O(n), so this loop is O(n*n). If used with really large
// selections, it might have noticably bad performance. If so, we
// can write a more efficient deleteFiles() function.
for (var i = 0; i < selectedFileNames.length; i++) {
deleteFile(selectedFileNames[i]);
}
clearSelection();
});
});
}
function deleteFile(filename) {
// Delete the file from the MediaDB. This removes the db entry and
// deletes the file in device storage. This will generate an change
// event which will call imageDeleted()
if (FROMCAMERA.test(filename)) {
// If we're deleting a video file recorded by our camera,
// we also need to delete the poster image associated with
// that video.
var postername = filename.replace('.3gp', '.jpg');
navigator.getDeviceStorage('pictures'). delete(postername);
}
// Whether or not there was a poster file to delete, delete the
// actual video file. This will cause the MediaDB to send a 'deleted'
// event, and the handler for that event will call videoDeleted() below.
videodb.deleteFile(filename);
}
// Clicking on the share button in select mode shares all selected images
function shareSelectedItems() {
var blobs = selectedFileNames.map(function(name) {
return selectedFileNamesToBlobs[name];
});
share(blobs);
}
// function from gallery/js/gallery.js
function share(blobs) {
if (blobs.length === 0)
return;
var names = [], fullpaths = [];
// Get the file name (minus path) and type of each blob
blobs.forEach(function(blob) {
// Discard the path, we just want the base name
var name = blob.name;
// We try to fix Bug 814323 by using
// current workaround of bluetooth transfer
// so we will pass both filenames and fullpaths
// The fullpaths can be removed after Bug 811615 is fixed
fullpaths.push(name);
name = name.substring(name.lastIndexOf('/') + 1);
names.push(name);
});
var a = new MozActivity({
name: 'share',
data: {
type: 'video/*', // Video app only supports video types (bug 1069885)
number: blobs.length,
blobs: blobs,
filenames: names,
filepaths: fullpaths
}
});
a.onerror = function(e) {
if (a.error.name === 'NO_PROVIDER') {
var msg = navigator.mozL10n.get('share-noprovider');
alert(msg);
} else {
console.warn('share activity error:', a.error.name);
}
};
}
function updateDialog() {
if (thumbnailList.count !== 0 && (!storageState || playerShowing)) {
showOverlay(null);
} else if (storageState === MediaDB.UPGRADING) {
showOverlay('upgrade');
} else if (storageState === MediaDB.NOCARD) {
showOverlay('nocard');
} else if (storageState === MediaDB.UNMOUNTED) {
showOverlay('pluggedin');
} else if (firstScanEnded &&
thumbnailList.count === 0 &&
metadataQueue.length === 0) {
showOverlay('empty');
}
}
function updateLoadingSpinner() {
// We show a loading spinner in tablet and landscape mode while first
// scanning of mediadb. When mediadb scanned and metadata parser parsed, we
// hide the loading spinner.
if (processingQueue) {
noMoreWorkCallback = updateLoadingSpinner;
} else {
PerformanceTestingHelper.dispatch('scan-finished');
dom.spinnerOverlay.classList.add('hidden');
dom.playerView.classList.remove('disabled');
if (thumbnailList.count) {
// Initialize currentVideo to first video item if it doesn't have a value.
currentVideo = currentVideo ||
thumbnailList.itemGroups[0].thumbnails[0].data;
// Load current video to player when we are in tablet and landscape.
if (!isPhone && !isPortrait) {
showPlayer(currentVideo, false, /* autoPlay */
false, /* enterFullscreen */
true); /* keepControls */
}
}
}
}
function thumbnailClickHandler(videodata) {
if (!isPhone && !isPortrait) {
// if the screen is large and landscape, we need to lock the operations
// while scanning and metadata parsing.
if (!firstScanEnded || processingQueue) {
return;
}
}
if (currentLayoutMode === LAYOUT_MODE.list) {
// The player is shown at landscape mode of tablet. We need to save the
// playing state before change to another video. Calling hidePlayer(true)
// can stop the video and save the state and hide everything.
// Calling hidePlayer(true) also releases hardware codec. And metadata
// parser can parse at least one video file.
hidePlayer(true, function() {
// Be certain that metadata parsing has stopped before we show the
// video player. Otherwise, we'll have contention for the video hardware
stopParsingMetadata(function() {
var fullscreen = pendingPick || isPhone || isPortrait;
showPlayer(videodata, !pendingPick, fullscreen, pendingPick);
});
});
}
else if (currentLayoutMode === LAYOUT_MODE.selection) {
updateSelection(videodata);
}
}
function setPosterImage(dom, poster) {
if (dom.dataset.uri) {
URL.revokeObjectURL(dom.dataset.uri);
}
dom.dataset.uri = URL.createObjectURL(poster);
dom.style.backgroundImage = 'url(' + dom.dataset.uri + ')';
}
function showOverlay(id) {
LazyLoader.load('shared/style/confirm.css', function() {
currentOverlay = id;
if (id === null) {
dom.overlay.classList.add('hidden');
return;
}
var _ = navigator.mozL10n.get;
var text, title;
if (pendingPick || id === 'empty') {
dom.overlayMenu.classList.remove('hidden');
dom.overlayActionButton.classList.remove('hidden');
dom.overlayActionButton.setAttribute('data-l10n-id',
pendingPick ?
'overlay-cancel-button' :
'overlay-camera-button');
} else {
dom.overlayMenu.classList.add('hidden');
dom.overlayActionButton.classList.add('hidden');
}
if (id === 'nocard') {
title = 'nocard2-title';
text = 'nocard3-text';
} else {
title = id + '-title';
text = id + '-text';
}
dom.overlayTitle.setAttribute('data-l10n-id', title);
dom.overlayText.setAttribute('data-l10n-id', text);
dom.overlay.classList.remove('hidden');
});
}
function setControlsVisibility(visible) {
// in tablet landscape mode, we always shows controls in list layout. We
// don't need to hide it.
if (isPhone || isPortrait ||
currentLayoutMode !== LAYOUT_MODE.list) {
dom.videoControls.classList[visible ? 'remove' : 'add']('hidden');
controlShowing = visible;
} else {
// always set it as shown.
controlShowing = true;
}
// to sync the slider under the case of auto-pause(unplugging headset), we
// need to update the slider when controls is visible.
if (controlShowing) {
updateVideoControlSlider();
}
}
function updateVideoControlSlider() {
// We update the slider when we get a 'seeked' event.
// Don't do updates while we're seeking because the position we fastSeek()
// to probably isn't exactly where we requested and we don't want jerky
// updates
if (dom.player.seeking) {
return;
}
var percent = (dom.player.currentTime / dom.player.duration) * 100;
if (isNaN(percent)) {
return;
}
percent += '%';
dom.elapsedText.textContent =
MediaUtils.formatDuration(dom.player.currentTime);
dom.elapsedTime.style.width = percent;
// Don't move the play head if the user is dragging it.
if (!dragging) {
dom.playHead.style.left = percent;
}
}
function setVideoPlaying(playing) {
if (playing) {
play();
} else {
pause();
}
}
function deleteCurrentVideo() {
hideOptionsView();
// We need to disable NFC sharing when showing delete confirmation dialog
setNFCSharing(false);
LazyLoader.load('shared/style/confirm.css', function() {
// If we're deleting the file shown in the player we've got to
// return to the thumbnail list. We pass false to hidePlayer() to tell it
// not to record new metadata for the file we're about to delete.
Dialogs.confirm({
messageId: 'delete-video?',
cancelId: 'cancel',
confirmId: 'delete',
danger: true
}, function _onSuccess() { // onSuccess
deleteFile(currentVideo.name);
if (!isPhone && !isPortrait) {
// If the file is deleted, we need to load another video file. This is
// only required at tablet and landscape mode. When there is no video in
// video app, the currentVideo is null and the overlay is shown.
if (currentVideo) {
showPlayer(currentVideo, false, true, true);
}
} else {
hidePlayer(false);
}
}, function _onError() {
// Enable NFC sharing when cancels delete and returns to fullscreen mode
setNFCSharing(true);
});
});
}
function handlePlayButtonClick() {
setVideoPlaying(dom.player.paused);
}
function handleCloseButtonClick() {
if (isPhone || isPortrait) {
hidePlayer(true);
} else {
// In tablet and landscape mode, close is view as a button to go back to
// player mode. And close button is only shown at fullscreen mode when it
// is tablet and landscape.
toggleFullscreenPlayer();
}
}
function postPickResult() {
pendingPick.postResult({
type: currentVideoBlob.type,
blob: currentVideoBlob
});
cleanupPick();
}
function shareCurrentVideo() {
hideOptionsView();
videodb.getFile(currentVideo.name, function(blob) {
share([blob]);
});
}
function handleSliderTouchStart(event) {
// If we have a touch start event, we don't need others.
if (null != touchStartID) {
return;
}
touchStartID = event.changedTouches[0].identifier;
isPausedWhileDragging = dom.player.paused;
dragging = true;
// calculate the slider wrapper size for slider dragging.
sliderRect = dom.sliderWrapper.getBoundingClientRect();
// We can't do anything if we don't know our duration
if (dom.player.duration === Infinity)
return;
if (!isPausedWhileDragging) {
dom.player.pause();
}
handleSliderTouchMove(event);
}
function setVideoUrl(player, video, callback) {
function handleLoadedMetadata() {
// We only want the 'loadedmetadata' handler to execute when the video
// app explicitly loads a video. To prevent unwanted side affects, for
// example, when the video app is sent to the background and then to the
// foreground, where gecko sends a 'loadedmetadata' event (among others),
// we clear the 'loadedmetadata' event handler after the event fires.
dom.player.onloadedmetadata = null;
callback();
}
if ('name' in video) {
videodb.getFile(video.name, function(file) {
var url = URL.createObjectURL(file);
player.onloadedmetadata = handleLoadedMetadata;
player.src = url;
if (pendingPick)
currentVideoBlob = file;
});
} else if ('url' in video) {
player.onloadedmetadata = handleLoadedMetadata;
player.src = video.url;
}
}
function scheduleVideoControlsAutoHiding() {
controlFadeTimeout = setTimeout(function() {
setControlsVisibility(false);
}, 250);
}
function setNFCSharing(enable) {
if (!window.navigator.mozNfc) {
return;
}
if (enable) {
// If we have NFC, we need to put the callback to have shrinking UI.
window.navigator.mozNfc.onpeerready = function(event) {
// The callback function is called when user confirm to share the
// content, send it with NFC Peer.
videodb.getFile(currentVideo.name, function(file) {
event.peer.sendFile(file);
});
};
} else {
// We need to remove onpeerready while out of fullscreen view.
window.navigator.mozNfc.onpeerready = null;
}
}
// show video player
function showPlayer(video, autoPlay, enterFullscreen, keepControls) {
if (currentVideo) {
var old = thumbnailList.thumbnailMap[currentVideo.name];
old.htmlNode.classList.remove('focused');
}
currentVideo = video;
var thumbnail = thumbnailList.thumbnailMap[currentVideo.name];
thumbnail.htmlNode.classList.add('focused');
// switch to the video player view
updateDialog();
dom.player.preload = 'metadata';
function doneSeeking() {
dom.player.onseeked = null;
setControlsVisibility(true);
// to schedule auto hiding when caller don't need to keep controls always.
if (!keepControls) {
scheduleVideoControlsAutoHiding();
}
if (autoPlay) {
play();
} else {
pause();
}
//show video player after seeking is done
dom.player.hidden = false;
}
//hide video player before setVideoUrl
dom.player.hidden = true;
setVideoUrl(dom.player, currentVideo, function() {
if (enterFullscreen) {
switchLayout(LAYOUT_MODE.fullscreenPlayer);
}
dom.durationText.textContent = MediaUtils.formatDuration(
dom.player.duration);
timeUpdated();
dom.play.classList.remove('paused');
playerShowing = true;
var rotation;
if ('metadata' in currentVideo) {