mirror of
https://github.com/ArcaneChat/android.git
synced 2026-07-03 14:05:24 +02:00
Compare commits
319 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2263c24019 | |||
| 19e414e65c | |||
| f5a52c1aa2 | |||
| 1cf5039c81 | |||
| 90a5e39872 | |||
| 30868b107e | |||
| 546d4a3bda | |||
| 33eaf71e5b | |||
| a61e73b91b | |||
| f03a3a9b50 | |||
| e2225be331 | |||
| f1f23a5099 | |||
| db3bcb017c | |||
| ab0ce1393e | |||
| b941b9e21a | |||
| b838e0d69e | |||
| 8459f5552d | |||
| 293d249024 | |||
| 38a39aec17 | |||
| f4fb855cb6 | |||
| 8fa34e8659 | |||
| eb2f2de29c | |||
| 1b2c5a028a | |||
| 4057c08df9 | |||
| 074d2054ec | |||
| cf2ea4cc56 | |||
| cff6b6bba7 | |||
| 595111fb56 | |||
| cfc0485579 | |||
| 7e7d4176f2 | |||
| 8abaa7bc02 | |||
| 714e079b17 | |||
| 6983491586 | |||
| 2cea64ccff | |||
| 0ef81716c5 | |||
| c780ddf081 | |||
| 30b778c4f6 | |||
| 5e0c7553e2 | |||
| b5fe0acd89 | |||
| 01551fe71a | |||
| edd4176890 | |||
| f4f27ac0ae | |||
| aeb297548c | |||
| eb3aa46ff7 | |||
| 05fbf5bdce | |||
| 8a5f05fe2e | |||
| 590841d139 | |||
| 44caf01cae | |||
| db36341251 | |||
| 0a63816ece | |||
| ceb0155f5f | |||
| 723e677b2b | |||
| fab24ee956 | |||
| 94f4c8b302 | |||
| 008a2410a7 | |||
| b43f337af9 | |||
| 21895cf00f | |||
| 721d016d86 | |||
| 89aaa9c072 | |||
| bcb00a9d23 | |||
| 34cd40fdd9 | |||
| c8001cedce | |||
| 880353888b | |||
| 2c67d20233 | |||
| 42c08a4d5b | |||
| 01bf0f3af5 | |||
| e765968c2c | |||
| 3837463e41 | |||
| 545a2ddc24 | |||
| 4f6f0b4685 | |||
| 1d1bad8b3b | |||
| af5769f231 | |||
| 42c6337c4d | |||
| 37a49c9d39 | |||
| 3b2f778114 | |||
| b55cc03f6d | |||
| 2e6eead045 | |||
| e77c3303a1 | |||
| e83c4f315c | |||
| 833c75d874 | |||
| 9688003648 | |||
| a2609d5bbe | |||
| 227f129455 | |||
| 4e683e5b37 | |||
| c5a0a00dd8 | |||
| de0bce163f | |||
| 9dcb58c1ea | |||
| 4729642f87 | |||
| 751cbfa635 | |||
| e40cae149b | |||
| 758dfbaa67 | |||
| 29ec49b806 | |||
| 8afb5595d0 | |||
| 8430e9ddc6 | |||
| 7439fafe2b | |||
| e1655a40bd | |||
| 92fc521d5b | |||
| 023d34f2b6 | |||
| 8fc064a5a4 | |||
| b9a329f416 | |||
| 4997fa7301 | |||
| e267d67d6e | |||
| 83b04a97ef | |||
| 7852c9e9f9 | |||
| 009adc09bc | |||
| 4d3929576d | |||
| 7712def225 | |||
| 9509919431 | |||
| 15cc62f559 | |||
| ae46cbbf5e | |||
| 1664fcdc84 | |||
| 2c45f4af37 | |||
| b3d1747c0b | |||
| 693952d0eb | |||
| 0ad5bd6e48 | |||
| 89c34f89c9 | |||
| 70971a73ad | |||
| 2c5b377712 | |||
| ae4b5a711b | |||
| 252bc52d47 | |||
| 655783db1e | |||
| 10b2af3656 | |||
| 54c3a963a4 | |||
| a7836eaded | |||
| 10fcbdc81d | |||
| b2a5885787 | |||
| 9886a4feb4 | |||
| dcd04f7064 | |||
| 5773ce8b83 | |||
| 0c3eb19de6 | |||
| 5e72e30d58 | |||
| c9d8ad3d4a | |||
| 62bd4f6d9f | |||
| 15e1d55a77 | |||
| 04cab2ee0c | |||
| fd28868ea8 | |||
| 129e6ad487 | |||
| 082f7229f2 | |||
| 1c6001ed92 | |||
| 2ec48ef1e6 | |||
| 04397f3cb0 | |||
| 8697756083 | |||
| 7be5ec589c | |||
| d3fbf529eb | |||
| e47818b5df | |||
| 201c9ebf4c | |||
| 0626192659 | |||
| 0acdd3f885 | |||
| 6f0fd1072d | |||
| d17579b928 | |||
| 090039ec29 | |||
| df8bbcd00a | |||
| fffc77cc82 | |||
| 9ee5af9fd2 | |||
| 5462f3d341 | |||
| 46dca0d212 | |||
| 603572c796 | |||
| db6c2d9d7c | |||
| b6c6375492 | |||
| 3f5255c116 | |||
| 68f3974aa2 | |||
| 2c062d8d51 | |||
| 1097157f69 | |||
| 21784aa951 | |||
| f980f7285a | |||
| 622b6bc786 | |||
| 61fc0485b7 | |||
| be2af9c871 | |||
| 898e4a45e3 | |||
| e47c6406f8 | |||
| 1d0ed83bad | |||
| 404f6ea9da | |||
| 8d75f867fd | |||
| 83f60e6252 | |||
| c4bd6576d8 | |||
| 12df911162 | |||
| f5a37ee185 | |||
| 92d71ad150 | |||
| 8824b30c4a | |||
| 741e281a37 | |||
| 354295ae7a | |||
| 09af0640c7 | |||
| 1485eeecf6 | |||
| 8b78df6a14 | |||
| 686ee6c246 | |||
| ca8114d9af | |||
| b2392c90c2 | |||
| d207fa67e5 | |||
| 2e41fe756a | |||
| d533ea5c37 | |||
| 4365e176d8 | |||
| 486b03e031 | |||
| 1dbf08327c | |||
| 0d15bb3544 | |||
| e3b48206e9 | |||
| a0e364a50f | |||
| 0db3fc55c6 | |||
| 95c3fca389 | |||
| 68a72fb8fd | |||
| 473410ece2 | |||
| 4f760a790a | |||
| ad7ee4428f | |||
| 92cf756ad2 | |||
| 3d746f08ba | |||
| e272459fc9 | |||
| a793ae52f9 | |||
| f2349a9bdd | |||
| 7082798c03 | |||
| f4fc5fae2b | |||
| 5799e43b3a | |||
| f929d6cc31 | |||
| 9f92efc554 | |||
| 3338b83910 | |||
| a4c104431d | |||
| 31ba521244 | |||
| 50dfe15f09 | |||
| 4b06d19787 | |||
| 66d147eb8b | |||
| d2591922a6 | |||
| bcc6f79373 | |||
| 015edd6053 | |||
| bec562bfb2 | |||
| 01a7c93771 | |||
| 502bae625f | |||
| a34d511922 | |||
| e65aa19109 | |||
| 30585b8de4 | |||
| 0bd4234214 | |||
| db4ceb6d68 | |||
| 1612a5d7cd | |||
| f60f4539b5 | |||
| db7c8a9dfc | |||
| 9d1f4266c2 | |||
| 0614c4fc32 | |||
| 58e452b711 | |||
| b478696bed | |||
| f3584d9eaf | |||
| d9998167f4 | |||
| 874e300220 | |||
| 49e4b90cc3 | |||
| f492f2cd71 | |||
| 2800a282ec | |||
| 593e93304c | |||
| 77b6108ca8 | |||
| 90bf2b6b19 | |||
| dd91d52df4 | |||
| de29317fa6 | |||
| 44faee6208 | |||
| 41ccf19e58 | |||
| 05c390980a | |||
| 4446ed0792 | |||
| 11942da0c0 | |||
| 9a0604a1a8 | |||
| 93ca874e61 | |||
| 9ba21c4346 | |||
| c0e7798cad | |||
| 0aea5a2201 | |||
| 63873ec1d5 | |||
| 23f269d4b3 | |||
| 9ebacb23c4 | |||
| d1e83f46d8 | |||
| 5f2dd23a6e | |||
| d29b24e9a6 | |||
| 4f1415e127 | |||
| c604313c09 | |||
| e6bc14a8de | |||
| 4a5729d371 | |||
| d9ac76a317 | |||
| 867df35d44 | |||
| e946d61b92 | |||
| fa2ffbd70f | |||
| 1123f03134 | |||
| 49e86d08bf | |||
| 5f00826e65 | |||
| 82382f31f1 | |||
| 833cbf7302 | |||
| 4e329adaca | |||
| dbc9e4c3c2 | |||
| d9cff40fd5 | |||
| ef248712d6 | |||
| 9765ba1bac | |||
| afcccaa864 | |||
| 7caef2ceb9 | |||
| cb4480ad78 | |||
| 6388349c16 | |||
| 73a111aeac | |||
| 5869bdc9dd | |||
| ff7f75abed | |||
| 28ac3bd9eb | |||
| 49f07874f8 | |||
| 59779b7f2a | |||
| 677df359ae | |||
| 4e4aca675f | |||
| 76163e6012 | |||
| 85b319825d | |||
| 8edf8a6140 | |||
| acba74142c | |||
| c06f34923e | |||
| bb00342b5d | |||
| 25b43986d3 | |||
| 9b5984182f | |||
| ae9dfb1595 | |||
| 001a4a8675 | |||
| 13a1e92321 | |||
| fb97c8edaf | |||
| ffce59ea7e | |||
| dd7ef2d744 | |||
| a76f840368 | |||
| c4bac7359b | |||
| 67e028502d | |||
| e05b31a76b | |||
| d1b95e369d | |||
| 64a71f25f2 | |||
| 76e906579b | |||
| 23dc66622b | |||
| 997bbd336c | |||
| d8a0225b1a | |||
| ce656ca374 | |||
| dd202b4c72 |
@@ -6,3 +6,6 @@ obj/
|
||||
local.properties
|
||||
*.keystore
|
||||
libs/
|
||||
|
||||
# ignore private scripts and directories, eg. local2github.prv.sh
|
||||
*.prv*
|
||||
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
# Delta Chat Changelog
|
||||
|
||||
## v0.1.27
|
||||
2017-04-12
|
||||
|
||||
* Use a permanent foreground service for reliable notifications
|
||||
* Monitor the IMAP-IDLE thread and reconnect if IMAP-IDLE seems to hang
|
||||
* Various battery and background optimizations
|
||||
|
||||
## v0.1.25
|
||||
2017-04-04
|
||||
|
||||
* Use system or user selected video player.
|
||||
* Do not connect if not configured (avoids a warning on the first time startup)
|
||||
* Add vertical scrollbar, eg. to settings activities.
|
||||
* Pimp GUI and logo.
|
||||
* Update Korean.
|
||||
|
||||
## v0.1.24
|
||||
2017-03-31
|
||||
|
||||
* Share images and documents from other apps to Delta Chat
|
||||
* Offer to mailto:-link-support to other apps
|
||||
* Ignore implausible sending time of incoming messages; use the receive time in these rare cases
|
||||
* Show errors only when Delta Chat is in foreground
|
||||
* Dynamically adapt video bitrate for longer videos to an attachment-size of max. 25 MB
|
||||
|
||||
## v0.1.23
|
||||
2017-03-28
|
||||
|
||||
* Retry connecting to IMAP if there is not network available on the first try
|
||||
* Notify about new messages if the app is not active for hours, optimize battery consumption
|
||||
|
||||
## v0.1.22
|
||||
2017-03-22
|
||||
|
||||
* Show HTML-only messages
|
||||
* Show connection errors
|
||||
* Add options for SSL/TLS and STARTTLS
|
||||
* Automatic account configuration, if possible
|
||||
* Recode large videos
|
||||
* Add Hungarian translation
|
||||
* Add Korean translation
|
||||
|
||||
## v0.1.21
|
||||
2017-03-10
|
||||
|
||||
* Record and send voice messages
|
||||
* Record and send videos
|
||||
* Send and play music
|
||||
* Send contacts and email addresses
|
||||
* Sending and opening attachments of any type
|
||||
* Share and open commands for all attachments
|
||||
* Accept VCards send to us by other apps
|
||||
* Clickable email addresses
|
||||
* Update Polish translation
|
||||
* Fix tablet startup bug
|
||||
* Close the app when using the lock-app-via-pincode function
|
||||
* Protect data by using a content provider for sharing
|
||||
* Try to clear the task switcher's screenshots when locking the app via pincode
|
||||
* Pimp GUI
|
||||
|
||||
## v0.1.20
|
||||
2017-02-16
|
||||
|
||||
* Avoid unwanted downloads of lots of old messages
|
||||
* Make the "Chats" folder visible if the server hides new folders by default
|
||||
* Fix a crash when the server returns empty folders
|
||||
* Update Polish and Portuguese translations
|
||||
* Use API level 25 (Nougat 7.1) as target
|
||||
|
||||
## v0.1.18
|
||||
2017-02-11
|
||||
|
||||
* Add Polish translation
|
||||
* Use a new default background for chats
|
||||
* Improve typography by using the system font instead of a custom resource font
|
||||
* Remove custom plural handling, use Android's routines instead
|
||||
* Remove unused source code and strings
|
||||
* More fixes of lint errors and warnings
|
||||
|
||||
## v0.1.17
|
||||
2017-02-07
|
||||
|
||||
* Drop two unnecessary permissions: ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION
|
||||
* Really add French translation
|
||||
* Update Portuguese translation
|
||||
* Start fixing translation handling of the program
|
||||
* Remove special "foss" build, because the whole program is free now.
|
||||
|
||||
## v0.1.16
|
||||
2017-02-06
|
||||
|
||||
* Add French translation
|
||||
* Fix some lint errors and warnings
|
||||
|
||||
## v0.1.15
|
||||
2017-01-31
|
||||
|
||||
* Prepare for release on [F-Droid](https://f-droid.org/)
|
||||
@@ -24,15 +24,15 @@ tasks.withType(JavaCompile) {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile 'com.android.support:support-v4:23.4.0'
|
||||
compile 'com.android.support:appcompat-v7:25.1.1'
|
||||
compile 'com.googlecode.mp4parser:isoparser:1.0.6'
|
||||
compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
|
||||
compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdkVersion 23
|
||||
buildToolsVersion '23.0.3'
|
||||
compileSdkVersion 25
|
||||
buildToolsVersion '25.0.2'
|
||||
|
||||
useLibrary 'org.apache.http.legacy'
|
||||
defaultConfig.applicationId = "com.b44t.messenger"
|
||||
@@ -74,34 +74,17 @@ android {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
|
||||
foss {
|
||||
debuggable false
|
||||
jniDebuggable false
|
||||
signingConfig signingConfigs.release
|
||||
}
|
||||
}
|
||||
|
||||
defaultConfig.versionCode = 15
|
||||
defaultConfig.versionCode = 27
|
||||
|
||||
sourceSets.main {
|
||||
jniLibs.srcDir 'libs'
|
||||
jni.srcDirs = [] //disable automatic ndk-build call
|
||||
}
|
||||
|
||||
sourceSets.debug {
|
||||
manifest.srcFile 'config/debug/AndroidManifest.xml'
|
||||
}
|
||||
|
||||
sourceSets.release {
|
||||
manifest.srcFile 'config/release/AndroidManifest.xml'
|
||||
}
|
||||
|
||||
sourceSets.foss {
|
||||
manifest.srcFile 'config/foss/AndroidManifest.xml'
|
||||
}
|
||||
|
||||
productFlavors {
|
||||
/*
|
||||
x86 {
|
||||
ndk {
|
||||
abiFilter "x86"
|
||||
@@ -120,6 +103,7 @@ android {
|
||||
}
|
||||
versionCode = 1
|
||||
}
|
||||
*/
|
||||
fat {
|
||||
versionCode = 3
|
||||
}
|
||||
@@ -131,8 +115,8 @@ android {
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 14 // 14: Android 4.0 Ice Cream Sandwich 2011 (Telegram default), 21: Android 5.0 Lollipop 2014 (recommended for InstantRun)
|
||||
targetSdkVersion 23
|
||||
versionName "0.1.16"
|
||||
minSdkVersion 14 // 14: Android 4.0 Ice Cream Sandwich 2011 (Telegram default), 21: Android 5.0 Lollipop 2014 (recommended for InstantRun)
|
||||
targetSdkVersion 25 // 25: Nougat. CAVE: Do NOT target "Andoid O" without checking the background tasks carefully, see https://developer.android.com/preview/behavior-changes.html#back-all . As long as we target "Nougat", everything works as expected even for "Andoid O" or later
|
||||
versionName "0.1.27" // do NOT forget to increase defaultConfig.versionCode!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
package="com.b44t.messenger"
|
||||
android:installLocation="auto">
|
||||
|
||||
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.location.network" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.location" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.LOCATION" android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:label="@string/AppName"
|
||||
android:theme="@style/Theme.MessengerProj.Start"
|
||||
android:name=".ApplicationLoader"
|
||||
android:hardwareAccelerated="@bool/useHardwareAcceleration"
|
||||
android:largeHeap="true">
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -1,17 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.b44t.messenger"
|
||||
android:installLocation="auto">
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:label="@string/AppName"
|
||||
android:theme="@style/Theme.MessengerProj.Start"
|
||||
android:name=".ApplicationLoader"
|
||||
android:hardwareAccelerated="@bool/useHardwareAcceleration"
|
||||
android:largeHeap="true">
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -1,24 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
package="com.b44t.messenger"
|
||||
android:installLocation="auto">
|
||||
|
||||
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.location.network" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.location" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.LOCATION" android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:label="@string/AppName"
|
||||
android:theme="@style/Theme.MessengerProj.Start"
|
||||
android:name=".ApplicationLoader"
|
||||
android:hardwareAccelerated="@bool/useHardwareAcceleration"
|
||||
android:largeHeap="true">
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -1598,9 +1598,8 @@ ifeq ($(TARGET_ARCH_ABI),armeabi-v7a)
|
||||
endif
|
||||
|
||||
LOCAL_SRC_FILES += \
|
||||
./jni.c \
|
||||
./mrjnimain.c \
|
||||
./audio.c \
|
||||
./utils.c \
|
||||
./image.c \
|
||||
./video.c \
|
||||
./gifvideo.cpp \
|
||||
@@ -1611,14 +1610,16 @@ LOCAL_SRC_FILES += \
|
||||
./messenger-backend/src/mre2ee.c \
|
||||
./messenger-backend/src/mrimap.c \
|
||||
./messenger-backend/src/mrjob.c \
|
||||
./messenger-backend/src/mrlog.c \
|
||||
./messenger-backend/src/mrloginparam.c \
|
||||
./messenger-backend/src/mrmailbox.c \
|
||||
./messenger-backend/src/mrmailbox_configure.c \
|
||||
./messenger-backend/src/mrmailbox_log.c \
|
||||
./messenger-backend/src/mrmimeparser.c \
|
||||
./messenger-backend/src/mrmsg.c \
|
||||
./messenger-backend/src/mrosnative.c \
|
||||
./messenger-backend/src/mrparam.c \
|
||||
./messenger-backend/src/mrpoortext.c \
|
||||
./messenger-backend/src/mrsaxparser.c \
|
||||
./messenger-backend/src/mrsimplify.c \
|
||||
./messenger-backend/src/mrsmtp.c \
|
||||
./messenger-backend/src/mrsqlite3.c \
|
||||
|
||||
+64
-40
@@ -1,3 +1,26 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
#include <jni.h>
|
||||
#include <ogg/ogg.h>
|
||||
#include <stdio.h>
|
||||
@@ -6,7 +29,7 @@
|
||||
#include <time.h>
|
||||
#include <opusfile.h>
|
||||
#include <math.h>
|
||||
#include "utils.h"
|
||||
#include "mrjnimain.h"
|
||||
|
||||
typedef struct {
|
||||
int version;
|
||||
@@ -115,7 +138,7 @@ static int read_chars(ROPacket *p, unsigned char *str, int nb_chars)
|
||||
return 1;
|
||||
}
|
||||
|
||||
int opus_header_to_packet(const OpusHeader *h, unsigned char *packet, int len) {
|
||||
static int opus_header_to_packet(const OpusHeader *h, unsigned char *packet, int len) {
|
||||
int i;
|
||||
Packet p;
|
||||
unsigned char ch;
|
||||
@@ -219,34 +242,34 @@ static int writeOggPage(ogg_page *page, FILE *os) {
|
||||
return written;
|
||||
}
|
||||
|
||||
const opus_int32 bitrate = 16000;
|
||||
const opus_int32 rate = 16000;
|
||||
const opus_int32 frame_size = 960;
|
||||
const int with_cvbr = 1;
|
||||
const int max_ogg_delay = 0;
|
||||
const int comment_padding = 512;
|
||||
static const opus_int32 bitrate = 16000;
|
||||
static const opus_int32 rate = 16000;
|
||||
static const opus_int32 frame_size = 960;
|
||||
static const int with_cvbr = 1;
|
||||
static const int max_ogg_delay = 0;
|
||||
static const int comment_padding = 512;
|
||||
|
||||
opus_int32 coding_rate = 16000;
|
||||
ogg_int32_t _packetId;
|
||||
OpusEncoder *_encoder = 0;
|
||||
uint8_t *_packet = 0;
|
||||
ogg_stream_state os;
|
||||
FILE *_fileOs = 0;
|
||||
oe_enc_opt inopt;
|
||||
OpusHeader header;
|
||||
opus_int32 min_bytes;
|
||||
int max_frame_bytes;
|
||||
ogg_packet op;
|
||||
ogg_page og;
|
||||
opus_int64 bytes_written;
|
||||
opus_int64 pages_out;
|
||||
opus_int64 total_samples;
|
||||
ogg_int64_t enc_granulepos;
|
||||
ogg_int64_t last_granulepos;
|
||||
int size_segments;
|
||||
int last_segments;
|
||||
static opus_int32 coding_rate = 16000;
|
||||
static ogg_int32_t _packetId;
|
||||
static OpusEncoder *_encoder = 0;
|
||||
static uint8_t *_packet = 0;
|
||||
static ogg_stream_state os;
|
||||
static FILE *_fileOs = 0;
|
||||
static oe_enc_opt inopt;
|
||||
static OpusHeader header;
|
||||
static opus_int32 min_bytes;
|
||||
static int max_frame_bytes;
|
||||
static ogg_packet op;
|
||||
static ogg_page og;
|
||||
static opus_int64 bytes_written;
|
||||
static opus_int64 pages_out;
|
||||
static opus_int64 total_samples;
|
||||
static ogg_int64_t enc_granulepos;
|
||||
static ogg_int64_t last_granulepos;
|
||||
static int size_segments;
|
||||
static int last_segments;
|
||||
|
||||
void cleanupRecorder() {
|
||||
static void cleanupRecorder() {
|
||||
|
||||
ogg_stream_flush(&os, &og);
|
||||
|
||||
@@ -282,7 +305,7 @@ void cleanupRecorder() {
|
||||
memset(&og, 0, sizeof(ogg_page));
|
||||
}
|
||||
|
||||
int initRecorder(const char *path) {
|
||||
static int initRecorder(const char *path) {
|
||||
cleanupRecorder();
|
||||
|
||||
if (!path) {
|
||||
@@ -421,7 +444,7 @@ int initRecorder(const char *path) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
int writeFrame(uint8_t *framePcmBytes, unsigned int frameByteCount) {
|
||||
static int writeFrame(uint8_t *framePcmBytes, unsigned int frameByteCount) {
|
||||
int cur_frame_size = frame_size;
|
||||
_packetId++;
|
||||
|
||||
@@ -527,15 +550,15 @@ JNIEXPORT void Java_com_b44t_messenger_MediaController_stopRecord(JNIEnv *env, j
|
||||
}
|
||||
|
||||
//player
|
||||
OggOpusFile *_opusFile;
|
||||
int _isSeekable = 0;
|
||||
int64_t _totalPcmDuration = 0;
|
||||
int64_t _currentPcmOffset = 0;
|
||||
int _finished = 0;
|
||||
static OggOpusFile *_opusFile;
|
||||
static int _isSeekable = 0;
|
||||
static int64_t _totalPcmDuration = 0;
|
||||
static int64_t _currentPcmOffset = 0;
|
||||
static int _finished = 0;
|
||||
static const int playerBuffersCount = 3;
|
||||
static const int playerSampleRate = 48000;
|
||||
|
||||
void cleanupPlayer() {
|
||||
static void cleanupPlayer() {
|
||||
if (_opusFile) {
|
||||
op_free(_opusFile);
|
||||
_opusFile = 0;
|
||||
@@ -546,7 +569,7 @@ void cleanupPlayer() {
|
||||
_finished = 0;
|
||||
}
|
||||
|
||||
int seekPlayer(float position) {
|
||||
static int seekPlayer(float position) {
|
||||
if (!_opusFile || !_isSeekable || position < 0) {
|
||||
return 0;
|
||||
}
|
||||
@@ -559,7 +582,7 @@ int seekPlayer(float position) {
|
||||
return result == OPUS_OK;
|
||||
}
|
||||
|
||||
int initPlayer(const char *path) {
|
||||
static int initPlayer(const char *path) {
|
||||
cleanupPlayer();
|
||||
|
||||
int openError = OPUS_OK;
|
||||
@@ -576,7 +599,7 @@ int initPlayer(const char *path) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
void fillBuffer(uint8_t *buffer, int capacity, int *args) {
|
||||
static void fillBuffer(uint8_t *buffer, int capacity, int *args) {
|
||||
if (_opusFile) {
|
||||
args[1] = max(0, op_pcm_tell(_opusFile));
|
||||
|
||||
@@ -735,7 +758,7 @@ JNIEXPORT jbyteArray Java_com_b44t_messenger_MediaController_getWaveform2(JNIEnv
|
||||
return result;
|
||||
}
|
||||
|
||||
int16_t *sampleBuffer = NULL;
|
||||
static int16_t *sampleBuffer = NULL;
|
||||
|
||||
|
||||
JNIEXPORT jbyteArray Java_com_b44t_messenger_MediaController_getWaveform(JNIEnv *env, jclass class, jstring path) {
|
||||
@@ -819,3 +842,4 @@ JNIEXPORT jbyteArray Java_com_b44t_messenger_MediaController_getWaveform(JNIEnv
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,28 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
#include <jni.h>
|
||||
#include <utils.h>
|
||||
#include "mrjnimain.h"
|
||||
#include <libyuv.h>
|
||||
#include <android/bitmap.h>
|
||||
#include <cstdint>
|
||||
@@ -53,19 +76,14 @@ typedef struct VideoInfo {
|
||||
AVPacket orig_pkt;
|
||||
};
|
||||
|
||||
jobject makeGlobarRef(JNIEnv *env, jobject object) {
|
||||
if (object) {
|
||||
return env->NewGlobalRef(object);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int gifvideoOnJNILoad(JavaVM *vm, JNIEnv *env) {
|
||||
int gifvideoOnJNILoad(JavaVM *vm, JNIEnv *env) { /* called from JNI_OnLoad() */
|
||||
av_register_all();
|
||||
return 0;
|
||||
}
|
||||
|
||||
int open_codec_context(int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaType type) {
|
||||
|
||||
static int open_codec_context(int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaType type) {
|
||||
int ret;
|
||||
AVStream *st;
|
||||
AVCodecContext *dec_ctx = NULL;
|
||||
@@ -97,7 +115,7 @@ int open_codec_context(int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaTy
|
||||
return 0;
|
||||
}
|
||||
|
||||
int decode_packet(VideoInfo *info, int *got_frame) {
|
||||
static int decode_packet(VideoInfo *info, int *got_frame) {
|
||||
int ret = 0;
|
||||
int decoded = info->pkt.size;
|
||||
|
||||
@@ -263,4 +281,5 @@ jint Java_com_b44t_ui_Components_AnimatedFileDrawable_getVideoFrame(JNIEnv *env,
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
} /* extern "C" */
|
||||
|
||||
+9
-6
@@ -21,10 +21,13 @@
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
#ifndef __GIFVIDEO_H__
|
||||
#define __GIFVIDEO_H__
|
||||
|
||||
public class DownloadObject {
|
||||
public TLObject object;
|
||||
public int type;
|
||||
public long id;
|
||||
}
|
||||
|
||||
#include <jni.h>
|
||||
|
||||
int gifvideoOnJNILoad(JavaVM *vm, JNIEnv *env);
|
||||
|
||||
|
||||
#endif /* __GIFVIDEO_H__ */
|
||||
+52
-15
@@ -1,3 +1,26 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
#include <jni.h>
|
||||
#include <stdio.h>
|
||||
#include <setjmp.h>
|
||||
@@ -5,21 +28,35 @@
|
||||
#include <android/bitmap.h>
|
||||
#include <libwebp/webp/decode.h>
|
||||
#include <libwebp/webp/encode.h>
|
||||
#include "utils.h"
|
||||
#include "mrjnimain.h"
|
||||
#include "image.h"
|
||||
|
||||
jclass jclass_NullPointerException;
|
||||
jclass jclass_RuntimeException;
|
||||
|
||||
jclass jclass_Options;
|
||||
jfieldID jclass_Options_inJustDecodeBounds;
|
||||
jfieldID jclass_Options_outHeight;
|
||||
jfieldID jclass_Options_outWidth;
|
||||
static jclass jclass_NullPointerException;
|
||||
static jclass jclass_RuntimeException;
|
||||
|
||||
const uint32_t PGPhotoEnhanceHistogramBins = 256;
|
||||
const uint32_t PGPhotoEnhanceSegments = 4;
|
||||
static jclass jclass_Options;
|
||||
static jfieldID jclass_Options_inJustDecodeBounds;
|
||||
static jfieldID jclass_Options_outHeight;
|
||||
static jfieldID jclass_Options_outWidth;
|
||||
|
||||
jclass createGlobarRef(JNIEnv *env, jclass class) {
|
||||
static const uint32_t PGPhotoEnhanceHistogramBins = 256;
|
||||
static const uint32_t PGPhotoEnhanceSegments = 4;
|
||||
|
||||
static void throwException(JNIEnv *env, char *format, ...) {
|
||||
jclass exClass = (*env)->FindClass(env, "java/lang/UnsupportedOperationException");
|
||||
if (!exClass) {
|
||||
return;
|
||||
}
|
||||
char dest[256];
|
||||
va_list argptr;
|
||||
va_start(argptr, format);
|
||||
vsprintf(dest, format, argptr);
|
||||
va_end(argptr);
|
||||
(*env)->ThrowNew(env, exClass, dest);
|
||||
}
|
||||
|
||||
static jclass createGlobalRef(JNIEnv *env, jclass class) {
|
||||
if (class) {
|
||||
return (*env)->NewGlobalRef(env, class);
|
||||
}
|
||||
@@ -27,16 +64,16 @@ jclass createGlobarRef(JNIEnv *env, jclass class) {
|
||||
}
|
||||
|
||||
jint imageOnJNILoad(JavaVM *vm, void *reserved, JNIEnv *env) {
|
||||
jclass_NullPointerException = createGlobarRef(env, (*env)->FindClass(env, "java/lang/NullPointerException"));
|
||||
jclass_NullPointerException = createGlobalRef(env, (*env)->FindClass(env, "java/lang/NullPointerException"));
|
||||
if (jclass_NullPointerException == 0) {
|
||||
return -1;
|
||||
}
|
||||
jclass_RuntimeException = createGlobarRef(env, (*env)->FindClass(env, "java/lang/RuntimeException"));
|
||||
jclass_RuntimeException = createGlobalRef(env, (*env)->FindClass(env, "java/lang/RuntimeException"));
|
||||
if (jclass_RuntimeException == 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
jclass_Options = createGlobarRef(env, (*env)->FindClass(env, "android/graphics/BitmapFactory$Options"));
|
||||
jclass_Options = createGlobalRef(env, (*env)->FindClass(env, "android/graphics/BitmapFactory$Options"));
|
||||
if (jclass_Options == 0) {
|
||||
return -1;
|
||||
}
|
||||
@@ -262,7 +299,7 @@ typedef struct my_error_mgr {
|
||||
} *my_error_ptr;
|
||||
|
||||
|
||||
METHODDEF(void) my_error_exit(j_common_ptr cinfo) {
|
||||
METHODDEF(void) my_jpeglib_error_exit(j_common_ptr cinfo) {
|
||||
my_error_ptr myerr = (my_error_ptr) cinfo->err;
|
||||
(*cinfo->err->output_message) (cinfo);
|
||||
longjmp(myerr->setjmp_buffer, 1);
|
||||
@@ -424,7 +461,7 @@ JNIEXPORT void Java_com_b44t_messenger_Utilities_loadBitmap(JNIEnv *env, jclass
|
||||
struct jpeg_decompress_struct cinfo;
|
||||
|
||||
cinfo.err = jpeg_std_error(&jerr.pub);
|
||||
jerr.pub.error_exit = my_error_exit;
|
||||
jerr.pub.error_exit = my_jpeglib_error_exit;
|
||||
|
||||
if (!setjmp(jerr.setjmp_buffer)) {
|
||||
jpeg_create_decompress(&cinfo);
|
||||
|
||||
@@ -1,8 +1,34 @@
|
||||
#ifndef image_h
|
||||
#define image_h
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
#ifndef __IMAGE_H__
|
||||
#define __IMAGE_H__
|
||||
|
||||
|
||||
#include <jni.h>
|
||||
|
||||
jint imageOnJNILoad(JavaVM *vm, void *reserved, JNIEnv *env);
|
||||
|
||||
#endif
|
||||
|
||||
#endif /* __IMAGE_H__ */
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <jni.h>
|
||||
#include <sys/types.h>
|
||||
#include <inttypes.h>
|
||||
#include <stdlib.h>
|
||||
#include <openssl/aes.h>
|
||||
#include <unistd.h>
|
||||
#include "utils.h"
|
||||
#include "image.h"
|
||||
|
||||
int gifvideoOnJNILoad(JavaVM *vm, JNIEnv *env);
|
||||
|
||||
jint JNI_OnLoad(JavaVM *vm, void *reserved) { /* this function is called automatically by the JNI when the library gets loaded */
|
||||
JNIEnv *env = 0;
|
||||
srand(time(NULL));
|
||||
|
||||
if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (imageOnJNILoad(vm, reserved, env) == -1) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (gifvideoOnJNILoad(vm, env) == -1) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return JNI_VERSION_1_6;
|
||||
}
|
||||
|
||||
void JNI_OnUnload(JavaVM *vm, void *reserved) {
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
JNIEXPORT void Java_com_b44t_messenger_Utilities_aesIgeEncryption(JNIEnv *env, jclass class, jobject buffer, jbyteArray key, jbyteArray iv, jboolean encrypt, int offset, int length) {
|
||||
jbyte *what = (*env)->GetDirectBufferAddress(env, buffer) + offset;
|
||||
unsigned char *keyBuff = (unsigned char *)(*env)->GetByteArrayElements(env, key, NULL);
|
||||
unsigned char *ivBuff = (unsigned char *)(*env)->GetByteArrayElements(env, iv, NULL);
|
||||
|
||||
AES_KEY akey;
|
||||
if (!encrypt) {
|
||||
AES_set_decrypt_key(keyBuff, 32 * 8, &akey);
|
||||
AES_ige_encrypt(what, what, length, &akey, ivBuff, AES_DECRYPT);
|
||||
} else {
|
||||
AES_set_encrypt_key(keyBuff, 32 * 8, &akey);
|
||||
AES_ige_encrypt(what, what, length, &akey, ivBuff, AES_ENCRYPT);
|
||||
}
|
||||
(*env)->ReleaseByteArrayElements(env, key, keyBuff, JNI_ABORT);
|
||||
(*env)->ReleaseByteArrayElements(env, iv, ivBuff, 0);
|
||||
}
|
||||
*/
|
||||
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_Utilities_readlink(JNIEnv *env, jclass class, jstring path) {
|
||||
static char buf[1000];
|
||||
char *fileName = (*env)->GetStringUTFChars(env, path, NULL);
|
||||
int result = readlink(fileName, buf, 999);
|
||||
jstring value = 0;
|
||||
if (result != -1) {
|
||||
buf[result] = '\0';
|
||||
value = (*env)->NewStringUTF(env, buf);
|
||||
}
|
||||
(*env)->ReleaseStringUTFChars(env, path, fileName);
|
||||
return value;
|
||||
}
|
||||
Submodule MessengerProj/jni/messenger-backend updated: a5cabc8147...e2c23e4459
@@ -0,0 +1,77 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <jni.h>
|
||||
#include <sys/types.h>
|
||||
#include <inttypes.h>
|
||||
#include <stdlib.h>
|
||||
#include <openssl/aes.h>
|
||||
#include <unistd.h>
|
||||
#include "mrjnimain.h"
|
||||
#include "image.h"
|
||||
#include "gifvideo.h"
|
||||
|
||||
|
||||
jint JNI_OnLoad(JavaVM *vm, void *reserved) { /* this function is called automatically by the JNI when the library gets loaded */
|
||||
JNIEnv *env = 0;
|
||||
srand(time(NULL));
|
||||
|
||||
__android_log_print(ANDROID_LOG_INFO, "DeltaChat", "JNI_OnLoad() ..."); /* please note, that __android_log_print() may not work (eg. on LG X Cam), however, we don't have an option here. */
|
||||
|
||||
if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (imageOnJNILoad(vm, reserved, env) == -1) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (gifvideoOnJNILoad(vm, env) == -1) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
__android_log_print(ANDROID_LOG_INFO, "DeltaChat", "JNI_OnLoad() succeeded.");
|
||||
|
||||
return JNI_VERSION_1_6;
|
||||
}
|
||||
|
||||
|
||||
void JNI_OnUnload(JavaVM *vm, void *reserved) {
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_Utilities_readlink(JNIEnv *env, jclass class, jstring path) {
|
||||
static char buf[1000];
|
||||
char *fileName = (*env)->GetStringUTFChars(env, path, NULL);
|
||||
int result = readlink(fileName, buf, 999);
|
||||
jstring value = 0;
|
||||
if (result != -1) {
|
||||
buf[result] = '\0';
|
||||
value = (*env)->NewStringUTF(env, buf);
|
||||
}
|
||||
(*env)->ReleaseStringUTFChars(env, path, fileName);
|
||||
return value;
|
||||
}
|
||||
|
||||
+27
-14
@@ -21,21 +21,34 @@
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.ui.Components;
|
||||
#ifndef __MRJNIMAIN_H__
|
||||
#define __MRJNIMAIN_H__
|
||||
|
||||
import android.text.TextPaint;
|
||||
|
||||
import com.b44t.messenger.AndroidUtilities;
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
|
||||
public class URLSpanNoUnderlineBold extends URLSpanNoUnderline {
|
||||
public URLSpanNoUnderlineBold(String url) {
|
||||
super(url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateDrawState(TextPaint ds) {
|
||||
super.updateDrawState(ds);
|
||||
ds.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
|
||||
ds.setUnderlineText(false);
|
||||
}
|
||||
}
|
||||
#define LOG_TAG "DeltaChat"
|
||||
#ifndef LOG_DISABLED
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
|
||||
#else
|
||||
#define LOGI(...)
|
||||
#define LOGD(...)
|
||||
#define LOGE(...)
|
||||
#define LOGV(...)
|
||||
#endif
|
||||
|
||||
#ifndef max
|
||||
#define max(x, y) ((x) > (y)) ? (x) : (y)
|
||||
#endif
|
||||
#ifndef min
|
||||
#define min(x, y) ((x) < (y)) ? (x) : (y)
|
||||
#endif
|
||||
|
||||
|
||||
#endif /* __MRJNIMAIN_H__*/
|
||||
|
||||
+162
-80
@@ -23,8 +23,8 @@
|
||||
* Purpose: The C part of the Java<->C Wrapper, see also MrMailbox.java
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
|
||||
|
||||
#include <jni.h>
|
||||
#include <android/log.h>
|
||||
#include "messenger-backend/src/mrmailbox.h"
|
||||
@@ -66,45 +66,51 @@ static jstring jstring_new__(JNIEnv* env, const char* a)
|
||||
}
|
||||
|
||||
|
||||
/* our log handler */
|
||||
|
||||
static void s_log_callback_(int type, const char* msg)
|
||||
{
|
||||
int prio;
|
||||
|
||||
switch( type ) {
|
||||
case 'd': prio = ANDROID_LOG_DEBUG; break;
|
||||
case 'i': prio = ANDROID_LOG_INFO; break;
|
||||
case 'w': prio = ANDROID_LOG_WARN; break;
|
||||
default: prio = ANDROID_LOG_ERROR; break;
|
||||
}
|
||||
__android_log_print(prio, "DeltaChat", "%s\n", msg); /* on problems, add `-llog` to `Android.mk` */
|
||||
}
|
||||
|
||||
|
||||
/* global stuff */
|
||||
|
||||
static JavaVM* s_jvm = NULL;
|
||||
static jclass s_MrMailbox_class = NULL;
|
||||
static jmethodID s_MrCallback_methodID = NULL;
|
||||
static int s_global_init_done = 0;
|
||||
|
||||
|
||||
static void s_init_globals(JNIEnv *env, jclass MrMailbox_class)
|
||||
{
|
||||
/* make sure, the intialisation is done only once */
|
||||
static bool s_global_init_done = 0;
|
||||
if( s_global_init_done ) { return; }
|
||||
s_global_init_done = 1;
|
||||
|
||||
/* init global callback */
|
||||
mrlog_set_handler(s_log_callback_);
|
||||
|
||||
/* prepare calling back a Java function */
|
||||
__android_log_print(ANDROID_LOG_INFO, "DeltaChat", "JNI: s_init_globals()..."); /* low-level logging, mrmailbox_log_*() may not be yet available. However, please note that __android_log_print() may not work (eg. on LG X Cam) */
|
||||
|
||||
(*env)->GetJavaVM(env, &s_jvm); /* JNIEnv cannot be shared between threads, so we share the JavaVM object */
|
||||
s_MrMailbox_class = (*env)->NewGlobalRef(env, MrMailbox_class);
|
||||
s_MrCallback_methodID = (*env)->GetStaticMethodID(env, MrMailbox_class, "MrCallback","(IJJ)J" /*signature as "(param)ret" with I=int, J=long*/ );
|
||||
}
|
||||
|
||||
/* system-specific backend initialisations */
|
||||
mrosnative_init_android(env); /*this should be called before any other "important" routine is called*/
|
||||
|
||||
/* setup threads, only called directly by the backed */
|
||||
|
||||
int mrosnative_setup_thread(mrmailbox_t* mailbox)
|
||||
{
|
||||
if( s_jvm == NULL ) {
|
||||
mrmailbox_log_error(mailbox, 0, "Not ready, cannot setup thread.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
mrmailbox_log_info(mailbox, 0, "Attaching C-thread to Java VM...");
|
||||
JNIEnv* env = NULL;
|
||||
(*s_jvm)->AttachCurrentThread(s_jvm, &env, NULL);
|
||||
mrmailbox_log_info(mailbox, 0, "Attaching ok.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
void mrosnative_unsetup_thread(mrmailbox_t* mailbox)
|
||||
{
|
||||
mrmailbox_log_info(mailbox, 0, "Detaching C-thread from Java VM...");
|
||||
(*s_jvm)->DetachCurrentThread(s_jvm);
|
||||
mrmailbox_log_info(mailbox, 0, "DeltaChat", "Detaching done.");
|
||||
}
|
||||
|
||||
|
||||
@@ -189,15 +195,24 @@ static uintptr_t s_mailbox_callback_(mrmailbox_t* mailbox, int event, uintptr_t
|
||||
jlong l;
|
||||
JNIEnv* env;
|
||||
|
||||
#if 0 /* -- __android_log_print() does not log eg. on LG X Cam - but Javas Log.i() etc. do. So, we do not optimize these calls and just use the Java logging. */
|
||||
if( event==MR_EVENT_INFO || event==MR_EVENT_WARNING ) {
|
||||
__android_log_print(event==MR_EVENT_INFO? ANDROID_LOG_INFO : ANDROID_LOG_WARN, "DeltaChat", "%s", (char*)data2); /* on problems, add `-llog` to `Android.mk` */
|
||||
return 0; /* speed up things for info/warning */
|
||||
}
|
||||
else if( event == MR_EVENT_ERROR ) {
|
||||
__android_log_print(ANDROID_LOG_ERROR, "DeltaChat", "%s", (char*)data2);
|
||||
/* errors are also forwarded to Java to show them in a bubble or so */
|
||||
}
|
||||
#endif
|
||||
|
||||
if( s_jvm==NULL || s_MrMailbox_class==NULL || s_MrCallback_methodID==NULL ) {
|
||||
s_log_callback_('e', "Callback called but JavaVM not ready.");
|
||||
return 0;
|
||||
return 0; /* may happen on startup */
|
||||
}
|
||||
|
||||
(*s_jvm)->GetEnv(s_jvm, &env, JNI_VERSION_1_6); /* as this function may be called from _any_ thread, we cannot use a static pointer to JNIEnv */
|
||||
if( env==NULL ) {
|
||||
s_log_callback_('e', "Callback called but cannot get JNIEnv.");
|
||||
return 0;
|
||||
return 0; /* may happen on startup */
|
||||
}
|
||||
|
||||
l = (*env)->CallStaticLongMethod(env, s_MrMailbox_class, s_MrCallback_methodID, (jint)event, (jlong)data1, (jlong)data2);
|
||||
@@ -236,42 +251,33 @@ JNIEXPORT jstring Java_com_b44t_messenger_MrMailbox_getBlobdir(JNIEnv *env, jcla
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_MrMailboxConfigure(JNIEnv *env, jclass c, jlong hMailbox)
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMailbox_configureAndConnect(JNIEnv *env, jclass cls)
|
||||
{
|
||||
return mrmailbox_configure((mrmailbox_t*)hMailbox);
|
||||
mrmailbox_configure_and_connect(get_mrmailbox_t(env, cls));
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_MrMailboxIsConfigured(JNIEnv *env, jclass c, jlong hMailbox)
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMailbox_configureCancel(JNIEnv *env, jclass cls)
|
||||
{
|
||||
return (jint)mrmailbox_is_configured((mrmailbox_t*)hMailbox);
|
||||
mrmailbox_configure_cancel(get_mrmailbox_t(env, cls));
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_MrMailboxConnect(JNIEnv *env, jclass c, jlong hMailbox)
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_isConfigured(JNIEnv *env, jclass cls)
|
||||
{
|
||||
return mrmailbox_connect((mrmailbox_t*)hMailbox);
|
||||
return (jint)mrmailbox_is_configured(get_mrmailbox_t(env, cls));
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMailbox_MrMailboxDisconnect(JNIEnv *env, jclass c, jlong hMailbox)
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMailbox_connect(JNIEnv *env, jclass cls)
|
||||
{
|
||||
mrmailbox_disconnect((mrmailbox_t*)hMailbox);
|
||||
mrmailbox_connect(get_mrmailbox_t(env, cls));
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_MrMailboxFetch(JNIEnv *env, jclass c, jlong hMailbox)
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMailbox_disconnect(JNIEnv *env, jclass cls)
|
||||
{
|
||||
return mrmailbox_fetch((mrmailbox_t*)hMailbox);
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_MrMailbox_getErrorDescr(JNIEnv *env, jclass cls)
|
||||
{
|
||||
char* c = mrmailbox_get_error_descr(get_mrmailbox_t(env, cls));
|
||||
jstring ret = JSTRING_NEW(c);
|
||||
free(c);
|
||||
return ret;
|
||||
mrmailbox_disconnect(get_mrmailbox_t(env, cls));
|
||||
}
|
||||
|
||||
|
||||
@@ -351,9 +357,9 @@ JNIEXPORT jlong Java_com_b44t_messenger_MrMailbox_MrMailboxGetChat(JNIEnv *env,
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_MrMailboxGetChatIdByContactId(JNIEnv *env, jclass c, jlong hMailbox, jint contact_id)
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_getChatIdByContactId(JNIEnv *env, jclass cls, jint contact_id)
|
||||
{
|
||||
return (jint)mrmailbox_get_chat_id_by_contact_id((mrmailbox_t*)hMailbox, contact_id);
|
||||
return (jint)mrmailbox_get_chat_id_by_contact_id(get_mrmailbox_t(env, cls), contact_id);
|
||||
}
|
||||
|
||||
|
||||
@@ -369,9 +375,9 @@ JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_markseenChat(JNIEnv *env, jclas
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_MrMailboxCreateChatByContactId(JNIEnv *env, jclass c, jlong hMailbox, jint contact_id)
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_createChatByContactId(JNIEnv *env, jclass cls, jint contact_id)
|
||||
{
|
||||
return (jint)mrmailbox_create_chat_by_contact_id((mrmailbox_t*)hMailbox, contact_id);
|
||||
return (jint)mrmailbox_create_chat_by_contact_id(get_mrmailbox_t(env, cls), contact_id);
|
||||
}
|
||||
|
||||
|
||||
@@ -384,6 +390,12 @@ JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_createGroupChat(JNIEnv *env, jc
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_isContactInChat(JNIEnv *env, jclass cls, jint chat_id, jint contact_id)
|
||||
{
|
||||
return (jint)mrmailbox_is_contact_in_chat(get_mrmailbox_t(env, cls), chat_id, contact_id);
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_addContactToChat(JNIEnv *env, jclass cls, jint chat_id, jint contact_id)
|
||||
{
|
||||
return (jint)mrmailbox_add_contact_to_chat(get_mrmailbox_t(env, cls), chat_id, contact_id);
|
||||
@@ -448,22 +460,29 @@ JNIEXPORT void Java_com_b44t_messenger_MrMailbox_forwardMsgs(JNIEnv *env, jclass
|
||||
|
||||
/* MrMailbox - handle config */
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_MrMailboxSetConfig(JNIEnv *env, jclass c, jlong hMailbox, jstring key, jstring value)
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMailbox_setConfig(JNIEnv *env, jclass cls, jstring key, jstring value)
|
||||
{
|
||||
CHAR_REF(key);
|
||||
CHAR_REF(value);
|
||||
jint ret = (jint)mrmailbox_set_config((mrmailbox_t*)hMailbox, keyPtr, valuePtr);
|
||||
mrmailbox_set_config(get_mrmailbox_t(env, cls), keyPtr, valuePtr);
|
||||
CHAR_UNREF(key);
|
||||
CHAR_UNREF(value);
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_MrMailbox_MrMailboxGetConfig(JNIEnv *env, jclass c, jlong hMailbox, jstring key, jstring def)
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMailbox_setConfigInt(JNIEnv *env, jclass cls, jstring key, jint value)
|
||||
{
|
||||
CHAR_REF(key);
|
||||
mrmailbox_set_config_int(get_mrmailbox_t(env, cls), keyPtr, value);
|
||||
CHAR_UNREF(key);
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_MrMailbox_getConfig(JNIEnv *env, jclass cls, jstring key, jstring def)
|
||||
{
|
||||
CHAR_REF(key);
|
||||
CHAR_REF(def);
|
||||
char* temp = mrmailbox_get_config((mrmailbox_t*)hMailbox, keyPtr, defPtr);
|
||||
char* temp = mrmailbox_get_config(get_mrmailbox_t(env, cls), keyPtr, defPtr);
|
||||
jstring ret = JSTRING_NEW(temp);
|
||||
free(temp);
|
||||
CHAR_UNREF(key);
|
||||
@@ -472,10 +491,10 @@ JNIEXPORT jstring Java_com_b44t_messenger_MrMailbox_MrMailboxGetConfig(JNIEnv *e
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_MrMailboxGetConfigInt(JNIEnv *env, jclass c, jlong hMailbox, jstring key, jint def)
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_getConfigInt(JNIEnv *env, jclass cls, jstring key, jint def)
|
||||
{
|
||||
CHAR_REF(key);
|
||||
jint ret = mrmailbox_get_config_int((mrmailbox_t*)hMailbox, keyPtr, def);
|
||||
jint ret = mrmailbox_get_config_int(get_mrmailbox_t(env, cls), keyPtr, def);
|
||||
CHAR_UNREF(key);
|
||||
return ret;
|
||||
}
|
||||
@@ -503,6 +522,12 @@ JNIEXPORT jstring Java_com_b44t_messenger_MrMailbox_cmdline(JNIEnv *env, jclass
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMailbox_heartbeat(JNIEnv *env, jclass cls)
|
||||
{
|
||||
mrmailbox_heartbeat(get_mrmailbox_t(env, cls));
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_MrMailboxAddAddressBook(JNIEnv *env, jclass c, jlong hMailbox, jstring adrbook)
|
||||
{
|
||||
CHAR_REF(adrbook);
|
||||
@@ -649,20 +674,20 @@ JNIEXPORT jint Java_com_b44t_messenger_MrChat_MrChatSetDraft(JNIEnv *env, jclass
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrChat_MrChatSendText(JNIEnv *env, jclass c, jlong hChat, jstring text)
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrChat_sendText(JNIEnv *env, jclass cls, jstring text)
|
||||
{
|
||||
mrmsg_t* msg = mrmsg_new();
|
||||
msg->m_type = MR_MSG_TEXT;
|
||||
CHAR_REF(text);
|
||||
msg->m_text = textPtr? strdup(textPtr) : NULL;
|
||||
CHAR_UNREF(text);
|
||||
jint msg_id = mrchat_send_msg((mrchat_t*)hChat, msg);
|
||||
jint msg_id = mrchat_send_msg(get_mrchat_t(env, cls), msg);
|
||||
mrmsg_unref(msg);
|
||||
return msg_id;
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrChat_MrChatSendMedia(JNIEnv *env, jclass c, jlong hChat, jint type, jstring file, jstring mime, jint w, jint h, jint ms)
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrChat_sendMedia(JNIEnv *env, jclass cls, jint type, jstring file, jstring mime, jint w, jint h, jint ms, jstring author, jstring trackname)
|
||||
{
|
||||
mrmsg_t* msg = mrmsg_new();
|
||||
msg->m_type = type;
|
||||
@@ -676,22 +701,36 @@ JNIEXPORT jint Java_com_b44t_messenger_MrChat_MrChatSendMedia(JNIEnv *env, jclas
|
||||
mrparam_set_int(msg->m_param, 'w', w);
|
||||
mrparam_set_int(msg->m_param, 'h', h);
|
||||
}
|
||||
if( type == MR_MSG_AUDIO || type == MR_MSG_VIDEO ) {
|
||||
if( type == MR_MSG_AUDIO || type == MR_MSG_VOICE || type == MR_MSG_VIDEO ) {
|
||||
mrparam_set_int(msg->m_param, 'd', ms);
|
||||
}
|
||||
jint msg_id = mrchat_send_msg((mrchat_t*)hChat, msg);
|
||||
if( type == MR_MSG_AUDIO ) {
|
||||
CHAR_REF(author);
|
||||
mrparam_set(msg->m_param, 'N', authorPtr);
|
||||
CHAR_UNREF(author);
|
||||
CHAR_REF(trackname);
|
||||
mrparam_set(msg->m_param, 'n', tracknamePtr);
|
||||
CHAR_UNREF(trackname);
|
||||
}
|
||||
jint msg_id = mrchat_send_msg(get_mrchat_t(env, cls), msg);
|
||||
mrmsg_unref(msg);
|
||||
return msg_id;
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jintArray Java_com_b44t_messenger_MrMailbox_MrMailboxGetChatMedia(JNIEnv *env, jclass c, jlong hMailbox, jint chat_id, jint msg_type, jint or_msg_type)
|
||||
JNIEXPORT jintArray Java_com_b44t_messenger_MrMailbox_getChatMedia(JNIEnv *env, jclass cls, jint chat_id, jint msg_type, jint or_msg_type)
|
||||
{
|
||||
carray* ca = mrmailbox_get_chat_media((mrmailbox_t*)hMailbox, chat_id, msg_type, or_msg_type);
|
||||
carray* ca = mrmailbox_get_chat_media(get_mrmailbox_t(env, cls), chat_id, msg_type, or_msg_type);
|
||||
return carray2jintArray_n_carray_free(env, ca);
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMailbox_getNextMedia(JNIEnv *env, jclass cls, jint msg_id, jint dir)
|
||||
{
|
||||
return mrmailbox_get_next_media(get_mrmailbox_t(env, cls), msg_id, dir);
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jintArray Java_com_b44t_messenger_MrMailbox_getChatMsgs(JNIEnv *env, jclass cls, jint chat_id, jint flags, jint marker1before)
|
||||
{
|
||||
carray* ca = mrmailbox_get_chat_msgs(get_mrmailbox_t(env, cls), chat_id, flags, marker1before);
|
||||
@@ -803,9 +842,9 @@ JNIEXPORT jint Java_com_b44t_messenger_MrMsg_MrMsgGetToId(JNIEnv *env, jclass c,
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_MrMsg_MrMsgGetParam(JNIEnv *env, jclass c, jlong hMsg, jint key, jstring def)
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_MrMsg_getParam(JNIEnv *env, jobject obj, jint key, jstring def)
|
||||
{
|
||||
mrmsg_t* ths = (mrmsg_t*)hMsg;
|
||||
mrmsg_t* ths = get_mrmsg_t(env, obj);
|
||||
CHAR_REF(def);
|
||||
char* temp = mrparam_get(ths? ths->m_param:NULL, key, defPtr);
|
||||
jstring ret = JSTRING_NEW(temp);
|
||||
@@ -815,17 +854,38 @@ JNIEXPORT jstring Java_com_b44t_messenger_MrMsg_MrMsgGetParam(JNIEnv *env, jclas
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMsg_MrMsgGetParamInt(JNIEnv *env, jclass c, jlong hMsg, jint key, jint def)
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMsg_getParamInt(JNIEnv *env, jobject obj, jint key, jint def)
|
||||
{
|
||||
mrmsg_t* ths = (mrmsg_t*)hMsg;
|
||||
mrmsg_t* ths = get_mrmsg_t(env, obj);
|
||||
return mrparam_get_int(ths? ths->m_param:NULL, key, def);
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMsg_setParamInt(JNIEnv *env, jobject obj, jint key, jint value)
|
||||
{
|
||||
mrmsg_t* ths = get_mrmsg_t(env, obj);
|
||||
mrparam_set_int(ths? ths->m_param:NULL, key, value);
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMsg_saveParamToDisk(JNIEnv *env, jobject obj)
|
||||
{
|
||||
mrmsg_save_param_to_disk(get_mrmsg_t(env, obj));
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMsg_getBytes(JNIEnv *env, jobject obj)
|
||||
{
|
||||
jint ret = 0;
|
||||
mrmsg_t* ths = get_mrmsg_t(env, obj);
|
||||
return ths? ths->m_bytes : 0;
|
||||
if( ths ) {
|
||||
const char* file = mrparam_get(ths->m_param, 'f', NULL);
|
||||
if( file ) {
|
||||
ret = mr_get_filebytes(file);
|
||||
free(file);
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
@@ -841,6 +901,24 @@ JNIEXPORT jint Java_com_b44t_messenger_MrMsg_getSummarytext(JNIEnv *env, jobject
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMsg_getFilename(JNIEnv *env, jobject obj)
|
||||
{
|
||||
return JSTRING_NEW(mrmsg_get_filename(get_mrmsg_t(env, obj)));
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jlong Java_com_b44t_messenger_MrMsg_getMediainfoCPtr(JNIEnv *env, jobject obj)
|
||||
{
|
||||
return (jlong)mrmsg_get_mediainfo(get_mrmsg_t(env, obj));
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrMsg_isIncreation(JNIEnv *env, jobject obj)
|
||||
{
|
||||
return (jint)mrmsg_is_increation(get_mrmsg_t(env, obj));
|
||||
}
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
* MrContact
|
||||
******************************************************************************/
|
||||
@@ -884,24 +962,24 @@ JNIEXPORT void Java_com_b44t_messenger_MrPoortext_MrPoortextUnref(JNIEnv *env, j
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_MrPoortext_MrPoortextGetTitle(JNIEnv *env, jclass c, jlong hPoortext)
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_MrPoortext_MrPoortextGetText1(JNIEnv *env, jclass c, jlong hPoortext)
|
||||
{
|
||||
mrpoortext_t* ths = (mrpoortext_t*)hPoortext; if( ths == NULL ) { return JSTRING_NEW(NULL); }
|
||||
return JSTRING_NEW(ths->m_title);
|
||||
return JSTRING_NEW(ths->m_text1);
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrPoortext_MrPoortextGetTitleMeaning(JNIEnv *env, jclass c, jlong hPoortext)
|
||||
JNIEXPORT jint Java_com_b44t_messenger_MrPoortext_MrPoortextGetText1Meaning(JNIEnv *env, jclass c, jlong hPoortext)
|
||||
{
|
||||
mrpoortext_t* ths = (mrpoortext_t*)hPoortext; if( ths == NULL ) { return 0; }
|
||||
return ths->m_title_meaning;
|
||||
return ths->m_text1_meaning;
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_MrPoortext_MrPoortextGetText(JNIEnv *env, jclass c, jlong hPoortext)
|
||||
JNIEXPORT jstring Java_com_b44t_messenger_MrPoortext_MrPoortextGetText2(JNIEnv *env, jclass c, jlong hPoortext)
|
||||
{
|
||||
mrpoortext_t* ths = (mrpoortext_t*)hPoortext; if( ths == NULL ) { return JSTRING_NEW(NULL); }
|
||||
return JSTRING_NEW(ths->m_text);
|
||||
return JSTRING_NEW(ths->m_text2);
|
||||
}
|
||||
|
||||
|
||||
@@ -935,11 +1013,15 @@ JNIEXPORT jstring Java_com_b44t_messenger_MrMailbox_CPtr2String(JNIEnv *env, jcl
|
||||
}
|
||||
|
||||
|
||||
JNIEXPORT void Java_com_b44t_messenger_MrMailbox_MrStockAddStr(JNIEnv* env, jclass c, jint id, jstring str)
|
||||
JNIEXPORT jlong Java_com_b44t_messenger_MrMailbox_String2CPtr(JNIEnv *env, jclass c, jstring str)
|
||||
{
|
||||
CHAR_REF(str);
|
||||
mrstock_add_str(id, strPtr);
|
||||
CHAR_UNREF(str)
|
||||
char* hStr = NULL;
|
||||
if( str ) {
|
||||
CHAR_REF(str);
|
||||
hStr = strdup(strPtr);
|
||||
CHAR_UNREF(str);
|
||||
}
|
||||
return (jlong)hStr;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
#include "utils.h"
|
||||
|
||||
void throwException(JNIEnv *env, char *format, ...) {
|
||||
jclass exClass = (*env)->FindClass(env, "java/lang/UnsupportedOperationException");
|
||||
if (!exClass) {
|
||||
return;
|
||||
}
|
||||
char dest[256];
|
||||
va_list argptr;
|
||||
va_start(argptr, format);
|
||||
vsprintf(dest, format, argptr);
|
||||
va_end(argptr);
|
||||
(*env)->ThrowNew(env, exClass, dest);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
#ifndef log_h
|
||||
#define log_h
|
||||
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
|
||||
#define LOG_TAG "DeltaChat"
|
||||
#ifndef LOG_DISABLED
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
|
||||
#else
|
||||
#define LOGI(...)
|
||||
#define LOGD(...)
|
||||
#define LOGE(...)
|
||||
#define LOGV(...)
|
||||
#endif
|
||||
|
||||
#ifndef max
|
||||
#define max(x, y) ((x) > (y)) ? (x) : (y)
|
||||
#endif
|
||||
#ifndef min
|
||||
#define min(x, y) ((x) < (y)) ? (x) : (y)
|
||||
#endif
|
||||
|
||||
void throwException(JNIEnv *env, char *format, ...);
|
||||
|
||||
#endif
|
||||
@@ -1,6 +1,30 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
#include <jni.h>
|
||||
#include <libyuv.h>
|
||||
#include <utils.h>
|
||||
#include "mrjnimain.h"
|
||||
|
||||
|
||||
enum COLOR_FORMATTYPE {
|
||||
COLOR_FormatMonochrome = 1,
|
||||
@@ -52,7 +76,7 @@ enum COLOR_FORMATTYPE {
|
||||
COLOR_QCOM_FormatYUV420SemiPlanar = 0x7fa30c00
|
||||
};
|
||||
|
||||
int isSemiPlanarYUV(int colorFormat) {
|
||||
static int isSemiPlanarYUV(int colorFormat) {
|
||||
switch (colorFormat) {
|
||||
case COLOR_FormatYUV420Planar:
|
||||
case COLOR_FormatYUV420PackedPlanar:
|
||||
|
||||
@@ -20,34 +20,35 @@
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- we need it eg. for getActiveNetworkInfo() -->
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
|
||||
<!-- <uses-permission android:name="android.permission.GET_ACCOUNTS" /> - required for AccountManager -->
|
||||
<uses-permission android:name="android.permission.READ_CONTACTS" />
|
||||
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
|
||||
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/>
|
||||
<uses-permission android:name="android.permission.READ_PROFILE"/>
|
||||
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS"/>
|
||||
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS"/>
|
||||
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
|
||||
<!-- <uses-permission android:name="android.permission.WRITE_CONTACTS" /> -->
|
||||
<!-- <uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/> - required for AccountManager in API level <= 22 -->
|
||||
<!-- <uses-permission android:name="android.permission.READ_PROFILE"/> - required for ContactsContract.Profile -->
|
||||
<!-- <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS"/> required for AbstractThreadedSyncAdapter-->
|
||||
<!-- <uses-permission android:name="android.permission.READ_SYNC_SETTINGS"/> - required for AbstractThreadedSyncAdapter -->
|
||||
<!-- <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/> - seems to be unneeded and is no longer supported by Android, was needed for AbstractAccountAuthenticator, see http://stackoverflow.com/questions/32601456/marshmallow-permission-implementation#36907308 -->
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
|
||||
<!-- <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> - required for windows using the TYPE_SYSTEM_ALERT flag -->
|
||||
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!-- we need the TelephonyManager to pause the audio player on calls -->
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
|
||||
<uses-permission android:name="android.permission.INSTALL_SHORTCUT" />
|
||||
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
|
||||
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>
|
||||
<!--<uses-permission android:name="android.permission.CAMERA" />-->
|
||||
<!-- <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" /> - required for AndroidUtilities.uninstallShortcut() -->
|
||||
<!-- <uses-permission android:name="android.permission.CAMERA" /> - also disabled in T'gram; we're using the camera via an intent only -->
|
||||
|
||||
<application
|
||||
android:name=".ApplicationLoader"
|
||||
android:allowBackup="false"
|
||||
android:hardwareAccelerated="@bool/useHardwareAcceleration"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:label="@string/AppName"
|
||||
android:largeHeap="true"
|
||||
android:theme="@style/Theme.MessengerProj.Start"
|
||||
android:manageSpaceActivity="com.b44t.ui.ManageSpaceActivity">
|
||||
@@ -98,22 +99,13 @@
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
<data android:mimeType="vnd.android.cursor.item/vnd.com.b44t.messenger.android.profile"/>
|
||||
</intent-filter>
|
||||
<!-- <intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW"/>
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:host="t'gram.me" android:scheme="http" />
|
||||
<data android:host="t'gram.me" android:scheme="https" />
|
||||
<data android:host="t'gram.dog" android:scheme="http" />
|
||||
<data android:host="t'gram.dog" android:scheme="https" />
|
||||
</intent-filter> -->
|
||||
<!-- <intent-filter android:icon="@drawable/ic_launcher" android:priority="1">
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:scheme="tg" />
|
||||
</intent-filter> -->
|
||||
<meta-data android:name="android.service.chooser.chooser_target_service" android:value=".TgChooserTargetService" />
|
||||
<action android:name="android.intent.action.SENDTO"/> <!-- VIEW seems to be standard, however, SENDTO is also mentioned in some examples -->
|
||||
<data android:scheme="mailto"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
<category android:name="android.intent.category.BROWSABLE"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity
|
||||
android:name="com.b44t.ui.ManageSpaceActivity"
|
||||
@@ -156,6 +148,7 @@
|
||||
</receiver>
|
||||
-->
|
||||
|
||||
<!-- currently, we do not use the android account system
|
||||
<service android:name=".AuthenticatorService" android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.accounts.AccountAuthenticator"/>
|
||||
@@ -163,7 +156,9 @@
|
||||
<meta-data android:name="android.accounts.AccountAuthenticator"
|
||||
android:resource="@xml/auth"/>
|
||||
</service>
|
||||
-->
|
||||
|
||||
<!-- seems to be not needed, derived from AbstractThreadedSyncAdapter, would need the READ/WRITE_SYNC_SETTINGS
|
||||
<service android:name=".ContactsSyncAdapterService" android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.content.SyncAdapter" />
|
||||
@@ -173,7 +168,11 @@
|
||||
<meta-data android:name="android.provider.CONTACTS_STRUCTURE"
|
||||
android:resource="@xml/contacts" />
|
||||
</service>
|
||||
-->
|
||||
|
||||
<!-- this would implement the "direct share" functionality (the system shows some direct links eg.
|
||||
to the most recent chats when calling "share" from another app, see https://developer.android.com/reference/android/service/chooser/ChooserTargetService.html )
|
||||
however, if we want this feature, we have to implement a ChooserTargetService and add <meta-data android:name="android.service.chooser.chooser_target_service" android:value=".OurChooserTargetService" />
|
||||
<service
|
||||
android:name="com.b44t.messenger.TgChooserTargetService"
|
||||
android:label="@string/AppName"
|
||||
@@ -181,18 +180,18 @@
|
||||
<intent-filter>
|
||||
<action android:name="android.service.chooser.ChooserTargetService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
</service> -->
|
||||
|
||||
<service android:name=".NotificationsService" android:enabled="true"/>
|
||||
<service android:name=".KeepAliveService" android:enabled="true"/>
|
||||
<service android:name=".NotificationRepeat" android:exported="false"/>
|
||||
<service android:name=".ClearCacheService" android:exported="false"/>
|
||||
<service android:name=".VideoEncodingService" android:enabled="true"/>
|
||||
<service android:name=".MusicPlayerService" android:exported="true" android:enabled="true"/>
|
||||
<!-- Do not expose data through MediaBrowserService, this seems unexpected for an messenger.
|
||||
Instead, the user can use 'save to music' or 'share' explicitly for items not privacy related.
|
||||
<service android:name=".MusicBrowserService" android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.media.browse.MediaBrowserService"/>
|
||||
</intent-filter>
|
||||
</service>
|
||||
</service> -->
|
||||
|
||||
<receiver android:name=".MusicPlayerReceiver" >
|
||||
<intent-filter>
|
||||
@@ -206,9 +205,8 @@
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<receiver android:name=".AppStartReceiver" android:enabled="true">
|
||||
<receiver android:name=".BootCompletedReceiver" android:enabled="true">
|
||||
<intent-filter>
|
||||
<action android:name="com.b44t.start" />
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
@@ -216,10 +214,16 @@
|
||||
<receiver android:name=".WearReplyReceiver" android:enabled="true"/>
|
||||
<!-- <receiver android:name=".NetworkAlarm" android:enabled="true"/> -->
|
||||
|
||||
<!-- seems to be unneeded (bp)
|
||||
<receiver android:name=".ShareBroadcastReceiver" android:enabled="true"/>
|
||||
-->
|
||||
|
||||
<receiver android:name=".TimerReceiver" android:enabled="true"/>
|
||||
|
||||
<receiver android:name=".NotificationDismissReceiver" android:exported="false"/>
|
||||
|
||||
<provider android:name=".AttachmentsContentProvider" android:authorities="${applicationId}.attachments" android:exported="true" />
|
||||
|
||||
<uses-library android:name="com.sec.android.app.multiwindow" android:required="false" />
|
||||
<meta-data android:name="com.sec.android.support.multiwindow" android:value="true" />
|
||||
<meta-data android:name="com.sec.android.multiwindow.DEFAULT_SIZE_W" android:value="632dp" />
|
||||
|
||||
Binary file not shown.
@@ -22,33 +22,25 @@
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.Manifest;
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorSet;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.app.DownloadManager;
|
||||
import android.content.ContentUris;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ActivityInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.res.Configuration;
|
||||
import android.database.Cursor;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.BitmapShader;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Point;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.Shader;
|
||||
import android.graphics.Typeface;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
@@ -59,6 +51,7 @@ import android.text.SpannableStringBuilder;
|
||||
import android.text.Spanned;
|
||||
import android.text.style.ForegroundColorSpan;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.util.Log;
|
||||
import android.util.StateSet;
|
||||
import android.view.Display;
|
||||
import android.view.Surface;
|
||||
@@ -70,10 +63,9 @@ import android.widget.AbsListView;
|
||||
import android.widget.EdgeEffect;
|
||||
import android.widget.EditText;
|
||||
import android.widget.ListView;
|
||||
import android.widget.ProgressBar;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.b44t.ui.ActionBar.BaseFragment;
|
||||
import com.b44t.ui.Components.ForegroundDetector;
|
||||
import com.b44t.ui.Components.TypefaceSpan;
|
||||
|
||||
@@ -86,6 +78,7 @@ import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
@@ -95,7 +88,6 @@ import java.util.regex.Pattern;
|
||||
|
||||
public class AndroidUtilities {
|
||||
|
||||
private static final Hashtable<String, Typeface> typefaceCache = new Hashtable<>();
|
||||
private static int prevOrientation = -10;
|
||||
|
||||
public static int statusBarHeight = 0;
|
||||
@@ -108,7 +100,6 @@ public class AndroidUtilities {
|
||||
private static Boolean isTablet = null;
|
||||
private static int adjustOwnerClassGuid = 0;
|
||||
|
||||
public static Pattern WEB_URL = null;
|
||||
static {
|
||||
try {
|
||||
final String GOOD_IRI_CHAR = "a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF";
|
||||
@@ -122,17 +113,8 @@ public class AndroidUtilities {
|
||||
final String GTLD = "[" + GOOD_GTLD_CHAR + "]{2,63}";
|
||||
final String HOST_NAME = "(" + IRI + "\\.)+" + GTLD;
|
||||
final Pattern DOMAIN_NAME = Pattern.compile("(" + HOST_NAME + "|" + IP_ADDRESS + ")");
|
||||
WEB_URL = Pattern.compile(
|
||||
"((?:(http|https|Http|Https):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
|
||||
+ "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
|
||||
+ "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?"
|
||||
+ "(?:" + DOMAIN_NAME + ")"
|
||||
+ "(?:\\:\\d{1,5})?)" // plus option port number
|
||||
+ "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~" // plus option query params
|
||||
+ "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?"
|
||||
+ "(?:\\b|$)");
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,101 +124,6 @@ public class AndroidUtilities {
|
||||
checkDisplaySize();
|
||||
}
|
||||
|
||||
public static int[] calcDrawableColor(Drawable drawable) {
|
||||
int bitmapColor = 0xff000000;
|
||||
int result[] = new int[2];
|
||||
try {
|
||||
if (drawable instanceof BitmapDrawable) {
|
||||
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
|
||||
if (bitmap != null) {
|
||||
Bitmap b = Bitmaps.createScaledBitmap(bitmap, 1, 1, true);
|
||||
if (b != null) {
|
||||
bitmapColor = b.getPixel(0, 0);
|
||||
b.recycle();
|
||||
}
|
||||
}
|
||||
} else if (drawable instanceof ColorDrawable) {
|
||||
bitmapColor = ((ColorDrawable) drawable).getColor();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
|
||||
double[] hsv = rgbToHsv((bitmapColor >> 16) & 0xff, (bitmapColor >> 8) & 0xff, bitmapColor & 0xff);
|
||||
hsv[1] = Math.min(1.0, hsv[1] + 0.05 + 0.1 * (1.0 - hsv[1]));
|
||||
hsv[2] = Math.max(0, hsv[2] * 0.65);
|
||||
int rgb[] = hsvToRgb(hsv[0], hsv[1], hsv[2]);
|
||||
result[0] = Color.argb(0x66, rgb[0], rgb[1], rgb[2]);
|
||||
result[1] = Color.argb(0x88, rgb[0], rgb[1], rgb[2]);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static double[] rgbToHsv(int r, int g, int b) {
|
||||
double rf = r / 255.0;
|
||||
double gf = g / 255.0;
|
||||
double bf = b / 255.0;
|
||||
double max = (rf > gf && rf > bf) ? rf : (gf > bf) ? gf : bf;
|
||||
double min = (rf < gf && rf < bf) ? rf : (gf < bf) ? gf : bf;
|
||||
double h, s;
|
||||
double d = max - min;
|
||||
s = max == 0 ? 0 : d / max;
|
||||
if (max == min) {
|
||||
h = 0;
|
||||
} else {
|
||||
if (rf > gf && rf > bf) {
|
||||
h = (gf - bf) / d + (gf < bf ? 6 : 0);
|
||||
} else if (gf > bf) {
|
||||
h = (bf - rf) / d + 2;
|
||||
} else {
|
||||
h = (rf - gf) / d + 4;
|
||||
}
|
||||
h /= 6;
|
||||
}
|
||||
return new double[]{h, s, max};
|
||||
}
|
||||
|
||||
private static int[] hsvToRgb(double h, double s, double v) {
|
||||
double r = 0, g = 0, b = 0;
|
||||
double i = (int) Math.floor(h * 6);
|
||||
double f = h * 6 - i;
|
||||
double p = v * (1 - s);
|
||||
double q = v * (1 - f * s);
|
||||
double t = v * (1 - (1 - f) * s);
|
||||
switch ((int) i % 6) {
|
||||
case 0:
|
||||
r = v;
|
||||
g = t;
|
||||
b = p;
|
||||
break;
|
||||
case 1:
|
||||
r = q;
|
||||
g = v;
|
||||
b = p;
|
||||
break;
|
||||
case 2:
|
||||
r = p;
|
||||
g = v;
|
||||
b = t;
|
||||
break;
|
||||
case 3:
|
||||
r = p;
|
||||
g = q;
|
||||
b = v;
|
||||
break;
|
||||
case 4:
|
||||
r = t;
|
||||
g = p;
|
||||
b = v;
|
||||
break;
|
||||
case 5:
|
||||
r = v;
|
||||
g = p;
|
||||
b = q;
|
||||
break;
|
||||
}
|
||||
return new int[]{(int) (r * 255), (int) (g * 255), (int) (b * 255)};
|
||||
}
|
||||
|
||||
public static void requestAdjustResize(Activity activity, int classGuid) {
|
||||
if (activity == null || isTablet()) {
|
||||
return;
|
||||
@@ -307,7 +194,7 @@ public class AndroidUtilities {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,22 +208,7 @@ public class AndroidUtilities {
|
||||
prevOrientation = -10;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Typeface getTypeface(String assetPath) {
|
||||
synchronized (typefaceCache) {
|
||||
if (!typefaceCache.containsKey(assetPath)) {
|
||||
try {
|
||||
Typeface t = Typeface.createFromAsset(ApplicationLoader.applicationContext.getAssets(), assetPath);
|
||||
typefaceCache.put(assetPath, t);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("Typefaces", "Could not get typeface '" + assetPath + "' because " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return typefaceCache.get(assetPath);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,21 +220,8 @@ public class AndroidUtilities {
|
||||
InputMethodManager inputManager = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
|
||||
inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isKeyboardShowed(View view) {
|
||||
if (view == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
|
||||
return inputManager.isActive(view);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void hideKeyboard(View view) {
|
||||
@@ -376,7 +235,7 @@ public class AndroidUtilities {
|
||||
}
|
||||
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -386,7 +245,7 @@ public class AndroidUtilities {
|
||||
try {
|
||||
state = Environment.getExternalStorageState();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
if (state == null || state.startsWith(Environment.MEDIA_MOUNTED)) {
|
||||
try {
|
||||
@@ -395,7 +254,7 @@ public class AndroidUtilities {
|
||||
return file;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
try {
|
||||
@@ -404,7 +263,7 @@ public class AndroidUtilities {
|
||||
return file;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return new File("");
|
||||
}
|
||||
@@ -443,11 +302,10 @@ public class AndroidUtilities {
|
||||
if (display != null) {
|
||||
display.getMetrics(displayMetrics);
|
||||
display.getSize(displaySize);
|
||||
FileLog.e("messenger", "display size = " + displaySize.x + " " + displaySize.y + " " + displayMetrics.xdpi + "x" + displayMetrics.ydpi);
|
||||
Log.i("DeltaChat", "Display size: " + displaySize.x + " x " + displaySize.y + ", DPI: " + displayMetrics.xdpi + " x " + displayMetrics.ydpi);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,25 +371,6 @@ public class AndroidUtilities {
|
||||
return photoSize;
|
||||
}
|
||||
|
||||
public static String formatTTLString(int ttl) {
|
||||
if (ttl < 60) {
|
||||
return LocaleController.formatPluralString("Seconds", ttl);
|
||||
} else if (ttl < 60 * 60) {
|
||||
return LocaleController.formatPluralString("Minutes", ttl / 60);
|
||||
} else if (ttl < 60 * 60 * 24) {
|
||||
return LocaleController.formatPluralString("Hours", ttl / 60 / 60);
|
||||
} else if (ttl < 60 * 60 * 24 * 7) {
|
||||
return LocaleController.formatPluralString("Days", ttl / 60 / 60 / 24);
|
||||
} else {
|
||||
int days = ttl / 60 / 60 / 24;
|
||||
if (ttl % 7 == 0) {
|
||||
return LocaleController.formatPluralString("Weeks", days / 7);
|
||||
} else {
|
||||
return String.format("%s %s", LocaleController.formatPluralString("Weeks", days / 7), LocaleController.formatPluralString("Days", days % 7));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void clearCursorDrawable(EditText editText) {
|
||||
if (editText == null) {
|
||||
return;
|
||||
@@ -541,20 +380,7 @@ public class AndroidUtilities {
|
||||
mCursorDrawableRes.setAccessible(true);
|
||||
mCursorDrawableRes.setInt(editText, 0);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void setProgressBarAnimationDuration(ProgressBar progressBar, int duration) {
|
||||
if (progressBar == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Field mCursorDrawableRes = ProgressBar.class.getDeclaredField("mDuration");
|
||||
mCursorDrawableRes.setAccessible(true);
|
||||
mCursorDrawableRes.setInt(progressBar, duration);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -584,19 +410,22 @@ public class AndroidUtilities {
|
||||
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
|
||||
ApplicationLoader.applicationContext.sendBroadcast(addIntent);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/* -- uninstalling shortcuts would be needed if a chat is deleted. However,
|
||||
-- com.b44t.messenger.openchatNNN just opens the overview in this case, which is okay for the moment.
|
||||
-- uninstalling shortcuts would required the permission com.android.launcher.permission.UNINSTALL_SHORTCUT
|
||||
public static void uninstallShortcut(int did) {
|
||||
try {
|
||||
Intent addIntent = createShortcutIntent(did, null);
|
||||
addIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
|
||||
ApplicationLoader.applicationContext.sendBroadcast(addIntent);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
public static int getViewInset(View view) {
|
||||
if (view == null || Build.VERSION.SDK_INT < 21 || view.getHeight() == AndroidUtilities.displaySize.y || view.getHeight() == AndroidUtilities.displaySize.y - statusBarHeight) {
|
||||
@@ -613,7 +442,7 @@ public class AndroidUtilities {
|
||||
return insets.bottom;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -631,11 +460,11 @@ public class AndroidUtilities {
|
||||
size.set((Integer) mGetRawW.invoke(windowManager.getDefaultDisplay()), (Integer) mGetRawH.invoke(windowManager.getDefaultDisplay()));
|
||||
} catch (Exception e) {
|
||||
size.set(windowManager.getDefaultDisplay().getWidth(), windowManager.getDefaultDisplay().getHeight());
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return size;
|
||||
}
|
||||
@@ -653,28 +482,6 @@ public class AndroidUtilities {
|
||||
return src;
|
||||
}
|
||||
|
||||
public static void setListViewEdgeEffectColor(AbsListView listView, int color) {
|
||||
if (Build.VERSION.SDK_INT >= 21) {
|
||||
try {
|
||||
Field field = AbsListView.class.getDeclaredField("mEdgeGlowTop");
|
||||
field.setAccessible(true);
|
||||
EdgeEffect mEdgeGlowTop = (EdgeEffect) field.get(listView);
|
||||
if (mEdgeGlowTop != null) {
|
||||
mEdgeGlowTop.setColor(color);
|
||||
}
|
||||
|
||||
field = AbsListView.class.getDeclaredField("mEdgeGlowBottom");
|
||||
field.setAccessible(true);
|
||||
EdgeEffect mEdgeGlowBottom = (EdgeEffect) field.get(listView);
|
||||
if (mEdgeGlowBottom != null) {
|
||||
mEdgeGlowBottom.setColor(color);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NewApi")
|
||||
public static void clearDrawableAnimation(View view) {
|
||||
if (Build.VERSION.SDK_INT < 21 || view == null) {
|
||||
@@ -731,7 +538,7 @@ public class AndroidUtilities {
|
||||
}
|
||||
}
|
||||
ArrayList<Integer> colors = new ArrayList<>();
|
||||
if ((flag & FLAG_TAG_COLOR) != 0) {
|
||||
if ((flag & FLAG_TAG_COLOR) != 0) { // used eg. by the message preview when following a mailto:-link
|
||||
while ((start = stringBuilder.indexOf("<c#")) != -1) {
|
||||
stringBuilder.replace(start, start + 2, "");
|
||||
end = stringBuilder.indexOf(">", start);
|
||||
@@ -746,14 +553,14 @@ public class AndroidUtilities {
|
||||
}
|
||||
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder);
|
||||
for (int a = 0; a < bolds.size() / 2; a++) {
|
||||
spannableStringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
|
||||
spannableStringBuilder.setSpan(new TypefaceSpan(Typeface.DEFAULT_BOLD), bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
|
||||
}
|
||||
for (int a = 0; a < colors.size() / 3; a++) {
|
||||
spannableStringBuilder.setSpan(new ForegroundColorSpan(colors.get(a * 3 + 2)), colors.get(a * 3), colors.get(a * 3 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
|
||||
}
|
||||
return spannableStringBuilder;
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return new SpannableStringBuilder(str);
|
||||
}
|
||||
@@ -764,7 +571,7 @@ public class AndroidUtilities {
|
||||
ForegroundDetector.getInstance().resetBackgroundVar();
|
||||
}
|
||||
return UserConfig.passcodeHash.length() > 0 && wasInBackground &&
|
||||
(UserConfig.appLocked || UserConfig.autoLockIn != 0 && UserConfig.lastPauseTime != 0 && !UserConfig.appLocked && (UserConfig.lastPauseTime + UserConfig.autoLockIn) <= ConnectionsManager.getInstance().getCurrentTime());
|
||||
(UserConfig.appLocked || UserConfig.autoLockIn != 0 && UserConfig.lastPauseTime != 0 && !UserConfig.appLocked && (UserConfig.lastPauseTime + UserConfig.autoLockIn) <= MrMailbox.getCurrentTime());
|
||||
}
|
||||
|
||||
public static void shakeView(final View view, final float x, final int num) {
|
||||
@@ -784,13 +591,33 @@ public class AndroidUtilities {
|
||||
animatorSet.start();
|
||||
}
|
||||
|
||||
public static void showDoneHint(Context context)
|
||||
{
|
||||
// this hint should be shown when an action is complete and not directly visible on the screen,
|
||||
// eg. copy-to-clipboard or item deletion in a long list
|
||||
Toast.makeText(context, ApplicationLoader.applicationContext.getString(R.string.DoneHint), Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
public static void showErrorHint(Context context)
|
||||
{
|
||||
// this hint should be shown on errors that normally should not happen.
|
||||
showHint(context, ApplicationLoader.applicationContext.getString(R.string.ErrorHint));
|
||||
}
|
||||
|
||||
public static Toast showHint(Context context, String text)
|
||||
{
|
||||
Toast t = Toast.makeText(context, text, Toast.LENGTH_LONG);
|
||||
t.show();
|
||||
return t;
|
||||
}
|
||||
|
||||
public static void addToClipboard(CharSequence str) {
|
||||
try {
|
||||
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE);
|
||||
android.content.ClipData clip = android.content.ClipData.newPlainText("label", str);
|
||||
clipboard.setPrimaryClip(clip);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -812,7 +639,7 @@ public class AndroidUtilities {
|
||||
mediaScanIntent.setData(uri);
|
||||
ApplicationLoader.applicationContext.sendBroadcast(mediaScanIntent);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -825,12 +652,12 @@ public class AndroidUtilities {
|
||||
storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Delta Chat");
|
||||
if (!storageDir.mkdirs()) {
|
||||
if (!storageDir.exists()){
|
||||
FileLog.d("messenger", "failed to create directory");
|
||||
Log.w("DeltaChat", "failed to create directory");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
FileLog.d("messenger", "External storage is not mounted READ/WRITE.");
|
||||
Log.w("DeltaChat", "External storage is not mounted READ/WRITE.");
|
||||
}
|
||||
|
||||
return storageDir;
|
||||
@@ -883,7 +710,7 @@ public class AndroidUtilities {
|
||||
return uri.getPath();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -907,7 +734,7 @@ public class AndroidUtilities {
|
||||
return value;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
} finally {
|
||||
if (cursor != null) {
|
||||
cursor.close();
|
||||
@@ -934,74 +761,31 @@ public class AndroidUtilities {
|
||||
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
|
||||
return new File(storageDir, "IMG_" + timeStamp + ".jpg");
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static CharSequence generateSearchName(String name, String name2, String q) {
|
||||
if (name == null && name2 == null) {
|
||||
return "";
|
||||
}
|
||||
SpannableStringBuilder builder = new SpannableStringBuilder();
|
||||
String wholeString = name;
|
||||
if (wholeString == null || wholeString.length() == 0) {
|
||||
wholeString = name2;
|
||||
} else if (name2 != null && name2.length() != 0) {
|
||||
wholeString += " " + name2;
|
||||
}
|
||||
wholeString = wholeString.trim();
|
||||
String lower = " " + wholeString.toLowerCase();
|
||||
|
||||
int index;
|
||||
int lastIndex = 0;
|
||||
while ((index = lower.indexOf(" " + q, lastIndex)) != -1) {
|
||||
int idx = index - (index == 0 ? 0 : 1);
|
||||
int end = q.length() + (index == 0 ? 0 : 1) + idx;
|
||||
|
||||
if (lastIndex != 0 && lastIndex != idx + 1) {
|
||||
builder.append(wholeString.substring(lastIndex, idx));
|
||||
} else if (lastIndex == 0 && idx != 0) {
|
||||
builder.append(wholeString.substring(0, idx));
|
||||
}
|
||||
|
||||
String query = wholeString.substring(idx, end);
|
||||
if (query.startsWith(" ")) {
|
||||
builder.append(" ");
|
||||
}
|
||||
query = query.trim();
|
||||
builder.append(AndroidUtilities.replaceTags("<c#ff4d83b3>" + query + "</c>"));
|
||||
|
||||
lastIndex = end;
|
||||
}
|
||||
|
||||
if (lastIndex != -1 && lastIndex != wholeString.length()) {
|
||||
builder.append(wholeString.substring(lastIndex, wholeString.length()));
|
||||
}
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
public static File generateVideoPath() {
|
||||
try {
|
||||
File storageDir = getAlbumDir();
|
||||
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
|
||||
return new File(storageDir, "VID_" + timeStamp + ".mp4");
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String formatFileSize(long size) {
|
||||
if (size < 1024) {
|
||||
return String.format("%d B", size);
|
||||
} else if (size < 1024 * 1024) {
|
||||
return String.format("%.1f KB", size / 1024.0f);
|
||||
} else if (size < 1024 * 1024 * 1024) {
|
||||
return String.format("%.1f MB", size / 1024.0f / 1024.0f);
|
||||
public static String formatFileSize(long bytes) {
|
||||
// We use the SI-prefix with the usual base as defined in the 1990's.
|
||||
// The other option would be to show MiB and KiB, however, these abbreviations are not very usual.
|
||||
if (bytes < 1000) {
|
||||
return String.format("%d Byte", bytes);
|
||||
} else if (bytes < (1000 * 1000)-500) { // 999499 Byte=999 KB, 999500 Byte=1,0 MB
|
||||
return String.format("%.0f KB", bytes / 1000.0f);
|
||||
} else {
|
||||
return String.format("%.1f GB", size / 1024.0f / 1024.0f / 1024.0f);
|
||||
return String.format("%.1f MB", bytes / 1000.0f / 1000.0f);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1018,7 +802,7 @@ public class AndroidUtilities {
|
||||
final int l = Character.digit((char) bytes[++i], 16);
|
||||
buffer.write((char) ((u << 4) + l));
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
@@ -1029,7 +813,7 @@ public class AndroidUtilities {
|
||||
try {
|
||||
buffer.close();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return array;
|
||||
}
|
||||
@@ -1057,7 +841,7 @@ public class AndroidUtilities {
|
||||
destination = new FileOutputStream(destFile);
|
||||
destination.getChannel().transferFrom(source.getChannel(), 0, source.getChannel().size());
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
return false;
|
||||
} finally {
|
||||
if (source != null) {
|
||||
@@ -1070,56 +854,186 @@ public class AndroidUtilities {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static byte[] calcAuthKeyHash(byte[] auth_key) {
|
||||
byte[] sha1 = Utilities.computeSHA1(auth_key);
|
||||
byte[] key_hash = new byte[16];
|
||||
System.arraycopy(sha1, 0, key_hash, 0, 16);
|
||||
return key_hash;
|
||||
}
|
||||
/* open, view, download files
|
||||
**********************************************************************************************/
|
||||
|
||||
public static void openForView(MessageObject message, Activity activity) throws Exception {
|
||||
File f = null;
|
||||
String fileName = message.getFileName();
|
||||
if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) {
|
||||
f = new File(message.messageOwner.attachPath);
|
||||
}
|
||||
if (f == null || !f.exists()) {
|
||||
f = FileLoader.getPathToMessage(message.messageOwner);
|
||||
}
|
||||
if (f != null && f.exists()) {
|
||||
String realMimeType = null;
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||
MimeTypeMap myMime = MimeTypeMap.getSingleton();
|
||||
public static String getMimetype(String fileName, String def)
|
||||
{
|
||||
String mimeType = "application/octet-stream";
|
||||
try {
|
||||
MimeTypeMap mimeMap = MimeTypeMap.getSingleton();
|
||||
int idx = fileName.lastIndexOf('.');
|
||||
if (idx != -1) {
|
||||
String ext = fileName.substring(idx + 1);
|
||||
realMimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
|
||||
if (realMimeType == null) {
|
||||
if (message.type == 9 || message.type == 0) {
|
||||
realMimeType = message.getDocument().mime_type;
|
||||
}
|
||||
if (realMimeType == null || realMimeType.length() == 0) {
|
||||
realMimeType = null;
|
||||
}
|
||||
}
|
||||
if (realMimeType != null) {
|
||||
intent.setDataAndType(Uri.fromFile(f), realMimeType);
|
||||
} else {
|
||||
intent.setDataAndType(Uri.fromFile(f), "text/plain");
|
||||
}
|
||||
} else {
|
||||
intent.setDataAndType(Uri.fromFile(f), "text/plain");
|
||||
mimeType = mimeMap.getMimeTypeFromExtension(ext.toLowerCase());
|
||||
}
|
||||
if (realMimeType != null) {
|
||||
try {
|
||||
activity.startActivityForResult(intent, 500);
|
||||
} catch (Exception e) {
|
||||
intent.setDataAndType(Uri.fromFile(f), "text/plain");
|
||||
activity.startActivityForResult(intent, 500);
|
||||
}
|
||||
} else {
|
||||
activity.startActivityForResult(intent, 500);
|
||||
if (mimeType == null) {
|
||||
mimeType = def==null? "application/octet-stream" : def;
|
||||
}
|
||||
}
|
||||
catch(Exception e) {
|
||||
}
|
||||
return mimeType;
|
||||
}
|
||||
|
||||
public static void openForViewOrShare(Activity activity, int msg_id, String cmd)
|
||||
{
|
||||
MrMsg msg = MrMailbox.getMsg(msg_id);
|
||||
String path = msg.getParam('f', "");
|
||||
String mimeType = getMimetype(path, msg.getParam('m', "application/octet-stream"));
|
||||
try {
|
||||
File file = new File(path);
|
||||
if( !file.exists() ) {
|
||||
showHint(activity, LocaleController.formatString("FileNotFound", R.string.FileNotFound, path));
|
||||
return;
|
||||
}
|
||||
|
||||
Uri uri;
|
||||
if (path.startsWith(MrMailbox.getBlobdir())) {
|
||||
uri = Uri.parse("content://" + BuildConfig.APPLICATION_ID + ".attachments/" + file.getName());
|
||||
} else {
|
||||
uri = Uri.fromFile(file);
|
||||
}
|
||||
|
||||
if( cmd == Intent.ACTION_VIEW ) {
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setDataAndType(uri, mimeType);
|
||||
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||
activity.startActivity(intent);
|
||||
}
|
||||
else {
|
||||
Intent intent = new Intent(Intent.ACTION_SEND);
|
||||
intent.setType(mimeType);
|
||||
intent.putExtra(Intent.EXTRA_STREAM, uri);
|
||||
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||
activity.startActivity(Intent.createChooser(intent, ApplicationLoader.applicationContext.getString(R.string.Share)));
|
||||
}
|
||||
|
||||
}
|
||||
catch (Exception e) {
|
||||
showHint(activity, LocaleController.formatString("NoHandleAppInstalled", R.string.NoHandleAppInstalled, mimeType));
|
||||
}
|
||||
}
|
||||
|
||||
public static File getFineFilename(File path, String desiredName)
|
||||
{
|
||||
// get a fine file name by adding a number to the basename and avoid overwrites
|
||||
for( int i = 0; i < 1000; i++ ) {
|
||||
String testName = desiredName;
|
||||
if( i > 0 ) {
|
||||
String baseName=desiredName, ext = "";
|
||||
int idx = desiredName.lastIndexOf('.');
|
||||
if( idx != -1 ) {
|
||||
baseName = desiredName.substring(0, idx);
|
||||
ext = desiredName.substring(idx);
|
||||
}
|
||||
testName = String.format("%s-%d%s", baseName, i, ext);
|
||||
}
|
||||
File pathNFile = new File(path, testName);
|
||||
if (!pathNFile.exists()) {
|
||||
return pathNFile;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void saveMessageFileToExt(final Activity context, int msg_id)
|
||||
{
|
||||
if (Build.VERSION.SDK_INT >= 23 && context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
context.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4);
|
||||
return;
|
||||
}
|
||||
|
||||
MrMsg msg = MrMailbox.getMsg(msg_id);
|
||||
final int msg_type = msg.getType();
|
||||
String msg_file_path = msg.getParam('f', "");
|
||||
final String msg_mime = msg.getParam('m', "application/octet-stream");
|
||||
final String msg_file_name = msg.getFilename();
|
||||
final File sourceFile = new File(msg_file_path);
|
||||
if( !sourceFile.exists() ) {
|
||||
showHint(context, LocaleController.formatString("FileNotFound", R.string.FileNotFound, msg_file_path));
|
||||
return;
|
||||
}
|
||||
|
||||
final Toast waitingHint = showHint(context, ApplicationLoader.applicationContext.getString(R.string.OneMoment));
|
||||
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
boolean allOkay = false;
|
||||
|
||||
try {
|
||||
// get destination path
|
||||
File destPath = null;
|
||||
boolean add_to_download_manager = false;
|
||||
if (msg_type == MrMsg.MR_MSG_IMAGE || msg_type == MrMsg.MR_MSG_VIDEO) {
|
||||
destPath = AndroidUtilities.getAlbumDir();
|
||||
} else if (msg_type == MrMsg.MR_MSG_FILE) {
|
||||
destPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
|
||||
add_to_download_manager = true;
|
||||
} else if (msg_type == MrMsg.MR_MSG_AUDIO || msg_type == MrMsg.MR_MSG_VOICE ) {
|
||||
destPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
|
||||
}
|
||||
|
||||
// create destination path (must be done, see documentation for getExternalStoragePublicDirectory())
|
||||
destPath.mkdirs();
|
||||
|
||||
File destPathNFile = getFineFilename(destPath, msg_file_name);
|
||||
if( destPathNFile != null )
|
||||
{
|
||||
destPathNFile.createNewFile();
|
||||
boolean copied = true;
|
||||
FileChannel source = null;
|
||||
FileChannel destination = null;
|
||||
try {
|
||||
source = new FileInputStream(sourceFile).getChannel();
|
||||
destination = new FileOutputStream(destPathNFile).getChannel();
|
||||
long size = source.size();
|
||||
for (long a = 0; a < size; a += 4096) {
|
||||
destination.transferFrom(source, a, Math.min(4096, size - a));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
copied = false;
|
||||
} finally {
|
||||
if (source != null) {
|
||||
source.close();
|
||||
}
|
||||
if (destination != null) {
|
||||
destination.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (copied) {
|
||||
if ( add_to_download_manager ) {
|
||||
DownloadManager downloadManager = (DownloadManager) ApplicationLoader.applicationContext.getSystemService(Context.DOWNLOAD_SERVICE);
|
||||
downloadManager.addCompletedDownload(destPathNFile.getName(), destPathNFile.getName(), false, getMimetype(msg_file_name, msg_mime), destPathNFile.getAbsolutePath(), destPathNFile.length(), true);
|
||||
} else {
|
||||
addMediaToGallery(Uri.fromFile(destPathNFile));
|
||||
}
|
||||
allOkay = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
;
|
||||
}
|
||||
|
||||
final boolean allOkayFinal = allOkay;
|
||||
AndroidUtilities.runOnUIThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
waitingHint.cancel();
|
||||
if( allOkayFinal ) {
|
||||
showDoneHint(context);
|
||||
}
|
||||
else {
|
||||
showHint(context, ApplicationLoader.applicationContext.getString(R.string.AccessError));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -33,65 +33,46 @@ import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.res.Configuration;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.NetworkInfo;
|
||||
import android.os.Handler;
|
||||
import android.os.PowerManager;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
|
||||
import com.b44t.ui.Components.ForegroundDetector;
|
||||
import com.b44t.ui.SettingsAdvActivity;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class ApplicationLoader extends Application {
|
||||
private static PendingIntent pendingIntent;
|
||||
|
||||
private static Drawable cachedWallpaper;
|
||||
private static int selectedColor;
|
||||
private static boolean isCustomTheme;
|
||||
private static final Object sync = new Object();
|
||||
|
||||
private static int serviceMessageColor;
|
||||
private static int serviceSelectedMessageColor;
|
||||
|
||||
public static volatile Context applicationContext;
|
||||
public static volatile Handler applicationHandler;
|
||||
private static volatile boolean applicationInited = false;
|
||||
|
||||
public static volatile boolean isScreenOn = false;
|
||||
public static volatile boolean mainInterfacePaused = true;
|
||||
|
||||
public static boolean isCustomTheme() {
|
||||
return isCustomTheme;
|
||||
}
|
||||
public static PowerManager.WakeLock backendWakeLock = null;
|
||||
public static PowerManager.WakeLock wakeupWakeLock = null;
|
||||
private static PowerManager.WakeLock stayAwakeWakeLock = null;
|
||||
|
||||
public static int getSelectedColor() {
|
||||
return selectedColor;
|
||||
}
|
||||
|
||||
public static int fontSize;
|
||||
|
||||
public static void reloadWallpaper() {
|
||||
cachedWallpaper = null;
|
||||
serviceMessageColor = 0;
|
||||
ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit().remove("serviceMessageColor").commit();
|
||||
loadWallpaper();
|
||||
}
|
||||
|
||||
private static void calcBackgroundColor() {
|
||||
int result[] = AndroidUtilities.calcDrawableColor(cachedWallpaper);
|
||||
serviceMessageColor = result[0];
|
||||
serviceSelectedMessageColor = result[1];
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
|
||||
preferences.edit().putInt("serviceMessageColor", serviceMessageColor).putInt("serviceSelectedMessageColor", serviceSelectedMessageColor).commit();
|
||||
}
|
||||
|
||||
public static int getServiceMessageColor() {
|
||||
return serviceMessageColor;
|
||||
}
|
||||
|
||||
public static int getServiceSelectedMessageColor() {
|
||||
return serviceSelectedMessageColor;
|
||||
return 0x44000000; // this color is used as a background for date headlines, empty chat hints and in the drawer
|
||||
}
|
||||
|
||||
public static void loadWallpaper() {
|
||||
@@ -107,20 +88,15 @@ public class ApplicationLoader extends Application {
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
|
||||
int selectedBackground = preferences.getInt("selectedBackground", 1000001);
|
||||
selectedColor = preferences.getInt("selectedColor", 0);
|
||||
serviceMessageColor = preferences.getInt("serviceMessageColor", 0);
|
||||
serviceSelectedMessageColor = preferences.getInt("serviceSelectedMessageColor", 0);
|
||||
if (selectedColor == 0) {
|
||||
if (selectedBackground == 1000001) {
|
||||
cachedWallpaper = applicationContext.getResources().getDrawable(R.drawable.background_hd);
|
||||
isCustomTheme = false;
|
||||
} else {
|
||||
File toFile = new File(getFilesDirFixed(), "wallpaper.jpg");
|
||||
if (toFile.exists()) {
|
||||
cachedWallpaper = Drawable.createFromPath(toFile.getAbsolutePath());
|
||||
isCustomTheme = true;
|
||||
} else {
|
||||
cachedWallpaper = applicationContext.getResources().getDrawable(R.drawable.background_hd);
|
||||
isCustomTheme = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,9 +109,6 @@ public class ApplicationLoader extends Application {
|
||||
}
|
||||
cachedWallpaper = new ColorDrawable(selectedColor);
|
||||
}
|
||||
if (serviceMessageColor == 0) {
|
||||
calcBackgroundColor();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -160,25 +133,56 @@ public class ApplicationLoader extends Application {
|
||||
path.mkdirs();
|
||||
return path;
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return new File("/data/data/com.b44t.messenger/files"); // EDIT BY MR
|
||||
return new File("/data/data/com.b44t.messenger/files");
|
||||
}
|
||||
|
||||
public static void postInitApplication() {
|
||||
if (applicationInited) {
|
||||
return;
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
applicationContext = getApplicationContext(); // should be set very first as it may be needed eg. for logging
|
||||
|
||||
MrMailbox.log_i("DeltaChat", "*************** ApplicationLoader.onCreate() ***************");
|
||||
System.loadLibrary("messenger.1");
|
||||
new ForegroundDetector(this);
|
||||
applicationHandler = new Handler(applicationContext.getMainLooper());
|
||||
|
||||
// create wake locks
|
||||
try {
|
||||
PowerManager pm = (PowerManager) ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE);
|
||||
|
||||
backendWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backendWakeLock" /*any name*/);
|
||||
// bakendWakeLock _is_ reference counted by the backend (every acquire() has a release())
|
||||
|
||||
wakeupWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "wakeupWakeLock" /*any name*/);
|
||||
wakeupWakeLock.setReferenceCounted(false);
|
||||
|
||||
stayAwakeWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "stayAwakeWakeLock" /*any name*/);
|
||||
stayAwakeWakeLock.setReferenceCounted(false);
|
||||
|
||||
} catch (Exception e) {
|
||||
Log.e("DeltaChat", "Cannot acquire wakeLock");
|
||||
}
|
||||
|
||||
applicationInited = true;
|
||||
//convertConfig();
|
||||
// create a MrMailbox object; as android stops the App by just killing it, we do never call MrMailboxUnref()
|
||||
// however, we may want to to have a look at onPause() eg. of activities (eg. for flushing data, if needed)
|
||||
MrMailbox.MrCallback(0, 0, 0); // do not remove this call; this makes sure, the function is not removed from build or warnings are printed!
|
||||
MrMailbox.init();
|
||||
|
||||
// start keep-alive service that restarts the app as soon it is terminated
|
||||
// (this is done by just marking the service as START_STICKY which recreates the service as
|
||||
// it goes away which also inititialized the app indirectly by calling this function)
|
||||
applicationContext.startService(new Intent(applicationContext, KeepAliveService.class));
|
||||
|
||||
// init locale
|
||||
try {
|
||||
LocaleController.getInstance();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
// track screen on/ff
|
||||
try {
|
||||
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
|
||||
filter.addAction(Intent.ACTION_SCREEN_OFF);
|
||||
@@ -191,114 +195,40 @@ public class ApplicationLoader extends Application {
|
||||
try {
|
||||
PowerManager pm = (PowerManager)ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE);
|
||||
isScreenOn = pm.isScreenOn();
|
||||
FileLog.e("messenger", "screen state = " + isScreenOn);
|
||||
//Log.i("DeltaChat", "screen state = " + isScreenOn);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
|
||||
UserConfig.loadConfig();
|
||||
String deviceModel;
|
||||
String langCode;
|
||||
String appVersion;
|
||||
String systemVersion;
|
||||
String configPath = getFilesDirFixed().toString();
|
||||
|
||||
try {
|
||||
langCode = LocaleController.getLocaleStringIso639();
|
||||
deviceModel = Build.MANUFACTURER + Build.MODEL;
|
||||
PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0);
|
||||
appVersion = pInfo.versionName + " (" + pInfo.versionCode + ")";
|
||||
systemVersion = "SDK " + Build.VERSION.SDK_INT;
|
||||
} catch (Exception e) {
|
||||
langCode = "en";
|
||||
deviceModel = "Android unknown";
|
||||
appVersion = "App version unknown";
|
||||
systemVersion = "SDK " + Build.VERSION.SDK_INT;
|
||||
}
|
||||
if (langCode.trim().length() == 0) {
|
||||
langCode = "en";
|
||||
}
|
||||
if (deviceModel.trim().length() == 0) {
|
||||
deviceModel = "Android unknown";
|
||||
}
|
||||
if (appVersion.trim().length() == 0) {
|
||||
appVersion = "App version unknown";
|
||||
}
|
||||
if (systemVersion.trim().length() == 0) {
|
||||
systemVersion = "SDK Unknown";
|
||||
}
|
||||
// create a timer that wakes up the CPU from time to time
|
||||
TimerReceiver.scheduleNextAlarm();
|
||||
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
|
||||
boolean enablePushConnection = preferences.getBoolean("pushConnection", true);
|
||||
|
||||
if( preferences.getInt("notify2_"+MrChat.MR_CHAT_ID_DEADDROP, 666)==666 ) {
|
||||
// make sure, the notifications for the "deaddrop" dialog are muted by default
|
||||
SharedPreferences.Editor editor = preferences.edit();
|
||||
// make sure, the notifications for the "deaddrop" dialog are muted by default
|
||||
SharedPreferences notificationPreferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
|
||||
if( notificationPreferences.getInt("notify2_"+MrChat.MR_CHAT_ID_DEADDROP, 666)==666 ) {
|
||||
SharedPreferences.Editor editor = notificationPreferences.edit();
|
||||
editor.putInt("notify2_"+MrChat.MR_CHAT_ID_DEADDROP, 2);
|
||||
editor.commit();
|
||||
editor.apply();
|
||||
}
|
||||
|
||||
// open() sqlite file (you can inspect the file eg. with "Tools / Android Device Monitor / File Explorer")
|
||||
// open() should be called before MessagesController.getInstance() as this also initilizes directories based upon getBlobdir().
|
||||
File dbfile = new File(getFilesDirFixed(), "messenger.db");
|
||||
MrMailbox.open(dbfile.getAbsolutePath());
|
||||
MrMailbox.connect();
|
||||
if( MrMailbox.isConfigured()!=0 ) {
|
||||
MrMailbox.connect();
|
||||
}
|
||||
|
||||
// create other default objects
|
||||
MessagesController.getInstance();
|
||||
ConnectionsManager.getInstance().init(deviceModel, systemVersion, appVersion, langCode, configPath, FileLog.getNetworkLogPath(), UserConfig.getClientUserId(), enablePushConnection);
|
||||
if (UserConfig.getCurrentUser() != null) {
|
||||
SendMessagesHelper.getInstance().checkUnsentMessages();
|
||||
}
|
||||
SharedPreferences mainPreferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
|
||||
fontSize = mainPreferences.getInt("msg_font_size", SettingsAdvActivity.defMsgFontSize());
|
||||
|
||||
ImageLoader.getInstance();
|
||||
MediaController.getInstance();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
|
||||
applicationContext = getApplicationContext();
|
||||
NativeLoader.initNativeLibs(ApplicationLoader.applicationContext);
|
||||
//ConnectionsManager.native_setJava(Build.VERSION.SDK_INT == 14 || Build.VERSION.SDK_INT == 15);
|
||||
new ForegroundDetector(this);
|
||||
|
||||
// EDIT BY MR - create a MrMailbox object; as android stops the App by just killing it, we do never call MrMailboxUnref()
|
||||
// however, we may want to to have a look at onPause() eg. of activities (eg. for flushing data, if needed)
|
||||
MrMailbox.MrCallback(0, 0, 0); // do not remove this call; this makes sure, the function is not removed from build or warnings are printed!
|
||||
MrMailbox.init();
|
||||
MrMailbox.initStockStrings();
|
||||
|
||||
applicationHandler = new Handler(applicationContext.getMainLooper());
|
||||
|
||||
startPushService();
|
||||
}
|
||||
|
||||
public static void startPushService() {
|
||||
SharedPreferences preferences = applicationContext.getSharedPreferences("Notifications", MODE_PRIVATE);
|
||||
|
||||
if (preferences.getBoolean("pushService", true)) {
|
||||
AlarmManager am = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE);
|
||||
Intent i = new Intent(applicationContext, ApplicationLoader.class);
|
||||
pendingIntent = PendingIntent.getBroadcast(applicationContext, 0, i, 0);
|
||||
|
||||
am.cancel(pendingIntent);
|
||||
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000, pendingIntent);
|
||||
|
||||
applicationContext.startService(new Intent(applicationContext, NotificationsService.class));
|
||||
} else {
|
||||
stopPushService();
|
||||
}
|
||||
}
|
||||
|
||||
public static void stopPushService() {
|
||||
applicationContext.stopService(new Intent(applicationContext, NotificationsService.class));
|
||||
|
||||
PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0);
|
||||
AlarmManager alarm = (AlarmManager)applicationContext.getSystemService(Context.ALARM_SERVICE);
|
||||
alarm.cancel(pintent);
|
||||
alarm.cancel(pendingIntent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConfigurationChanged(Configuration newConfig) {
|
||||
super.onConfigurationChanged(newConfig);
|
||||
@@ -309,4 +239,27 @@ public class ApplicationLoader extends Application {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static int lastClassGuid = 1;
|
||||
public static int generateClassGuid() {
|
||||
return lastClassGuid++;
|
||||
}
|
||||
|
||||
public static boolean isNetworkOnline() {
|
||||
try {
|
||||
ConnectivityManager cm = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
NetworkInfo netInfo = cm.getActiveNetworkInfo();
|
||||
if (netInfo != null && netInfo.isConnected()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void stayAwakeForAMoment()
|
||||
{
|
||||
stayAwakeWakeLock.acquire(1*60*1000); // 1 Minute to wait for "after chat" messages, after that, we sleep most time, see wakeupWakeLock
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.content.ContentProvider;
|
||||
import android.content.ContentValues;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
|
||||
|
||||
public class AttachmentsContentProvider extends ContentProvider {
|
||||
|
||||
/* We save all attachments in our private files-directory
|
||||
that cannot be read by other apps.
|
||||
|
||||
So starting, when starting an Intent for viewing (eg. openForView()), we cannot use the paths.
|
||||
Instead, we give a content://-url that results in calls to this class.
|
||||
|
||||
(An alternative would be to copy files to view to a public directory, however, this would
|
||||
lead to duplicate data.
|
||||
Another alterntive would be to write all attachments to a public directory, however, this
|
||||
may lead to security problems as files are system-wide-readable and would also cause problems
|
||||
if the user or another app deletes these files) */
|
||||
|
||||
@Override
|
||||
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
|
||||
File privateFile = new File(MrMailbox.getBlobdir(), uri.getPath());
|
||||
return ParcelFileDescriptor.open(privateFile, ParcelFileDescriptor.MODE_READ_ONLY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int delete(Uri arg0, String arg1, String[] arg2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getType(Uri arg0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Uri insert(Uri arg0, ContentValues arg1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCreate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,
|
||||
String arg4) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.accounts.AbstractAccountAuthenticator;
|
||||
import android.accounts.Account;
|
||||
import android.accounts.AccountAuthenticatorResponse;
|
||||
import android.accounts.AccountManager;
|
||||
import android.accounts.NetworkErrorException;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.os.IBinder;
|
||||
|
||||
public class AuthenticatorService extends Service {
|
||||
|
||||
private static class Authenticator extends AbstractAccountAuthenticator {
|
||||
private final Context context;
|
||||
|
||||
public Authenticator(Context context) {
|
||||
super(context);
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options)
|
||||
throws NetworkErrorException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle getAccountRemovalAllowed(AccountAuthenticatorResponse response, Account account) throws NetworkErrorException {
|
||||
return super.getAccountRemovalAllowed(response, account);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options)
|
||||
throws NetworkErrorException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthTokenLabel(String authTokenType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle hasFeatures(AccountAuthenticatorResponse response,
|
||||
Account account, String[] features)
|
||||
throws NetworkErrorException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options)
|
||||
throws NetworkErrorException {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static Authenticator authenticator = null;
|
||||
|
||||
protected Authenticator getAuthenticator() {
|
||||
if (authenticator == null) {
|
||||
authenticator = new Authenticator(this);
|
||||
}
|
||||
return authenticator;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
if (intent.getAction().equals(AccountManager.ACTION_AUTHENTICATOR_INTENT)) {
|
||||
return getAuthenticator().getIBinder();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,12 +26,13 @@ package com.b44t.messenger;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.util.Log;
|
||||
|
||||
public class AutoMessageHeardReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
ApplicationLoader.postInitApplication();
|
||||
|
||||
long dialog_id = intent.getLongExtra("dialog_id", 0);
|
||||
int max_id = intent.getIntExtra("max_id", 0);
|
||||
if (dialog_id == 0 || max_id == 0) {
|
||||
|
||||
@@ -28,12 +28,13 @@ import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.app.RemoteInput;
|
||||
import android.util.Log;
|
||||
|
||||
public class AutoMessageReplyReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
ApplicationLoader.postInitApplication();
|
||||
|
||||
Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
|
||||
if (remoteInput == null) {
|
||||
return;
|
||||
@@ -47,7 +48,7 @@ public class AutoMessageReplyReceiver extends BroadcastReceiver {
|
||||
if (dialog_id == 0 || max_id == 0) {
|
||||
return;
|
||||
}
|
||||
SendMessagesHelper.getInstance().sendMessageText(text.toString(), dialog_id, null, null);
|
||||
SendMessagesHelper.getInstance().sendMessageText(text.toString(), dialog_id, null);
|
||||
MrMailbox.markseenChat((int)dialog_id);
|
||||
NotificationsController.getInstance().removeSeenMessages();
|
||||
}
|
||||
|
||||
+6
-8
@@ -1,7 +1,6 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
@@ -26,14 +25,13 @@ package com.b44t.messenger;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.util.Log;
|
||||
|
||||
public class AppStartReceiver extends BroadcastReceiver {
|
||||
|
||||
public class BootCompletedReceiver extends BroadcastReceiver {
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
AndroidUtilities.runOnUIThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ApplicationLoader.startPushService();
|
||||
}
|
||||
});
|
||||
MrMailbox.log_i("DeltaChat", "*** BootCompletedReceiver.onReceive()");
|
||||
// there's nothing more to do here as all initialisation stuff is already done in
|
||||
// ApplicationLoader.onCreate() which is called before this broadcast is sended.
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
public class BuildVars {
|
||||
public static boolean DEBUG_VERSION = false;
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.IntentService;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Build;
|
||||
import android.system.Os;
|
||||
import android.system.StructStat;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class ClearCacheService extends IntentService {
|
||||
|
||||
public ClearCacheService() {
|
||||
super("ClearCacheService");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onHandleIntent(Intent intent) {
|
||||
ApplicationLoader.postInitApplication();
|
||||
|
||||
/*
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
|
||||
final int keepMedia = preferences.getInt("keep_media", 2);
|
||||
if (keepMedia == 2) {
|
||||
return;
|
||||
}
|
||||
Utilities.globalQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
long currentTime = System.currentTimeMillis();
|
||||
long diff = 60 * 60 * 1000 * 24 * (keepMedia == 0 ? 7 : 30);
|
||||
final HashMap<Integer, File> paths = ImageLoader.getInstance().createMediaPaths();
|
||||
for (HashMap.Entry<Integer, File> entry : paths.entrySet()) {
|
||||
if (entry.getKey() == FileLoader.MEDIA_DIR_CACHE) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
File[] array = entry.getValue().listFiles();
|
||||
if (array != null) {
|
||||
for (int b = 0; b < array.length; b++) {
|
||||
File f = array[b];
|
||||
if (f.isFile()) {
|
||||
if (f.getName().equals(".nomedia")) {
|
||||
continue;
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 21) {
|
||||
try {
|
||||
StructStat stat = Os.stat(f.getPath());
|
||||
if (stat.st_atime != 0) {
|
||||
if (stat.st_atime + diff < currentTime) {
|
||||
f.delete();
|
||||
}
|
||||
} else if (stat.st_mtime + diff < currentTime) {
|
||||
f.delete();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
} else if (f.lastModified() + diff < currentTime) {
|
||||
f.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
*/
|
||||
}
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.NetworkInfo;
|
||||
import android.os.PowerManager;
|
||||
|
||||
public class ConnectionsManager {
|
||||
|
||||
public final static int RequestFlagFailOnServerErrors = 2;
|
||||
|
||||
public final static int ConnectionStateConnecting = 1;
|
||||
public final static int ConnectionStateWaitingForNetwork = 2;
|
||||
public final static int ConnectionStateConnected = 3;
|
||||
public final static int ConnectionStateUpdating = 4;
|
||||
|
||||
private long lastPauseTime = System.currentTimeMillis();
|
||||
private boolean appPaused = true;
|
||||
private int lastClassGuid = 1;
|
||||
private PowerManager.WakeLock wakeLock = null;
|
||||
|
||||
private static volatile ConnectionsManager Instance = null;
|
||||
|
||||
public static ConnectionsManager getInstance() {
|
||||
ConnectionsManager localInstance = Instance;
|
||||
if (localInstance == null) {
|
||||
synchronized (ConnectionsManager.class) {
|
||||
localInstance = Instance;
|
||||
if (localInstance == null) {
|
||||
Instance = localInstance = new ConnectionsManager();
|
||||
}
|
||||
}
|
||||
}
|
||||
return localInstance;
|
||||
}
|
||||
|
||||
public ConnectionsManager() {
|
||||
try {
|
||||
PowerManager pm = (PowerManager) ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE);
|
||||
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
|
||||
wakeLock.setReferenceCounted(false);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
|
||||
public int getCurrentTime() {
|
||||
return MrMailbox.getCurrentTime();
|
||||
}
|
||||
|
||||
public void cancelRequest(int token, boolean notifyServer) {
|
||||
//native_cancelRequest(token, notifyServer);
|
||||
}
|
||||
|
||||
public void cleanup() {
|
||||
//native_cleanUp();
|
||||
}
|
||||
|
||||
public int getConnectionState() {
|
||||
return ConnectionStateWaitingForNetwork; // EDIT BY MR - we're always disconnected from the view of the caller
|
||||
/* EDIT BY MR
|
||||
if (connectionState == ConnectionStateConnected && isUpdating) {
|
||||
return ConnectionStateUpdating;
|
||||
}
|
||||
return connectionState;
|
||||
*/
|
||||
}
|
||||
|
||||
public void setPushConnectionEnabled(boolean value) {
|
||||
//native_setPushConnectionEnabled(value);
|
||||
}
|
||||
|
||||
public void init(String deviceModel, String systemVersion, String appVersion, String langCode, String configPath, String logPath, int userId, boolean enablePushConnection) {
|
||||
//native_init(version, layer, apiId, deviceModel, systemVersion, appVersion, langCode, configPath, logPath, userId, enablePushConnection);
|
||||
//checkConnection();
|
||||
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
//checkConnection();
|
||||
}
|
||||
};
|
||||
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
|
||||
ApplicationLoader.applicationContext.registerReceiver(networkStateReceiver, filter);
|
||||
}
|
||||
|
||||
public void resumeNetworkMaybe() {
|
||||
//native_resumeNetwork(true);
|
||||
}
|
||||
|
||||
public void setAppPaused(final boolean value, final boolean byScreenState) {
|
||||
if (!byScreenState) {
|
||||
appPaused = value;
|
||||
FileLog.d("messenger", "app paused = " + value);
|
||||
}
|
||||
if (value) {
|
||||
if (lastPauseTime == 0) {
|
||||
lastPauseTime = System.currentTimeMillis();
|
||||
}
|
||||
//native_pauseNetwork();
|
||||
} else {
|
||||
if (appPaused) {
|
||||
return;
|
||||
}
|
||||
FileLog.e("messenger", "reset app pause time");
|
||||
/*if (lastPauseTime != 0 && System.currentTimeMillis() - lastPauseTime > 5000) {
|
||||
ContactsController.getInstance().checkContacts();
|
||||
}*/
|
||||
lastPauseTime = 0;
|
||||
//native_resumeNetwork(false);
|
||||
}
|
||||
}
|
||||
|
||||
public int generateClassGuid() {
|
||||
return lastClassGuid++;
|
||||
}
|
||||
|
||||
public static boolean isRoaming() {
|
||||
try {
|
||||
ConnectivityManager cm = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
NetworkInfo netInfo = cm.getActiveNetworkInfo();
|
||||
if (netInfo != null) {
|
||||
return netInfo.isRoaming();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isConnectedToWiFi() {
|
||||
try {
|
||||
ConnectivityManager cm = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
NetworkInfo netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
|
||||
if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) {
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isNetworkOnline() {
|
||||
try {
|
||||
ConnectivityManager cm = (ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||
NetworkInfo netInfo = cm.getActiveNetworkInfo();
|
||||
if (netInfo != null && (netInfo.isConnectedOrConnecting() || netInfo.isAvailable())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
|
||||
|
||||
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
|
||||
return true;
|
||||
} else {
|
||||
netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
|
||||
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -92,7 +92,7 @@ public class ContactsController {
|
||||
pCur.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return allContacts;
|
||||
}
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.accounts.Account;
|
||||
import android.accounts.OperationCanceledException;
|
||||
import android.app.Service;
|
||||
import android.content.AbstractThreadedSyncAdapter;
|
||||
import android.content.ContentProviderClient;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SyncResult;
|
||||
import android.os.Bundle;
|
||||
import android.os.IBinder;
|
||||
|
||||
public class ContactsSyncAdapterService extends Service {
|
||||
private static SyncAdapterImpl sSyncAdapter = null;
|
||||
|
||||
public ContactsSyncAdapterService() {
|
||||
super();
|
||||
}
|
||||
|
||||
private static class SyncAdapterImpl extends AbstractThreadedSyncAdapter {
|
||||
private Context mContext;
|
||||
|
||||
public SyncAdapterImpl(Context context) {
|
||||
super(context, true);
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
|
||||
try {
|
||||
ContactsSyncAdapterService.performSync(mContext, account, extras, authority, provider, syncResult);
|
||||
} catch (OperationCanceledException e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return getSyncAdapter().getSyncAdapterBinder();
|
||||
}
|
||||
|
||||
private SyncAdapterImpl getSyncAdapter() {
|
||||
if (sSyncAdapter == null) {
|
||||
sSyncAdapter = new SyncAdapterImpl(this);
|
||||
}
|
||||
return sSyncAdapter;
|
||||
}
|
||||
|
||||
private static void performSync(Context context, Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult)
|
||||
throws OperationCanceledException {
|
||||
FileLog.d("messenger", "performSync: " + account.toString());
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ public class DispatchQueue extends Thread {
|
||||
handler.sendMessageDelayed(msg, delay);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -58,7 +58,7 @@ public class DispatchQueue extends Thread {
|
||||
syncLatch.await();
|
||||
handler.removeCallbacks(runnable);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ public class DispatchQueue extends Thread {
|
||||
handler.postDelayed(runnable, delay);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ public class DispatchQueue extends Thread {
|
||||
syncLatch.await();
|
||||
handler.removeCallbacksAndMessages(null);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
@@ -117,7 +117,7 @@ public class Emoji {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -158,7 +158,7 @@ public class Emoji {
|
||||
}
|
||||
});
|
||||
} catch (Throwable x) {
|
||||
FileLog.e("messenger", "Error loading emoji", x);
|
||||
//Log.i("DeltaChat", "Error loading emoji", x);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,7 +209,7 @@ public class Emoji {
|
||||
public static EmojiDrawable getEmojiDrawable(CharSequence code) {
|
||||
DrawableInfo info = rects.get(code);
|
||||
if (info == null) {
|
||||
FileLog.e("messenger", "No drawable for emoji " + code);
|
||||
//Log.i("DeltaChat", "No drawable for emoji " + code);
|
||||
return null;
|
||||
}
|
||||
EmojiDrawable ed = new EmojiDrawable(info);
|
||||
@@ -434,7 +434,7 @@ public class Emoji {
|
||||
// }
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// FileLog.e("messenger", e);
|
||||
//
|
||||
// return cs;
|
||||
// }
|
||||
return s;
|
||||
|
||||
@@ -1,443 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import java.io.RandomAccessFile;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class FileLoadOperation {
|
||||
|
||||
private static class RequestInfo {
|
||||
private int requestToken;
|
||||
private int offset;
|
||||
}
|
||||
|
||||
private final static int stateIdle = 0;
|
||||
private final static int stateDownloading = 1;
|
||||
private final static int stateFailed = 2;
|
||||
private final static int stateFinished = 3;
|
||||
|
||||
private final static int downloadChunkSize = 1024 * 32;
|
||||
private final static int downloadChunkSizeBig = 1024 * 128;
|
||||
private final static int maxDownloadRequests = 4;
|
||||
private final static int maxDownloadRequestsBig = 2;
|
||||
private final static int bigFileSizeFrom = 1024 * 1024;
|
||||
|
||||
private int datacenter_id;
|
||||
private TLRPC.InputFileLocation location;
|
||||
private volatile int state = stateIdle;
|
||||
private int downloadedBytes;
|
||||
private int totalBytesCount;
|
||||
private int bytesCountPadding;
|
||||
private FileLoadOperationDelegate delegate;
|
||||
private byte[] key;
|
||||
private byte[] iv;
|
||||
private int currentDownloadChunkSize;
|
||||
private int currentMaxDownloadRequests;
|
||||
private int requestsCount;
|
||||
private int renameRetryCount;
|
||||
|
||||
private int nextDownloadOffset;
|
||||
private ArrayList<RequestInfo> requestInfos;
|
||||
private ArrayList<RequestInfo> delayedRequestInfos;
|
||||
|
||||
private File cacheFileTemp;
|
||||
private File cacheFileFinal;
|
||||
private File cacheIvTemp;
|
||||
|
||||
private String ext;
|
||||
private RandomAccessFile fileOutputStream;
|
||||
private RandomAccessFile fiv;
|
||||
private File storePath;
|
||||
private File tempPath;
|
||||
private boolean isForceRequest;
|
||||
|
||||
public interface FileLoadOperationDelegate {
|
||||
void didFinishLoadingFile(FileLoadOperation operation, File finalFile);
|
||||
void didFailedLoadingFile(FileLoadOperation operation, int state);
|
||||
void didChangedLoadProgress(FileLoadOperation operation, float progress);
|
||||
}
|
||||
|
||||
public FileLoadOperation(TLRPC.FileLocation photoLocation, String extension, int size) {
|
||||
/*if (photoLocation instanceof TLRPC.TL_fileEncryptedLocation) {
|
||||
location = new TLRPC.TL_inputEncryptedFileLocation();
|
||||
location.id = photoLocation.volume_id;
|
||||
location.volume_id = photoLocation.volume_id;
|
||||
location.access_hash = photoLocation.secret;
|
||||
location.local_id = photoLocation.local_id;
|
||||
iv = new byte[32];
|
||||
System.arraycopy(photoLocation.iv, 0, iv, 0, iv.length);
|
||||
key = photoLocation.key;
|
||||
datacenter_id = photoLocation.dc_id;
|
||||
} else*/ if (photoLocation instanceof TLRPC.TL_fileLocation) {
|
||||
location = new TLRPC.TL_inputFileLocation();
|
||||
location.volume_id = photoLocation.volume_id;
|
||||
location.local_id = photoLocation.local_id;
|
||||
datacenter_id = photoLocation.dc_id;
|
||||
}
|
||||
totalBytesCount = size;
|
||||
ext = extension != null ? extension : "jpg";
|
||||
}
|
||||
|
||||
public FileLoadOperation(TLRPC.Document documentLocation) {
|
||||
try {
|
||||
/*if (documentLocation instanceof TLRPC.TL_documentEncrypted) {
|
||||
location = new TLRPC.TL_inputEncryptedFileLocation();
|
||||
location.id = documentLocation.id;
|
||||
location.access_hash = documentLocation.access_hash;
|
||||
datacenter_id = documentLocation.dc_id;
|
||||
iv = new byte[32];
|
||||
System.arraycopy(documentLocation.iv, 0, iv, 0, iv.length);
|
||||
key = documentLocation.key;
|
||||
} else*/ if (documentLocation instanceof TLRPC.TL_document) {
|
||||
location = new TLRPC.TL_inputDocumentFileLocation();
|
||||
location.id = documentLocation.id;
|
||||
location.access_hash = documentLocation.access_hash;
|
||||
datacenter_id = documentLocation.dc_id;
|
||||
}
|
||||
totalBytesCount = documentLocation.size;
|
||||
if (key != null) {
|
||||
int toAdd = 0;
|
||||
if (totalBytesCount % 16 != 0) {
|
||||
bytesCountPadding = 16 - totalBytesCount % 16;
|
||||
totalBytesCount += bytesCountPadding;
|
||||
}
|
||||
}
|
||||
ext = FileLoader.getDocumentFileName(documentLocation);
|
||||
int idx;
|
||||
if (ext == null || (idx = ext.lastIndexOf('.')) == -1) {
|
||||
ext = "";
|
||||
} else {
|
||||
ext = ext.substring(idx);
|
||||
}
|
||||
if (ext.length() <= 1) {
|
||||
if (documentLocation.mime_type != null) {
|
||||
switch (documentLocation.mime_type) {
|
||||
case "video/mp4":
|
||||
ext = ".mp4";
|
||||
break;
|
||||
case "audio/ogg":
|
||||
ext = ".ogg";
|
||||
break;
|
||||
default:
|
||||
ext = "";
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
ext = "";
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
state = stateFailed;
|
||||
cleanup();
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void setForceRequest(boolean forceRequest) {
|
||||
isForceRequest = forceRequest;
|
||||
}
|
||||
|
||||
public boolean isForceRequest() {
|
||||
return isForceRequest;
|
||||
}
|
||||
|
||||
public void setPaths(File store, File temp) {
|
||||
storePath = store;
|
||||
tempPath = temp;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
if (state != stateIdle) {
|
||||
return;
|
||||
}
|
||||
currentDownloadChunkSize = totalBytesCount >= bigFileSizeFrom ? downloadChunkSizeBig : downloadChunkSize;
|
||||
currentMaxDownloadRequests = totalBytesCount >= bigFileSizeFrom ? maxDownloadRequestsBig : maxDownloadRequests;
|
||||
requestInfos = new ArrayList<>(currentMaxDownloadRequests);
|
||||
delayedRequestInfos = new ArrayList<>(currentMaxDownloadRequests - 1);
|
||||
state = stateDownloading;
|
||||
if (location == null) {
|
||||
cleanup();
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
String fileNameFinal;
|
||||
String fileNameTemp;
|
||||
String fileNameIv = null;
|
||||
if (location.volume_id != 0 && location.local_id != 0) {
|
||||
fileNameTemp = location.volume_id + "_" + location.local_id + ".temp";
|
||||
fileNameFinal = location.volume_id + "_" + location.local_id + "." + ext;
|
||||
if (key != null) {
|
||||
fileNameIv = location.volume_id + "_" + location.local_id + ".iv";
|
||||
}
|
||||
if (datacenter_id == Integer.MIN_VALUE || location.volume_id == Integer.MIN_VALUE || datacenter_id == 0) {
|
||||
cleanup();
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
fileNameTemp = datacenter_id + "_" + location.id + ".temp";
|
||||
fileNameFinal = datacenter_id + "_" + location.id + ext;
|
||||
if (key != null) {
|
||||
fileNameIv = datacenter_id + "_" + location.id + ".iv";
|
||||
}
|
||||
if (datacenter_id == 0 || location.id == 0) {
|
||||
cleanup();
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
cacheFileFinal = new File(storePath, fileNameFinal);
|
||||
boolean exist = cacheFileFinal.exists();
|
||||
if (exist && totalBytesCount != 0 && totalBytesCount != cacheFileFinal.length()) {
|
||||
cacheFileFinal.delete();
|
||||
}
|
||||
|
||||
if (!cacheFileFinal.exists()) {
|
||||
cacheFileTemp = new File(tempPath, fileNameTemp);
|
||||
if (cacheFileTemp.exists()) {
|
||||
downloadedBytes = (int) cacheFileTemp.length();
|
||||
nextDownloadOffset = downloadedBytes = downloadedBytes / currentDownloadChunkSize * currentDownloadChunkSize;
|
||||
}
|
||||
|
||||
if (BuildVars.DEBUG_VERSION) {
|
||||
FileLog.d("messenger", "start loading file to temp = " + cacheFileTemp + " final = " + cacheFileFinal);
|
||||
}
|
||||
|
||||
if (fileNameIv != null) {
|
||||
cacheIvTemp = new File(tempPath, fileNameIv);
|
||||
try {
|
||||
fiv = new RandomAccessFile(cacheIvTemp, "rws");
|
||||
long len = cacheIvTemp.length();
|
||||
if (len > 0 && len % 32 == 0) {
|
||||
fiv.read(iv, 0, 32);
|
||||
} else {
|
||||
downloadedBytes = 0;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
downloadedBytes = 0;
|
||||
}
|
||||
}
|
||||
try {
|
||||
fileOutputStream = new RandomAccessFile(cacheFileTemp, "rws");
|
||||
if (downloadedBytes != 0) {
|
||||
fileOutputStream.seek(downloadedBytes);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
if (fileOutputStream == null) {
|
||||
cleanup();
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (totalBytesCount != 0 && downloadedBytes == totalBytesCount) {
|
||||
try {
|
||||
onFinishLoadingFile();
|
||||
} catch (Exception e) {
|
||||
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
|
||||
}
|
||||
} else {
|
||||
startDownloadRequest();
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
onFinishLoadingFile();
|
||||
} catch (Exception e) {
|
||||
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (state == stateFinished || state == stateFailed) {
|
||||
return;
|
||||
}
|
||||
state = stateFailed;
|
||||
cleanup();
|
||||
if (requestInfos != null) {
|
||||
for (int a = 0; a < requestInfos.size(); a++) {
|
||||
RequestInfo requestInfo = requestInfos.get(a);
|
||||
if (requestInfo.requestToken != 0) {
|
||||
ConnectionsManager.getInstance().cancelRequest(requestInfo.requestToken, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
delegate.didFailedLoadingFile(FileLoadOperation.this, 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void cleanup() {
|
||||
try {
|
||||
if (fileOutputStream != null) {
|
||||
try {
|
||||
fileOutputStream.getChannel().close();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
fileOutputStream.close();
|
||||
fileOutputStream = null;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
|
||||
try {
|
||||
if (fiv != null) {
|
||||
fiv.close();
|
||||
fiv = null;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
if (delayedRequestInfos != null) {
|
||||
for (int a = 0; a < delayedRequestInfos.size(); a++) {
|
||||
RequestInfo requestInfo = delayedRequestInfos.get(a);
|
||||
/*if (requestInfo.response != null) {
|
||||
requestInfo.response.disableFree = false;
|
||||
requestInfo.response.freeResources();
|
||||
}*/
|
||||
}
|
||||
delayedRequestInfos.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private void onFinishLoadingFile() throws Exception {
|
||||
if (state != stateDownloading) {
|
||||
return;
|
||||
}
|
||||
state = stateFinished;
|
||||
cleanup();
|
||||
if (cacheIvTemp != null) {
|
||||
cacheIvTemp.delete();
|
||||
cacheIvTemp = null;
|
||||
}
|
||||
if (cacheFileTemp != null) {
|
||||
boolean renameResult = cacheFileTemp.renameTo(cacheFileFinal);
|
||||
if (!renameResult) {
|
||||
if (BuildVars.DEBUG_VERSION) {
|
||||
FileLog.e("messenger", "unable to rename temp = " + cacheFileTemp + " to final = " + cacheFileFinal + " retry = " + renameRetryCount);
|
||||
}
|
||||
renameRetryCount++;
|
||||
if (renameRetryCount < 3) {
|
||||
state = stateDownloading;
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
onFinishLoadingFile();
|
||||
} catch (Exception e) {
|
||||
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
|
||||
}
|
||||
}
|
||||
}, 200);
|
||||
return;
|
||||
}
|
||||
cacheFileFinal = cacheFileTemp;
|
||||
}
|
||||
}
|
||||
if (BuildVars.DEBUG_VERSION) {
|
||||
FileLog.e("messenger", "finished downloading file to " + cacheFileFinal);
|
||||
}
|
||||
delegate.didFinishLoadingFile(FileLoadOperation.this, cacheFileFinal);
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void startDownloadRequest() {
|
||||
if (state != stateDownloading || totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount || requestInfos.size() + delayedRequestInfos.size() >= currentMaxDownloadRequests) {
|
||||
return;
|
||||
}
|
||||
int count = 1;
|
||||
if (totalBytesCount > 0) {
|
||||
count = Math.max(0, currentMaxDownloadRequests - requestInfos.size() - delayedRequestInfos.size());
|
||||
}
|
||||
|
||||
for (int a = 0; a < count; a++) {
|
||||
if (totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount) {
|
||||
break;
|
||||
}
|
||||
boolean isLast = totalBytesCount <= 0 || a == count - 1 || totalBytesCount > 0 && nextDownloadOffset + currentDownloadChunkSize >= totalBytesCount;
|
||||
//TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
|
||||
//req.location = location;
|
||||
//req.offset = nextDownloadOffset;
|
||||
//req.limit = currentDownloadChunkSize;
|
||||
nextDownloadOffset += currentDownloadChunkSize;
|
||||
|
||||
final RequestInfo requestInfo = new RequestInfo();
|
||||
requestInfos.add(requestInfo);
|
||||
requestInfo.offset = nextDownloadOffset;
|
||||
requestInfo.requestToken = 0;/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
|
||||
@Override
|
||||
public void run(TLObject response, TLRPC.TL_error error) {
|
||||
requestInfo.response = (TLRPC.TL_upload_file) response;
|
||||
processRequestResult(requestInfo, error);
|
||||
}
|
||||
}, null, (isForceRequest ? ConnectionsManager.RequestFlagForceDownload : 0) | ConnectionsManager.RequestFlagFailOnServerErrors, datacenter_id, requestsCount % 2 == 0 ? ConnectionsManager.ConnectionTypeDownload : ConnectionsManager.ConnectionTypeDownload2, isLast);*/
|
||||
requestsCount++;
|
||||
}
|
||||
}
|
||||
|
||||
public void setDelegate(FileLoadOperationDelegate delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
}
|
||||
@@ -32,20 +32,6 @@ import java.util.concurrent.Semaphore;
|
||||
|
||||
public class FileLoader {
|
||||
|
||||
public interface FileLoaderDelegate {
|
||||
void fileUploadProgressChanged(String location, float progress, boolean isEncrypted);
|
||||
|
||||
void fileDidUploaded(String location, TLRPC.InputFile inputFile, TLRPC.InputEncryptedFile inputEncryptedFile, byte[] key, byte[] iv, long totalFileSize);
|
||||
|
||||
void fileDidFailedUpload(String location, boolean isEncrypted);
|
||||
|
||||
void fileDidLoaded(String location, File finalFile, int type);
|
||||
|
||||
void fileDidFailedLoad(String location, int state);
|
||||
|
||||
void fileLoadProgressChanged(String location, float progress);
|
||||
}
|
||||
|
||||
public static final int MEDIA_DIR_IMAGE = 0;
|
||||
public static final int MEDIA_DIR_AUDIO = 1;
|
||||
public static final int MEDIA_DIR_VIDEO = 2;
|
||||
@@ -53,25 +39,6 @@ public class FileLoader {
|
||||
public static final int MEDIA_DIR_CACHE = 4;
|
||||
|
||||
private HashMap<Integer, File> mediaDirs = null;
|
||||
private volatile DispatchQueue fileLoaderQueue = new DispatchQueue("fileUploadQueue");
|
||||
|
||||
private LinkedList<FileUploadOperation> uploadOperationQueue = new LinkedList<>();
|
||||
private LinkedList<FileUploadOperation> uploadSmallOperationQueue = new LinkedList<>();
|
||||
private LinkedList<FileLoadOperation> loadOperationQueue = new LinkedList<>();
|
||||
private LinkedList<FileLoadOperation> audioLoadOperationQueue = new LinkedList<>();
|
||||
private LinkedList<FileLoadOperation> photoLoadOperationQueue = new LinkedList<>();
|
||||
private ConcurrentHashMap<String, FileUploadOperation> uploadOperationPaths = new ConcurrentHashMap<>();
|
||||
private ConcurrentHashMap<String, FileUploadOperation> uploadOperationPathsEnc = new ConcurrentHashMap<>();
|
||||
private ConcurrentHashMap<String, FileLoadOperation> loadOperationPaths = new ConcurrentHashMap<>();
|
||||
private HashMap<String, Long> uploadSizes = new HashMap<>();
|
||||
|
||||
private FileLoaderDelegate delegate = null;
|
||||
|
||||
private int currentLoadOperationsCount = 0;
|
||||
private int currentAudioLoadOperationsCount = 0;
|
||||
private int currentPhotoLoadOperationsCount = 0;
|
||||
private int currentUploadOperationsCount = 0;
|
||||
private int currentUploadSmallOperationsCount = 0;
|
||||
|
||||
private static volatile FileLoader Instance = null;
|
||||
|
||||
@@ -92,12 +59,6 @@ public class FileLoader {
|
||||
mediaDirs = dirs;
|
||||
}
|
||||
|
||||
/*
|
||||
public File checkDirectory(int type) {
|
||||
return mediaDirs.get(type);
|
||||
}
|
||||
*/
|
||||
|
||||
public File getDirectory(int type) { // always returns the cache directory as this is the only one set in mediaDirs[] - we do not use the other directories at the moment
|
||||
File dir = mediaDirs.get(type);
|
||||
if (dir == null && type != MEDIA_DIR_CACHE) {
|
||||
@@ -113,411 +74,8 @@ public class FileLoader {
|
||||
return dir;
|
||||
}
|
||||
|
||||
/*
|
||||
public void checkUploadNewDataAvailable(final String location, final boolean encrypted, final long finalSize) {
|
||||
fileLoaderQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
FileUploadOperation operation;
|
||||
if (encrypted) {
|
||||
operation = uploadOperationPathsEnc.get(location);
|
||||
} else {
|
||||
operation = uploadOperationPaths.get(location);
|
||||
}
|
||||
if (operation != null) {
|
||||
operation.checkNewDataAvailable(finalSize);
|
||||
} else if (finalSize != 0) {
|
||||
uploadSizes.put(location, finalSize);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
*/
|
||||
|
||||
public void uploadFile(final String location, final boolean encrypted, final boolean small) {
|
||||
uploadFile(location, encrypted, small, 0);
|
||||
}
|
||||
|
||||
public void uploadFile(final String location, final boolean encrypted, final boolean small, final int estimatedSize) {
|
||||
if (location == null) {
|
||||
return;
|
||||
}
|
||||
fileLoaderQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (encrypted) {
|
||||
if (uploadOperationPathsEnc.containsKey(location)) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (uploadOperationPaths.containsKey(location)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
int esimated = estimatedSize;
|
||||
if (esimated != 0) {
|
||||
Long finalSize = uploadSizes.get(location);
|
||||
if (finalSize != null) {
|
||||
esimated = 0;
|
||||
uploadSizes.remove(location);
|
||||
}
|
||||
}
|
||||
FileUploadOperation operation = new FileUploadOperation(location, encrypted, esimated);
|
||||
if (encrypted) {
|
||||
uploadOperationPathsEnc.put(location, operation);
|
||||
} else {
|
||||
uploadOperationPaths.put(location, operation);
|
||||
}
|
||||
operation.delegate = new FileUploadOperation.FileUploadOperationDelegate() {
|
||||
@Override
|
||||
public void didFinishUploadingFile(final FileUploadOperation operation, final TLRPC.InputFile inputFile, final TLRPC.InputEncryptedFile inputEncryptedFile, final byte[] key, final byte[] iv) {
|
||||
fileLoaderQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (encrypted) {
|
||||
uploadOperationPathsEnc.remove(location);
|
||||
} else {
|
||||
uploadOperationPaths.remove(location);
|
||||
}
|
||||
if (small) {
|
||||
currentUploadSmallOperationsCount--;
|
||||
if (currentUploadSmallOperationsCount < 1) {
|
||||
FileUploadOperation operation = uploadSmallOperationQueue.poll();
|
||||
if (operation != null) {
|
||||
currentUploadSmallOperationsCount++;
|
||||
operation.start();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
currentUploadOperationsCount--;
|
||||
if (currentUploadOperationsCount < 1) {
|
||||
FileUploadOperation operation = uploadOperationQueue.poll();
|
||||
if (operation != null) {
|
||||
currentUploadOperationsCount++;
|
||||
operation.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (delegate != null) {
|
||||
delegate.fileDidUploaded(location, inputFile, inputEncryptedFile, key, iv, operation.getTotalFileSize());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didFailedUploadingFile(final FileUploadOperation operation) {
|
||||
fileLoaderQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (encrypted) {
|
||||
uploadOperationPathsEnc.remove(location);
|
||||
} else {
|
||||
uploadOperationPaths.remove(location);
|
||||
}
|
||||
if (delegate != null) {
|
||||
delegate.fileDidFailedUpload(location, encrypted);
|
||||
}
|
||||
if (small) {
|
||||
currentUploadSmallOperationsCount--;
|
||||
if (currentUploadSmallOperationsCount < 1) {
|
||||
FileUploadOperation operation = uploadSmallOperationQueue.poll();
|
||||
if (operation != null) {
|
||||
currentUploadSmallOperationsCount++;
|
||||
operation.start();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
currentUploadOperationsCount--;
|
||||
if (currentUploadOperationsCount < 1) {
|
||||
FileUploadOperation operation = uploadOperationQueue.poll();
|
||||
if (operation != null) {
|
||||
currentUploadOperationsCount++;
|
||||
operation.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didChangedUploadProgress(FileUploadOperation operation, final float progress) {
|
||||
if (delegate != null) {
|
||||
delegate.fileUploadProgressChanged(location, progress, encrypted);
|
||||
}
|
||||
}
|
||||
};
|
||||
if (small) {
|
||||
if (currentUploadSmallOperationsCount < 1) {
|
||||
currentUploadSmallOperationsCount++;
|
||||
operation.start();
|
||||
} else {
|
||||
uploadSmallOperationQueue.add(operation);
|
||||
}
|
||||
} else {
|
||||
if (currentUploadOperationsCount < 1) {
|
||||
currentUploadOperationsCount++;
|
||||
operation.start();
|
||||
} else {
|
||||
uploadOperationQueue.add(operation);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void cancelLoadFile(TLRPC.Document document) {
|
||||
cancelLoadFile(document, null, null);
|
||||
}
|
||||
|
||||
public void cancelLoadFile(TLRPC.PhotoSize photo) {
|
||||
cancelLoadFile(null, photo.location, null);
|
||||
}
|
||||
|
||||
public void cancelLoadFile(TLRPC.FileLocation location, String ext) {
|
||||
cancelLoadFile(null, location, ext);
|
||||
}
|
||||
|
||||
private void cancelLoadFile(final TLRPC.Document document, final TLRPC.FileLocation location, final String locationExt) {
|
||||
if (location == null && document == null) {
|
||||
return;
|
||||
}
|
||||
fileLoaderQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
String fileName = null;
|
||||
if (location != null) {
|
||||
fileName = getAttachFileName(location, locationExt);
|
||||
} else if (document != null) {
|
||||
fileName = getAttachFileName(document);
|
||||
}
|
||||
if (fileName == null) {
|
||||
return;
|
||||
}
|
||||
FileLoadOperation operation = loadOperationPaths.remove(fileName);
|
||||
if (operation != null) {
|
||||
if (MessageObject.isVoiceDocument(document)) {
|
||||
audioLoadOperationQueue.remove(operation);
|
||||
} else if (location != null) {
|
||||
photoLoadOperationQueue.remove(operation);
|
||||
} else {
|
||||
loadOperationQueue.remove(operation);
|
||||
}
|
||||
operation.cancel();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean isLoadingFile(final String fileName) {
|
||||
final Semaphore semaphore = new Semaphore(0);
|
||||
final Boolean[] result = new Boolean[1];
|
||||
fileLoaderQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
result[0] = loadOperationPaths.containsKey(fileName);
|
||||
semaphore.release();
|
||||
}
|
||||
});
|
||||
try {
|
||||
semaphore.acquire();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return result[0];
|
||||
}
|
||||
|
||||
public void loadFile(TLRPC.PhotoSize photo, String ext, boolean cacheOnly) {
|
||||
loadFile(null, photo.location, ext, photo.size, false, cacheOnly || (photo != null && photo.size == 0 || photo.location.key != null));
|
||||
}
|
||||
|
||||
public void loadFile(TLRPC.Document document, boolean force, boolean cacheOnly) {
|
||||
loadFile(document, null, null, 0, force, cacheOnly || document != null && document.key != null);
|
||||
}
|
||||
|
||||
public void loadFile(TLRPC.FileLocation location, String ext, int size, boolean cacheOnly) {
|
||||
loadFile(null, location, ext, size, true, cacheOnly || size == 0 || (location != null && location.key != null));
|
||||
}
|
||||
|
||||
private void loadFile(final TLRPC.Document document, final TLRPC.FileLocation location, final String locationExt, final int locationSize, final boolean force, final boolean cacheOnly) {
|
||||
fileLoaderQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
String fileName = null;
|
||||
if (location != null) {
|
||||
fileName = getAttachFileName(location, locationExt);
|
||||
} else if (document != null) {
|
||||
fileName = getAttachFileName(document);
|
||||
}
|
||||
if (fileName == null || fileName.contains("" + Integer.MIN_VALUE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
FileLoadOperation operation;
|
||||
operation = loadOperationPaths.get(fileName);
|
||||
if (operation != null) {
|
||||
if (force) {
|
||||
LinkedList<FileLoadOperation> downloadQueue;
|
||||
if (MessageObject.isVoiceDocument(document)) {
|
||||
downloadQueue = audioLoadOperationQueue;
|
||||
} else if (location != null) {
|
||||
downloadQueue = photoLoadOperationQueue;
|
||||
} else {
|
||||
downloadQueue = loadOperationQueue;
|
||||
}
|
||||
if (downloadQueue != null) {
|
||||
int index = downloadQueue.indexOf(operation);
|
||||
if (index != -1) {
|
||||
downloadQueue.remove(index);
|
||||
downloadQueue.add(0, operation);
|
||||
operation.setForceRequest(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
File tempDir = getDirectory(MEDIA_DIR_CACHE);
|
||||
File storeDir = tempDir;
|
||||
int type = MEDIA_DIR_CACHE;
|
||||
|
||||
if (location != null) {
|
||||
operation = new FileLoadOperation(location, locationExt, locationSize);
|
||||
type = MEDIA_DIR_IMAGE;
|
||||
} else if (document != null) {
|
||||
operation = new FileLoadOperation(document);
|
||||
if (MessageObject.isVoiceDocument(document)) {
|
||||
type = MEDIA_DIR_AUDIO;
|
||||
} else if (MessageObject.isVideoDocument(document)) {
|
||||
type = MEDIA_DIR_VIDEO;
|
||||
} else {
|
||||
type = MEDIA_DIR_DOCUMENT;
|
||||
}
|
||||
}
|
||||
if (!cacheOnly) {
|
||||
storeDir = getDirectory(type);
|
||||
}
|
||||
operation.setPaths(storeDir, tempDir);
|
||||
|
||||
final String finalFileName = fileName;
|
||||
final int finalType = type;
|
||||
loadOperationPaths.put(fileName, operation);
|
||||
operation.setDelegate(new FileLoadOperation.FileLoadOperationDelegate() {
|
||||
@Override
|
||||
public void didFinishLoadingFile(FileLoadOperation operation, File finalFile) {
|
||||
if (delegate != null) {
|
||||
delegate.fileDidLoaded(finalFileName, finalFile, finalType);
|
||||
}
|
||||
checkDownloadQueue(document, location, finalFileName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didFailedLoadingFile(FileLoadOperation operation, int canceled) {
|
||||
checkDownloadQueue(document, location, finalFileName);
|
||||
if (delegate != null) {
|
||||
delegate.fileDidFailedLoad(finalFileName, canceled);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didChangedLoadProgress(FileLoadOperation operation, float progress) {
|
||||
if (delegate != null) {
|
||||
delegate.fileLoadProgressChanged(finalFileName, progress);
|
||||
}
|
||||
}
|
||||
});
|
||||
int maxCount = force ? 3 : 1;
|
||||
if (type == MEDIA_DIR_AUDIO) {
|
||||
if (currentAudioLoadOperationsCount < maxCount) {
|
||||
currentAudioLoadOperationsCount++;
|
||||
operation.start();
|
||||
} else {
|
||||
if (force) {
|
||||
audioLoadOperationQueue.add(0, operation);
|
||||
} else {
|
||||
audioLoadOperationQueue.add(operation);
|
||||
}
|
||||
}
|
||||
} else if (location != null) {
|
||||
if (currentPhotoLoadOperationsCount < maxCount) {
|
||||
currentPhotoLoadOperationsCount++;
|
||||
operation.start();
|
||||
} else {
|
||||
if (force) {
|
||||
photoLoadOperationQueue.add(0, operation);
|
||||
} else {
|
||||
photoLoadOperationQueue.add(operation);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (currentLoadOperationsCount < maxCount) {
|
||||
currentLoadOperationsCount++;
|
||||
operation.start();
|
||||
} else {
|
||||
if (force) {
|
||||
loadOperationQueue.add(0, operation);
|
||||
} else {
|
||||
loadOperationQueue.add(operation);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void checkDownloadQueue(final TLRPC.Document document, final TLRPC.FileLocation location, final String arg1) {
|
||||
fileLoaderQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
loadOperationPaths.remove(arg1);
|
||||
FileLoadOperation operation;
|
||||
if (MessageObject.isVoiceDocument(document)) {
|
||||
currentAudioLoadOperationsCount--;
|
||||
if (!audioLoadOperationQueue.isEmpty()) {
|
||||
operation = audioLoadOperationQueue.get(0);
|
||||
int maxCount = operation.isForceRequest() ? 3 : 1;
|
||||
if (currentAudioLoadOperationsCount < maxCount) {
|
||||
operation = audioLoadOperationQueue.poll();
|
||||
if (operation != null) {
|
||||
currentAudioLoadOperationsCount++;
|
||||
operation.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (location != null) {
|
||||
currentPhotoLoadOperationsCount--;
|
||||
if (!photoLoadOperationQueue.isEmpty()) {
|
||||
operation = photoLoadOperationQueue.get(0);
|
||||
int maxCount = operation.isForceRequest() ? 3 : 1;
|
||||
if (currentPhotoLoadOperationsCount < maxCount) {
|
||||
operation = photoLoadOperationQueue.poll();
|
||||
if (operation != null) {
|
||||
currentPhotoLoadOperationsCount++;
|
||||
operation.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
currentLoadOperationsCount--;
|
||||
if (!loadOperationQueue.isEmpty()) {
|
||||
operation = loadOperationQueue.get(0);
|
||||
int maxCount = operation.isForceRequest() ? 3 : 1;
|
||||
if (currentLoadOperationsCount < maxCount) {
|
||||
operation = loadOperationQueue.poll();
|
||||
if (operation != null) {
|
||||
currentLoadOperationsCount++;
|
||||
operation.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setDelegate(FileLoaderDelegate delegate) {
|
||||
this.delegate = delegate;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static String getMessageFileName(TLRPC.Message message) {
|
||||
|
||||
@@ -23,8 +23,6 @@
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import com.b44t.messenger.time.FastDateFormat;
|
||||
|
||||
import java.io.File;
|
||||
@@ -37,7 +35,6 @@ public class FileLog {
|
||||
private FastDateFormat dateFormat = null;
|
||||
private DispatchQueue logQueue = null;
|
||||
private File currentFile = null;
|
||||
private File networkFile = null;
|
||||
|
||||
private static volatile FileLog Instance = null;
|
||||
public static FileLog getInstance() {
|
||||
@@ -54,10 +51,7 @@ public class FileLog {
|
||||
}
|
||||
|
||||
public FileLog() {
|
||||
if (!BuildVars.DEBUG_VERSION) {
|
||||
return;
|
||||
}
|
||||
dateFormat = FastDateFormat.getInstance("dd_MM_yyyy_HH_mm_ss", Locale.US);
|
||||
dateFormat = FastDateFormat.getInstance("yyyyMMdd_HHmmss", Locale.US);
|
||||
try {
|
||||
File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
|
||||
if (sdCard == null) {
|
||||
@@ -81,37 +75,14 @@ public class FileLog {
|
||||
}
|
||||
}
|
||||
|
||||
public static String getNetworkLogPath() {
|
||||
if (!BuildVars.DEBUG_VERSION) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
|
||||
if (sdCard == null) {
|
||||
return "";
|
||||
}
|
||||
File dir = new File(sdCard.getAbsolutePath() + "/logs");
|
||||
dir.mkdirs();
|
||||
getInstance().networkFile = new File(dir, getInstance().dateFormat.format(System.currentTimeMillis()) + "_net.txt");
|
||||
return getInstance().networkFile.getAbsolutePath();
|
||||
} catch (Throwable e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static void e(final String tag, final String message, final Throwable exception) {
|
||||
if (!BuildVars.DEBUG_VERSION) {
|
||||
return;
|
||||
}
|
||||
Log.e(tag, message, exception);
|
||||
private static void log(final String what, final String tag, final String message)
|
||||
{
|
||||
if (getInstance().streamWriter != null) {
|
||||
getInstance().logQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
getInstance().streamWriter.write(getInstance().dateFormat.format(System.currentTimeMillis()) + " E/" + tag + "﹕ " + message + "\n");
|
||||
getInstance().streamWriter.write(exception.toString());
|
||||
getInstance().streamWriter.write(getInstance().dateFormat.format(System.currentTimeMillis()) + " " + what + "/" + tag + ": " + message + "\n");
|
||||
getInstance().streamWriter.flush();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
@@ -122,109 +93,14 @@ public class FileLog {
|
||||
}
|
||||
|
||||
public static void e(final String tag, final String message) {
|
||||
if (!BuildVars.DEBUG_VERSION) {
|
||||
return;
|
||||
}
|
||||
Log.e(tag, message);
|
||||
if (getInstance().streamWriter != null) {
|
||||
getInstance().logQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
getInstance().streamWriter.write(getInstance().dateFormat.format(System.currentTimeMillis()) + " E/" + tag + "﹕ " + message + "\n");
|
||||
getInstance().streamWriter.flush();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static void e(final String tag, final Throwable e) {
|
||||
if (!BuildVars.DEBUG_VERSION) {
|
||||
return;
|
||||
}
|
||||
e.printStackTrace();
|
||||
if (getInstance().streamWriter != null) {
|
||||
getInstance().logQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
getInstance().streamWriter.write(getInstance().dateFormat.format(System.currentTimeMillis()) + " E/" + tag + "﹕ " + e + "\n");
|
||||
StackTraceElement[] stack = e.getStackTrace();
|
||||
for (int a = 0; a < stack.length; a++) {
|
||||
getInstance().streamWriter.write(getInstance().dateFormat.format(System.currentTimeMillis()) + " E/" + tag + "﹕ " + stack[a] + "\n");
|
||||
}
|
||||
getInstance().streamWriter.flush();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void d(final String tag, final String message) {
|
||||
if (!BuildVars.DEBUG_VERSION) {
|
||||
return;
|
||||
}
|
||||
Log.d(tag, message);
|
||||
if (getInstance().streamWriter != null) {
|
||||
getInstance().logQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
getInstance().streamWriter.write(getInstance().dateFormat.format(System.currentTimeMillis()) + " D/" + tag + "﹕ " + message + "\n");
|
||||
getInstance().streamWriter.flush();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
log("E", tag, message);
|
||||
}
|
||||
|
||||
public static void w(final String tag, final String message) {
|
||||
if (!BuildVars.DEBUG_VERSION) {
|
||||
return;
|
||||
}
|
||||
Log.w(tag, message);
|
||||
if (getInstance().streamWriter != null) {
|
||||
getInstance().logQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
getInstance().streamWriter.write(getInstance().dateFormat.format(System.currentTimeMillis()) + " W/" + tag + ": " + message + "\n");
|
||||
getInstance().streamWriter.flush();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
log("W", tag, message);
|
||||
}
|
||||
|
||||
public static void cleanupLogs() {
|
||||
File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
|
||||
if (sdCard == null) {
|
||||
return;
|
||||
}
|
||||
File dir = new File (sdCard.getAbsolutePath() + "/logs");
|
||||
File[] files = dir.listFiles();
|
||||
if (files != null) {
|
||||
for (int a = 0; a < files.length; a++) {
|
||||
File file = files[a];
|
||||
if (getInstance().currentFile != null && file.getAbsolutePath().equals(getInstance().currentFile.getAbsolutePath())) {
|
||||
continue;
|
||||
}
|
||||
if (getInstance().networkFile != null && file.getAbsolutePath().equals(getInstance().networkFile.getAbsolutePath())) {
|
||||
continue;
|
||||
}
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
public static void i(final String tag, final String message) {
|
||||
log("I", tag, message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
|
||||
public class FileUploadOperation {
|
||||
|
||||
public int state = 0;
|
||||
public FileUploadOperationDelegate delegate;
|
||||
private int requestToken = 0;
|
||||
private long totalFileSize = 0;
|
||||
private boolean isEncrypted = false;
|
||||
private int estimatedSize = 0;
|
||||
private FileInputStream stream;
|
||||
|
||||
public interface FileUploadOperationDelegate {
|
||||
void didFinishUploadingFile(FileUploadOperation operation, TLRPC.InputFile inputFile, TLRPC.InputEncryptedFile inputEncryptedFile, byte[] key, byte[] iv);
|
||||
void didFailedUploadingFile(FileUploadOperation operation);
|
||||
void didChangedUploadProgress(FileUploadOperation operation, float progress);
|
||||
}
|
||||
|
||||
public FileUploadOperation(String location, boolean encrypted, int estimated) {
|
||||
isEncrypted = encrypted;
|
||||
estimatedSize = estimated;
|
||||
}
|
||||
|
||||
public long getTotalFileSize() {
|
||||
return totalFileSize;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
if (state == 3) {
|
||||
return;
|
||||
}
|
||||
state = 2;
|
||||
if (requestToken != 0) {
|
||||
ConnectionsManager.getInstance().cancelRequest(requestToken, true);
|
||||
}
|
||||
delegate.didFailedUploadingFile(this);
|
||||
cleanup();
|
||||
}
|
||||
|
||||
private void cleanup() {
|
||||
}
|
||||
|
||||
/*
|
||||
protected void checkNewDataAvailable(final long finalSize) {
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (estimatedSize != 0 && finalSize != 0) {
|
||||
estimatedSize = 0;
|
||||
totalFileSize = finalSize;
|
||||
totalPartsCount = (int) (totalFileSize + uploadChunkSize - 1) / uploadChunkSize;
|
||||
if (started) {
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("uploadinfo", Activity.MODE_PRIVATE);
|
||||
storeFileUploadInfo(preferences);
|
||||
}
|
||||
}
|
||||
if (requestToken == 0) {
|
||||
startUploadRequest();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -371,12 +371,10 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
|
||||
setImageBackup.ext = currentExt;
|
||||
setImageBackup.cacheOnly = currentCacheOnly;
|
||||
}
|
||||
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReplacedPhotoInMemCache);
|
||||
clearImage();
|
||||
}
|
||||
|
||||
public boolean onAttachedToWindow() {
|
||||
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didReplacedPhotoInMemCache);
|
||||
if (setImageBackup != null && (setImageBackup.fileLocation != null || setImageBackup.httpUrl != null || setImageBackup.thumbLocation != null || setImageBackup.thumb != null)) {
|
||||
setImage(setImageBackup.fileLocation, setImageBackup.httpUrl, setImageBackup.filter, setImageBackup.thumb, setImageBackup.thumbLocation, setImageBackup.thumbFilter, setImageBackup.size, setImageBackup.ext, setImageBackup.cacheOnly);
|
||||
return true;
|
||||
@@ -485,7 +483,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
|
||||
currentThumbKey = null;
|
||||
}
|
||||
setImage(currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheOnly);
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
canvas.restore();
|
||||
} else {
|
||||
@@ -530,7 +528,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
|
||||
currentThumbKey = null;
|
||||
}
|
||||
setImage(currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheOnly);
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -567,7 +565,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
|
||||
currentThumbKey = null;
|
||||
}
|
||||
setImage(currentImageLocation, currentHttpUrl, currentFilter, currentThumb, currentThumbLocation, currentThumbFilter, currentSize, currentExt, currentCacheOnly);
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
canvas.restore();
|
||||
@@ -582,7 +580,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
|
||||
drawable.setAlpha(alpha);
|
||||
drawable.draw(canvas);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -664,7 +662,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
|
||||
checkAlphaAnimation(animationNotReady);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1058,26 +1056,6 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (id == NotificationCenter.didReplacedPhotoInMemCache) {
|
||||
String oldKey = (String) args[0];
|
||||
if (currentKey != null && currentKey.equals(oldKey)) {
|
||||
currentKey = (String) args[1];
|
||||
currentImageLocation = (TLRPC.FileLocation) args[2];
|
||||
}
|
||||
if (currentThumbKey != null && currentThumbKey.equals(oldKey)) {
|
||||
currentThumbKey = (String) args[1];
|
||||
currentThumbLocation = (TLRPC.FileLocation) args[2];
|
||||
}
|
||||
if (setImageBackup != null) {
|
||||
if (currentKey != null && currentKey.equals(oldKey)) {
|
||||
currentKey = (String) args[1];
|
||||
currentImageLocation = (TLRPC.FileLocation) args[2];
|
||||
}
|
||||
if (currentThumbKey != null && currentThumbKey.equals(oldKey)) {
|
||||
currentThumbKey = (String) args[1];
|
||||
currentThumbLocation = (TLRPC.FileLocation) args[2];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import android.os.IBinder;
|
||||
import android.support.v4.app.NotificationCompat;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
|
||||
public class KeepAliveService extends Service {
|
||||
|
||||
static KeepAliveService s_this = null;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
MrMailbox.log_i("DeltaChat", "*** KeepAliveService.onCreate()");
|
||||
// there's nothing more to do here as all initialisation stuff is already done in
|
||||
// ApplicationLoader.onCreate() which is called before this broadcast is sended.
|
||||
s_this = this;
|
||||
setSelfAsForeground();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
// START_STICKY ensured, the service is recreated as soon it is terminted for any reasons.
|
||||
// as ApplicationLoader.onCreate() is called before a service starts, there is no more to do here,
|
||||
// the app is just running fine.
|
||||
MrMailbox.log_i("DeltaChat", "*** KeepAliveService.onStartCommand()");
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void onDestroy() {
|
||||
MrMailbox.log_i("DeltaChat", "*** KeepAliveService.onDestroy()");
|
||||
// the service will be restarted due to START_STICKY automatically, there's nothing more to do.
|
||||
}
|
||||
|
||||
private void setSelfAsForeground() {
|
||||
stopForeground(true);
|
||||
startForeground(FG_NOTIFICATION_ID, createNotification()); // TODO: if we target Android O, we should use startServiceInForeground()
|
||||
}
|
||||
|
||||
static public KeepAliveService getInstance()
|
||||
{
|
||||
return s_this; // may be null
|
||||
}
|
||||
|
||||
/* The notification
|
||||
* A notification is required for a foreground service; and without a foreground service,
|
||||
* Delta Chat won't get new messages reliable
|
||||
**********************************************************************************************/
|
||||
|
||||
public static final int FG_NOTIFICATION_ID = 4142;
|
||||
private Notification createNotification()
|
||||
{
|
||||
// a notification _must_ contain a small icon, a title and a text, see https://developer.android.com/guide/topics/ui/notifiers/notifications.html#Required
|
||||
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
|
||||
|
||||
if( MrMailbox.isConfigured()!=0) {
|
||||
builder.setContentTitle(LocaleController.formatString("", R.string.PermNotificationTitle, MrMailbox.getConfig("addr", "")));
|
||||
builder.setContentText(getString(R.string.PermNotificationText));
|
||||
}
|
||||
else {
|
||||
builder.setContentTitle(getString(R.string.AppName));
|
||||
builder.setContentText(getString(R.string.AccountNotConfigured));
|
||||
}
|
||||
|
||||
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN ) {
|
||||
builder.setPriority(NotificationCompat.PRIORITY_MIN);
|
||||
}
|
||||
builder.setWhen(0);
|
||||
builder.setSmallIcon(R.drawable.notification_permanent);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
public void updateForegroundNotification()
|
||||
{
|
||||
// update the notification by simply creating a new notification with the same ID, see https://developer.android.com/training/notify-user/managing.html#Updating
|
||||
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
nm.notify(FG_NOTIFICATION_ID, createNotification());
|
||||
}
|
||||
}
|
||||
@@ -31,18 +31,10 @@ import android.content.IntentFilter;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.res.Configuration;
|
||||
import android.text.format.DateFormat;
|
||||
import android.util.Xml;
|
||||
|
||||
import com.b44t.messenger.time.FastDateFormat;
|
||||
|
||||
import org.xmlpull.v1.XmlPullParser;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
@@ -50,13 +42,6 @@ import java.util.TimeZone;
|
||||
|
||||
public class LocaleController {
|
||||
|
||||
static final int QUANTITY_OTHER = 0x0000;
|
||||
static final int QUANTITY_ZERO = 0x0001;
|
||||
static final int QUANTITY_ONE = 0x0002;
|
||||
static final int QUANTITY_TWO = 0x0004;
|
||||
static final int QUANTITY_FEW = 0x0008;
|
||||
static final int QUANTITY_MANY = 0x0010;
|
||||
|
||||
public static boolean isRTL = false;
|
||||
public static int nameDisplayOrder = 1;
|
||||
private static boolean is24HourFormat = false;
|
||||
@@ -68,14 +53,9 @@ public class LocaleController {
|
||||
public FastDateFormat chatDate;
|
||||
public FastDateFormat chatFullDate;
|
||||
|
||||
private HashMap<String, PluralRules> allRules = new HashMap<>();
|
||||
|
||||
private Locale currentLocale;
|
||||
private Locale systemDefaultLocale;
|
||||
private PluralRules currentPluralRules;
|
||||
private Locale systemDefaultLocale; // this is not Locale.getDefault(); Locale.getDefault() may be changed using Locale.setDefault()
|
||||
private LocaleInfo currentLocaleInfo;
|
||||
private LocaleInfo defaultLocalInfo;
|
||||
private HashMap<String, String> localeValues = new HashMap<>();
|
||||
private String languageOverride;
|
||||
private boolean changingConfiguration = false;
|
||||
|
||||
@@ -97,34 +77,10 @@ public class LocaleController {
|
||||
public String name;
|
||||
public String nameEnglish;
|
||||
public String shortName;
|
||||
public String pathToFile;
|
||||
|
||||
public String getSaveString() {
|
||||
return name + "|" + nameEnglish + "|" + shortName + "|" + pathToFile;
|
||||
}
|
||||
|
||||
public static LocaleInfo createWithString(String string) {
|
||||
if (string == null || string.length() == 0) {
|
||||
return null;
|
||||
}
|
||||
String[] args = string.split("\\|");
|
||||
if (args.length != 4) {
|
||||
return null;
|
||||
}
|
||||
LocaleInfo localeInfo = new LocaleInfo();
|
||||
localeInfo.name = args[0];
|
||||
localeInfo.nameEnglish = args[1];
|
||||
localeInfo.shortName = args[2];
|
||||
localeInfo.pathToFile = args[3];
|
||||
return localeInfo;
|
||||
}
|
||||
}
|
||||
|
||||
public ArrayList<LocaleInfo> sortedLanguages = new ArrayList<>();
|
||||
public HashMap<String, LocaleInfo> languagesDict = new HashMap<>();
|
||||
|
||||
private ArrayList<LocaleInfo> otherLanguages = new ArrayList<>();
|
||||
|
||||
private static volatile LocaleController Instance = null;
|
||||
public static LocaleController getInstance() {
|
||||
LocaleController localInstance = Instance;
|
||||
@@ -140,127 +96,67 @@ public class LocaleController {
|
||||
}
|
||||
|
||||
public LocaleController() {
|
||||
addRules(new String[]{"bem", "brx", "da", "de", "el", "en", "eo", "es", "et", "fi", "fo", "gl", "he", "iw", "it", "nb",
|
||||
"nl", "nn", "no", "sv", "af", "bg", "bn", "ca", "eu", "fur", "fy", "gu", "ha", "is", "ku",
|
||||
"lb", "ml", "mr", "nah", "ne", "om", "or", "pa", "pap", "ps", "so", "sq", "sw", "ta", "te",
|
||||
"tk", "ur", "zu", "mn", "gsw", "chr", "rm", "pt", "an", "ast"}, new PluralRules_One());
|
||||
addRules(new String[]{"cs", "sk"}, new PluralRules_Czech());
|
||||
addRules(new String[]{"ff", "fr", "kab"}, new PluralRules_French());
|
||||
addRules(new String[]{"hr", "ru", "sr", "uk", "be", "bs", "sh"}, new PluralRules_Balkan());
|
||||
addRules(new String[]{"lv"}, new PluralRules_Latvian());
|
||||
addRules(new String[]{"lt"}, new PluralRules_Lithuanian());
|
||||
addRules(new String[]{"pl"}, new PluralRules_Polish());
|
||||
addRules(new String[]{"ro", "mo"}, new PluralRules_Romanian());
|
||||
addRules(new String[]{"sl"}, new PluralRules_Slovenian());
|
||||
addRules(new String[]{"ar"}, new PluralRules_Arabic());
|
||||
addRules(new String[]{"mk"}, new PluralRules_Macedonian());
|
||||
addRules(new String[]{"cy"}, new PluralRules_Welsh());
|
||||
addRules(new String[]{"br"}, new PluralRules_Breton());
|
||||
addRules(new String[]{"lag"}, new PluralRules_Langi());
|
||||
addRules(new String[]{"shi"}, new PluralRules_Tachelhit());
|
||||
addRules(new String[]{"mt"}, new PluralRules_Maltese());
|
||||
addRules(new String[]{"ga", "se", "sma", "smi", "smj", "smn", "sms"}, new PluralRules_Two());
|
||||
addRules(new String[]{"ak", "am", "bh", "fil", "tl", "guw", "hi", "ln", "mg", "nso", "ti", "wa"}, new PluralRules_Zero());
|
||||
addRules(new String[]{"az", "bm", "fa", "ig", "hu", "ja", "kde", "kea", "ko", "my", "ses", "sg", "to",
|
||||
"tr", "vi", "wo", "yo", "zh", "bo", "dz", "id", "jv", "ka", "km", "kn", "ms", "th"}, new PluralRules_None());
|
||||
|
||||
LocaleInfo localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "English";
|
||||
localeInfo.nameEnglish = "English";
|
||||
localeInfo.shortName = "en";
|
||||
localeInfo.pathToFile = null;
|
||||
sortedLanguages.add(localeInfo);
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "Italiano";
|
||||
localeInfo.nameEnglish = "Italian";
|
||||
localeInfo.shortName = "it";
|
||||
localeInfo.pathToFile = null;
|
||||
sortedLanguages.add(localeInfo);
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "Español";
|
||||
localeInfo.nameEnglish = "Spanish";
|
||||
localeInfo.shortName = "es";
|
||||
sortedLanguages.add(localeInfo);
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "Deutsch";
|
||||
localeInfo.nameEnglish = "German";
|
||||
localeInfo.shortName = "de";
|
||||
localeInfo.pathToFile = null;
|
||||
sortedLanguages.add(localeInfo);
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "Français";
|
||||
localeInfo.nameEnglish = "French";
|
||||
localeInfo.shortName = "fr";
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "Nederlands";
|
||||
localeInfo.nameEnglish = "Dutch";
|
||||
localeInfo.shortName = "nl";
|
||||
localeInfo.pathToFile = null;
|
||||
sortedLanguages.add(localeInfo);
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
|
||||
/* EDIT BY MR
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "العربية";
|
||||
localeInfo.nameEnglish = "Arabic";
|
||||
localeInfo.shortName = "ar";
|
||||
localeInfo.pathToFile = null;
|
||||
sortedLanguages.add(localeInfo);
|
||||
localeInfo.name = "Polski";
|
||||
localeInfo.nameEnglish = "Polish";
|
||||
localeInfo.shortName = "pl";
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
*/
|
||||
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "Português";
|
||||
localeInfo.nameEnglish = "Portuguese";
|
||||
localeInfo.shortName = "pt";
|
||||
localeInfo.pathToFile = null;
|
||||
sortedLanguages.add(localeInfo);
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
|
||||
/* EDIT BY MR
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "Português (Portugal)";
|
||||
localeInfo.nameEnglish = "Portuguese (Portugal)";
|
||||
localeInfo.shortName = "pt_PT";
|
||||
localeInfo.pathToFile = null;
|
||||
sortedLanguages.add(localeInfo);
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "한국어";
|
||||
localeInfo.nameEnglish = "Korean";
|
||||
localeInfo.shortName = "ko";
|
||||
localeInfo.pathToFile = null;
|
||||
sortedLanguages.add(localeInfo);
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
*/
|
||||
|
||||
loadOtherLanguages();
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = "Magyar";
|
||||
localeInfo.nameEnglish = "Hungarian";
|
||||
localeInfo.shortName = "hu";
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
|
||||
for (LocaleInfo locale : otherLanguages) {
|
||||
sortedLanguages.add(locale);
|
||||
languagesDict.put(locale.shortName, locale);
|
||||
}
|
||||
|
||||
Collections.sort(sortedLanguages, new Comparator<LocaleInfo>() {
|
||||
@Override
|
||||
public int compare(LocaleController.LocaleInfo o, LocaleController.LocaleInfo o2) {
|
||||
return o.name.compareTo(o2.name);
|
||||
}
|
||||
});
|
||||
|
||||
defaultLocalInfo = localeInfo = new LocaleController.LocaleInfo();
|
||||
localeInfo.name = "System default";
|
||||
localeInfo.nameEnglish = "System default";
|
||||
localeInfo.shortName = null;
|
||||
localeInfo.pathToFile = null;
|
||||
sortedLanguages.add(0, localeInfo);
|
||||
|
||||
systemDefaultLocale = Locale.getDefault();
|
||||
systemDefaultLocale = Locale.getDefault(); // we have to remember this as we may switch back to default later
|
||||
is24HourFormat = DateFormat.is24HourFormat(ApplicationLoader.applicationContext);
|
||||
LocaleInfo currentInfo = null;
|
||||
boolean override = false;
|
||||
@@ -286,44 +182,17 @@ public class LocaleController {
|
||||
}
|
||||
applyLanguage(currentInfo, override);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
|
||||
try {
|
||||
IntentFilter timezoneFilter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
|
||||
ApplicationLoader.applicationContext.registerReceiver(new TimeZoneChangedReceiver(), timezoneFilter);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void addRules(String[] languages, PluralRules rules) {
|
||||
for (String language : languages) {
|
||||
allRules.put(language, rules);
|
||||
}
|
||||
}
|
||||
|
||||
private String stringForQuantity(int quantity) {
|
||||
switch (quantity) {
|
||||
case QUANTITY_ZERO:
|
||||
return "zero";
|
||||
case QUANTITY_ONE:
|
||||
return "one";
|
||||
case QUANTITY_TWO:
|
||||
return "two";
|
||||
case QUANTITY_FEW:
|
||||
return "few";
|
||||
case QUANTITY_MANY:
|
||||
return "many";
|
||||
default:
|
||||
return "other";
|
||||
}
|
||||
}
|
||||
|
||||
public Locale getSystemDefaultLocale() {
|
||||
return systemDefaultLocale;
|
||||
}
|
||||
|
||||
private String getLocaleString(Locale locale) {
|
||||
if (locale == null) {
|
||||
return "en";
|
||||
@@ -347,201 +216,7 @@ public class LocaleController {
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String getLocaleStringIso639() {
|
||||
Locale locale = getInstance().getSystemDefaultLocale();
|
||||
if (locale == null) {
|
||||
return "en";
|
||||
}
|
||||
String languageCode = locale.getLanguage();
|
||||
String countryCode = locale.getCountry();
|
||||
String variantCode = locale.getVariant();
|
||||
if (languageCode.length() == 0 && countryCode.length() == 0) {
|
||||
return "en";
|
||||
}
|
||||
StringBuilder result = new StringBuilder(11);
|
||||
result.append(languageCode);
|
||||
if (countryCode.length() > 0 || variantCode.length() > 0) {
|
||||
result.append('-');
|
||||
}
|
||||
result.append(countryCode);
|
||||
if (variantCode.length() > 0) {
|
||||
result.append('_');
|
||||
}
|
||||
result.append(variantCode);
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public boolean applyLanguageFile(File file) {
|
||||
try {
|
||||
HashMap<String, String> stringMap = getLocaleFileStrings(file);
|
||||
|
||||
String languageName = stringMap.get("LanguageName");
|
||||
String languageNameInEnglish = stringMap.get("LanguageNameInEnglish");
|
||||
String languageCode = stringMap.get("LanguageCode");
|
||||
|
||||
if (languageName != null && languageName.length() > 0 &&
|
||||
languageNameInEnglish != null && languageNameInEnglish.length() > 0 &&
|
||||
languageCode != null && languageCode.length() > 0) {
|
||||
|
||||
if (languageName.contains("&") || languageName.contains("|")) {
|
||||
return false;
|
||||
}
|
||||
if (languageNameInEnglish.contains("&") || languageNameInEnglish.contains("|")) {
|
||||
return false;
|
||||
}
|
||||
if (languageCode.contains("&") || languageCode.contains("|") || languageCode.contains("/") || languageCode.contains("\\")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
File finalFile = new File(ApplicationLoader.getFilesDirFixed(), languageCode + ".xml");
|
||||
if (!AndroidUtilities.copyFile(file, finalFile)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
LocaleInfo localeInfo = languagesDict.get(languageCode);
|
||||
if (localeInfo == null) {
|
||||
localeInfo = new LocaleInfo();
|
||||
localeInfo.name = languageName;
|
||||
localeInfo.nameEnglish = languageNameInEnglish;
|
||||
localeInfo.shortName = languageCode;
|
||||
|
||||
localeInfo.pathToFile = finalFile.getAbsolutePath();
|
||||
sortedLanguages.add(localeInfo);
|
||||
languagesDict.put(localeInfo.shortName, localeInfo);
|
||||
otherLanguages.add(localeInfo);
|
||||
|
||||
Collections.sort(sortedLanguages, new Comparator<LocaleInfo>() {
|
||||
@Override
|
||||
public int compare(LocaleController.LocaleInfo o, LocaleController.LocaleInfo o2) {
|
||||
if (o.shortName == null) {
|
||||
return -1;
|
||||
} else if (o2.shortName == null) {
|
||||
return 1;
|
||||
}
|
||||
return o.name.compareTo(o2.name);
|
||||
}
|
||||
});
|
||||
saveOtherLanguages();
|
||||
}
|
||||
localeValues = stringMap;
|
||||
applyLanguage(localeInfo, true, true);
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void saveOtherLanguages() {
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("langconfig", Activity.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = preferences.edit();
|
||||
String locales = "";
|
||||
for (LocaleInfo localeInfo : otherLanguages) {
|
||||
String loc = localeInfo.getSaveString();
|
||||
if (loc != null) {
|
||||
if (locales.length() != 0) {
|
||||
locales += "&";
|
||||
}
|
||||
locales += loc;
|
||||
}
|
||||
}
|
||||
editor.putString("locales", locales);
|
||||
editor.commit();
|
||||
}
|
||||
|
||||
public boolean deleteLanguage(LocaleInfo localeInfo) {
|
||||
if (localeInfo.pathToFile == null) {
|
||||
return false;
|
||||
}
|
||||
if (currentLocaleInfo == localeInfo) {
|
||||
applyLanguage(defaultLocalInfo, true);
|
||||
}
|
||||
|
||||
otherLanguages.remove(localeInfo);
|
||||
sortedLanguages.remove(localeInfo);
|
||||
languagesDict.remove(localeInfo.shortName);
|
||||
File file = new File(localeInfo.pathToFile);
|
||||
file.delete();
|
||||
saveOtherLanguages();
|
||||
return true;
|
||||
}
|
||||
|
||||
private void loadOtherLanguages() {
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("langconfig", Activity.MODE_PRIVATE);
|
||||
String locales = preferences.getString("locales", null);
|
||||
if (locales == null || locales.length() == 0) {
|
||||
return;
|
||||
}
|
||||
String[] localesArr = locales.split("&");
|
||||
for (String locale : localesArr) {
|
||||
LocaleInfo localeInfo = LocaleInfo.createWithString(locale);
|
||||
if (localeInfo != null) {
|
||||
otherLanguages.add(localeInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private HashMap<String, String> getLocaleFileStrings(File file) {
|
||||
FileInputStream stream = null;
|
||||
try {
|
||||
HashMap<String, String> stringMap = new HashMap<>();
|
||||
XmlPullParser parser = Xml.newPullParser();
|
||||
stream = new FileInputStream(file);
|
||||
parser.setInput(stream, "UTF-8");
|
||||
int eventType = parser.getEventType();
|
||||
String name = null;
|
||||
String value = null;
|
||||
String attrName = null;
|
||||
while (eventType != XmlPullParser.END_DOCUMENT) {
|
||||
if(eventType == XmlPullParser.START_TAG) {
|
||||
name = parser.getName();
|
||||
int c = parser.getAttributeCount();
|
||||
if (c > 0) {
|
||||
attrName = parser.getAttributeValue(0);
|
||||
}
|
||||
} else if(eventType == XmlPullParser.TEXT) {
|
||||
if (attrName != null) {
|
||||
value = parser.getText();
|
||||
if (value != null) {
|
||||
value = value.trim();
|
||||
value = value.replace("\\n", "\n");
|
||||
value = value.replace("\\", "");
|
||||
}
|
||||
}
|
||||
} else if (eventType == XmlPullParser.END_TAG) {
|
||||
value = null;
|
||||
attrName = null;
|
||||
name = null;
|
||||
}
|
||||
if (name != null && name.equals("string") && value != null && attrName != null && value.length() != 0 && attrName.length() != 0) {
|
||||
stringMap.put(attrName, value);
|
||||
name = null;
|
||||
value = null;
|
||||
attrName = null;
|
||||
}
|
||||
eventType = parser.next();
|
||||
}
|
||||
return stringMap;
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
} finally {
|
||||
try {
|
||||
if (stream != null) {
|
||||
stream.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
return new HashMap<>();
|
||||
}
|
||||
|
||||
public void applyLanguage(LocaleInfo localeInfo, boolean override) {
|
||||
applyLanguage(localeInfo, override, false);
|
||||
}
|
||||
|
||||
public void applyLanguage(LocaleInfo localeInfo, boolean override, boolean fromFile) {
|
||||
if (localeInfo == null) {
|
||||
return;
|
||||
}
|
||||
@@ -561,16 +236,16 @@ public class LocaleController {
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = preferences.edit();
|
||||
editor.putString("language", localeInfo.shortName);
|
||||
editor.commit();
|
||||
editor.apply();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
newLocale = systemDefaultLocale;
|
||||
newLocale = systemDefaultLocale; // this is not Locale.getDefault(); Locale.getDefault() may be changed using Locale.setDefault()
|
||||
languageOverride = null;
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = preferences.edit();
|
||||
editor.remove("language");
|
||||
editor.commit();
|
||||
editor.apply();
|
||||
|
||||
if (newLocale != null) {
|
||||
LocaleInfo info = null;
|
||||
@@ -586,17 +261,8 @@ public class LocaleController {
|
||||
}
|
||||
}
|
||||
if (newLocale != null) {
|
||||
if (localeInfo.pathToFile == null) {
|
||||
localeValues.clear();
|
||||
} else if (!fromFile) {
|
||||
localeValues = getLocaleFileStrings(new File(localeInfo.pathToFile));
|
||||
}
|
||||
currentLocale = newLocale;
|
||||
currentLocaleInfo = localeInfo;
|
||||
currentPluralRules = allRules.get(currentLocale.getLanguage());
|
||||
if (currentPluralRules == null) {
|
||||
currentPluralRules = allRules.get("en");
|
||||
}
|
||||
changingConfiguration = true;
|
||||
Locale.setDefault(currentLocale);
|
||||
android.content.res.Configuration config = new android.content.res.Configuration();
|
||||
@@ -605,29 +271,21 @@ public class LocaleController {
|
||||
changingConfiguration = false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
changingConfiguration = false;
|
||||
}
|
||||
recreateFormatters();
|
||||
}
|
||||
|
||||
private void loadCurrentLocale() {
|
||||
localeValues.clear();
|
||||
}
|
||||
|
||||
public static String getCurrentLanguageName() {
|
||||
return getString("LanguageName", R.string.LanguageName);
|
||||
}
|
||||
|
||||
private String getStringInternal(String key, int res) {
|
||||
String value = localeValues.get(key);
|
||||
if (value == null) {
|
||||
try {
|
||||
value = ApplicationLoader.applicationContext.getString(res);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
String value = null;
|
||||
try {
|
||||
value = ApplicationLoader.applicationContext.getString(res);
|
||||
} catch (Exception e) { }
|
||||
if (value == null) {
|
||||
value = "LOC_ERR:" + key;
|
||||
}
|
||||
@@ -638,30 +296,16 @@ public class LocaleController {
|
||||
return getInstance().getStringInternal(key, res);
|
||||
}
|
||||
|
||||
public static String formatPluralString(String key, int plural) {
|
||||
if (key == null || key.length() == 0 || getInstance().currentPluralRules == null) {
|
||||
return "LOC_ERR:" + key;
|
||||
}
|
||||
String param = getInstance().stringForQuantity(getInstance().currentPluralRules.quantityForNumber(plural));
|
||||
param = key + "_" + param;
|
||||
int resourceId = ApplicationLoader.applicationContext.getResources().getIdentifier(param, "string", ApplicationLoader.applicationContext.getPackageName());
|
||||
return formatString(param, resourceId, plural);
|
||||
}
|
||||
|
||||
public static String formatString(String key, int res, Object... args) {
|
||||
try {
|
||||
String value = getInstance().localeValues.get(key);
|
||||
if (value == null) {
|
||||
value = ApplicationLoader.applicationContext.getString(res);
|
||||
}
|
||||
|
||||
String value = ApplicationLoader.applicationContext.getString(res);
|
||||
if (getInstance().currentLocale != null) {
|
||||
return String.format(getInstance().currentLocale, value, args);
|
||||
} else {
|
||||
return String.format(value, args);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
return "LOC_ERR: " + key;
|
||||
}
|
||||
}
|
||||
@@ -674,7 +318,7 @@ public class LocaleController {
|
||||
return String.format(string, args);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
return "LOC_ERR: " + string;
|
||||
}
|
||||
}
|
||||
@@ -698,10 +342,6 @@ public class LocaleController {
|
||||
recreateFormatters();
|
||||
}
|
||||
currentLocale = newLocale;
|
||||
currentPluralRules = allRules.get(currentLocale.getLanguage());
|
||||
if (currentPluralRules == null) {
|
||||
currentPluralRules = allRules.get("en");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -719,93 +359,11 @@ public class LocaleController {
|
||||
}
|
||||
return getInstance().chatFullDate.format(date * 1000);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return "LOC_ERR: formatDateChat";
|
||||
}
|
||||
|
||||
public static String formatDate(long date) {
|
||||
try {
|
||||
Calendar rightNow = Calendar.getInstance();
|
||||
int day = rightNow.get(Calendar.DAY_OF_YEAR);
|
||||
int year = rightNow.get(Calendar.YEAR);
|
||||
rightNow.setTimeInMillis(date * 1000);
|
||||
int dateDay = rightNow.get(Calendar.DAY_OF_YEAR);
|
||||
int dateYear = rightNow.get(Calendar.YEAR);
|
||||
|
||||
if (dateDay == day && year == dateYear) {
|
||||
return getInstance().formatterDay.format(new Date(date * 1000));
|
||||
} else if (dateDay + 1 == day && year == dateYear) {
|
||||
return getString("Yesterday", R.string.Yesterday);
|
||||
} else if (year == dateYear) {
|
||||
return getInstance().formatterMonth.format(new Date(date * 1000));
|
||||
} else {
|
||||
return getInstance().formatterYear.format(new Date(date * 1000));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return "LOC_ERR: formatDate";
|
||||
}
|
||||
|
||||
public static String formatDateAudio(long date) {
|
||||
try {
|
||||
Calendar rightNow = Calendar.getInstance();
|
||||
int day = rightNow.get(Calendar.DAY_OF_YEAR);
|
||||
int year = rightNow.get(Calendar.YEAR);
|
||||
rightNow.setTimeInMillis(date * 1000);
|
||||
int dateDay = rightNow.get(Calendar.DAY_OF_YEAR);
|
||||
int dateYear = rightNow.get(Calendar.YEAR);
|
||||
|
||||
if (dateDay == day && year == dateYear) {
|
||||
return String.format("%s %s", LocaleController.getString("TodayAt", R.string.TodayAt), getInstance().formatterDay.format(new Date(date * 1000)));
|
||||
} else if (dateDay + 1 == day && year == dateYear) {
|
||||
return String.format("%s %s", LocaleController.getString("YesterdayAt", R.string.YesterdayAt), getInstance().formatterDay.format(new Date(date * 1000)));
|
||||
} else if (year == dateYear) {
|
||||
return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterMonth.format(new Date(date * 1000)), getInstance().formatterDay.format(new Date(date * 1000)));
|
||||
} else {
|
||||
return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterYear.format(new Date(date * 1000)), getInstance().formatterDay.format(new Date(date * 1000)));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return "LOC_ERR";
|
||||
}
|
||||
|
||||
public static String formatDateOnline(long date) {
|
||||
try {
|
||||
Calendar rightNow = Calendar.getInstance();
|
||||
int day = rightNow.get(Calendar.DAY_OF_YEAR);
|
||||
int year = rightNow.get(Calendar.YEAR);
|
||||
rightNow.setTimeInMillis(date * 1000);
|
||||
int dateDay = rightNow.get(Calendar.DAY_OF_YEAR);
|
||||
int dateYear = rightNow.get(Calendar.YEAR);
|
||||
|
||||
if (dateDay == day && year == dateYear) {
|
||||
return String.format("%s %s %s", LocaleController.getString("LastSeen", R.string.LastSeen), LocaleController.getString("TodayAt", R.string.TodayAt), getInstance().formatterDay.format(new Date(date * 1000)));
|
||||
/*int diff = (int) (ConnectionsManager.getInstance().getCurrentTime() - date) / 60;
|
||||
if (diff < 1) {
|
||||
return LocaleController.getString("LastSeenNow", R.string.LastSeenNow);
|
||||
} else if (diff < 60) {
|
||||
return LocaleController.formatPluralString("LastSeenMinutes", diff);
|
||||
} else {
|
||||
return LocaleController.formatPluralString("LastSeenHours", (int) Math.ceil(diff / 60.0f));
|
||||
}*/
|
||||
} else if (dateDay + 1 == day && year == dateYear) {
|
||||
return String.format("%s %s %s", LocaleController.getString("LastSeen", R.string.LastSeen), LocaleController.getString("YesterdayAt", R.string.YesterdayAt), getInstance().formatterDay.format(new Date(date * 1000)));
|
||||
} else if (year == dateYear) {
|
||||
String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterMonth.format(new Date(date * 1000)), getInstance().formatterDay.format(new Date(date * 1000)));
|
||||
return String.format("%s %s", LocaleController.getString("LastSeenDate", R.string.LastSeenDate), format);
|
||||
} else {
|
||||
String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterYear.format(new Date(date * 1000)), getInstance().formatterDay.format(new Date(date * 1000)));
|
||||
return String.format("%s %s", LocaleController.getString("LastSeenDate", R.string.LastSeenDate), format);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return "LOC_ERR";
|
||||
}
|
||||
|
||||
private FastDateFormat createFormatter(Locale locale, String format, String defaultFormat) {
|
||||
if (format == null || format.length() == 0) {
|
||||
format = defaultFormat;
|
||||
@@ -863,288 +421,8 @@ public class LocaleController {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return "LOC_ERR";
|
||||
}
|
||||
|
||||
/*
|
||||
public static String formatShortNumber(int number, int[] rounded) {
|
||||
String K = "";
|
||||
int lastDec = 0;
|
||||
int KCount = 0;
|
||||
while (number / 1000 > 0) {
|
||||
K += "K";
|
||||
lastDec = (number % 1000) / 100;
|
||||
number /= 1000;
|
||||
}
|
||||
if (rounded != null) {
|
||||
double value = number + lastDec / 10.0;
|
||||
for (int a = 0; a < K.length(); a++) {
|
||||
value *= 1000;
|
||||
}
|
||||
rounded[0] = (int) value;
|
||||
}
|
||||
if (lastDec != 0 && K.length() > 0) {
|
||||
if (K.length() == 2) {
|
||||
return String.format(Locale.US, "%d.%dM", number, lastDec);
|
||||
} else {
|
||||
return String.format(Locale.US, "%d.%d%s", number, lastDec, K);
|
||||
}
|
||||
}
|
||||
if (K.length() == 2) {
|
||||
return String.format(Locale.US, "%dM", number);
|
||||
} else {
|
||||
return String.format(Locale.US, "%d%s", number, K);
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
abstract public static class PluralRules {
|
||||
abstract int quantityForNumber(int n);
|
||||
}
|
||||
|
||||
public static class PluralRules_Zero extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
if (count == 0 || count == 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Welsh extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
if (count == 0) {
|
||||
return QUANTITY_ZERO;
|
||||
} else if (count == 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (count == 2) {
|
||||
return QUANTITY_TWO;
|
||||
} else if (count == 3) {
|
||||
return QUANTITY_FEW;
|
||||
} else if (count == 6) {
|
||||
return QUANTITY_MANY;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Two extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
if (count == 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (count == 2) {
|
||||
return QUANTITY_TWO;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Tachelhit extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
if (count >= 0 && count <= 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (count >= 2 && count <= 10) {
|
||||
return QUANTITY_FEW;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Slovenian extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
int rem100 = count % 100;
|
||||
if (rem100 == 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (rem100 == 2) {
|
||||
return QUANTITY_TWO;
|
||||
} else if (rem100 >= 3 && rem100 <= 4) {
|
||||
return QUANTITY_FEW;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Romanian extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
int rem100 = count % 100;
|
||||
if (count == 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else if ((count == 0 || (rem100 >= 1 && rem100 <= 19))) {
|
||||
return QUANTITY_FEW;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Polish extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
int rem100 = count % 100;
|
||||
int rem10 = count % 10;
|
||||
if (count == 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (rem10 >= 2 && rem10 <= 4 && !(rem100 >= 12 && rem100 <= 14) && !(rem100 >= 22 && rem100 <= 24)) {
|
||||
return QUANTITY_FEW;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_One extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
return count == 1 ? QUANTITY_ONE : QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_None extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Maltese extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
int rem100 = count % 100;
|
||||
if (count == 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (count == 0 || (rem100 >= 2 && rem100 <= 10)) {
|
||||
return QUANTITY_FEW;
|
||||
} else if (rem100 >= 11 && rem100 <= 19) {
|
||||
return QUANTITY_MANY;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Macedonian extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
if (count % 10 == 1 && count != 11) {
|
||||
return QUANTITY_ONE;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Lithuanian extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
int rem100 = count % 100;
|
||||
int rem10 = count % 10;
|
||||
if (rem10 == 1 && !(rem100 >= 11 && rem100 <= 19)) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (rem10 >= 2 && rem10 <= 9 && !(rem100 >= 11 && rem100 <= 19)) {
|
||||
return QUANTITY_FEW;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Latvian extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
if (count == 0) {
|
||||
return QUANTITY_ZERO;
|
||||
} else if (count % 10 == 1 && count % 100 != 11) {
|
||||
return QUANTITY_ONE;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Langi extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
if (count == 0) {
|
||||
return QUANTITY_ZERO;
|
||||
} else if (count > 0 && count < 2) {
|
||||
return QUANTITY_ONE;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_French extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
if (count >= 0 && count < 2) {
|
||||
return QUANTITY_ONE;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Czech extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
if (count == 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (count >= 2 && count <= 4) {
|
||||
return QUANTITY_FEW;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Breton extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
if (count == 0) {
|
||||
return QUANTITY_ZERO;
|
||||
} else if (count == 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (count == 2) {
|
||||
return QUANTITY_TWO;
|
||||
} else if (count == 3) {
|
||||
return QUANTITY_FEW;
|
||||
} else if (count == 6) {
|
||||
return QUANTITY_MANY;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Balkan extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
int rem100 = count % 100;
|
||||
int rem10 = count % 10;
|
||||
if (rem10 == 1 && rem100 != 11) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (rem10 >= 2 && rem10 <= 4 && !(rem100 >= 12 && rem100 <= 14)) {
|
||||
return QUANTITY_FEW;
|
||||
} else if ((rem10 == 0 || (rem10 >= 5 && rem10 <= 9) || (rem100 >= 11 && rem100 <= 14))) {
|
||||
return QUANTITY_MANY;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class PluralRules_Arabic extends PluralRules {
|
||||
public int quantityForNumber(int count) {
|
||||
int rem100 = count % 100;
|
||||
if (count == 0) {
|
||||
return QUANTITY_ZERO;
|
||||
} else if (count == 1) {
|
||||
return QUANTITY_ONE;
|
||||
} else if (count == 2) {
|
||||
return QUANTITY_TWO;
|
||||
} else if (rem100 >= 3 && rem100 <= 10) {
|
||||
return QUANTITY_FEW;
|
||||
} else if (rem100 >= 11 && rem100 <= 99) {
|
||||
return QUANTITY_MANY;
|
||||
} else {
|
||||
return QUANTITY_OTHER;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,373 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
import com.b44t.ui.ActionBar.BaseFragment;
|
||||
import com.b44t.ui.SettingsActivity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class MessagesController implements NotificationCenter.NotificationCenterDelegate {
|
||||
|
||||
public ArrayList<TLRPC.TL_dialog> dialogs = new ArrayList<>();
|
||||
public int nextDialogsCacheOffset;
|
||||
public ConcurrentHashMap<Long, TLRPC.TL_dialog> dialogs_dict = new ConcurrentHashMap<>(100, 1.0f, 2);
|
||||
public HashMap<Long, MessageObject> dialogMessage = new HashMap<>();
|
||||
public HashMap<Long, MessageObject> dialogMessagesByRandomIds = new HashMap<>();
|
||||
public HashMap<Integer, MessageObject> dialogMessagesByIds = new HashMap<>();
|
||||
public HashMap<Long, CharSequence> printingStrings = new HashMap<>();
|
||||
|
||||
public int secretWebpagePreview = 2;
|
||||
|
||||
private String uploadingAvatar = null;
|
||||
|
||||
public int fontSize = AndroidUtilities.dp(16);
|
||||
public int ratingDecay;
|
||||
|
||||
public static final int UPDATE_MASK_NAME = 1;
|
||||
public static final int UPDATE_MASK_AVATAR = 2;
|
||||
public static final int UPDATE_MASK_STATUS = 4;
|
||||
public static final int UPDATE_MASK_CHAT_AVATAR = 8;
|
||||
public static final int UPDATE_MASK_CHAT_NAME = 16;
|
||||
public static final int UPDATE_MASK_CHAT_MEMBERS = 32;
|
||||
public static final int UPDATE_MASK_USER_PRINT = 64;
|
||||
public static final int UPDATE_MASK_READ_DIALOG_MESSAGE = 256;
|
||||
public static final int UPDATE_MASK_SELECT_DIALOG = 512;
|
||||
public static final int UPDATE_MASK_NEW_MESSAGE = 2048;
|
||||
public static final int UPDATE_MASK_SEND_STATE = 4096;
|
||||
|
||||
private static volatile MessagesController Instance = null;
|
||||
|
||||
public static MessagesController getInstance() {
|
||||
MessagesController localInstance = Instance;
|
||||
if (localInstance == null) {
|
||||
synchronized (MessagesController.class) {
|
||||
localInstance = Instance;
|
||||
if (localInstance == null) {
|
||||
Instance = localInstance = new MessagesController();
|
||||
}
|
||||
}
|
||||
}
|
||||
return localInstance;
|
||||
}
|
||||
|
||||
public MessagesController() {
|
||||
ImageLoader.getInstance();
|
||||
NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidUpload);
|
||||
NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailUpload);
|
||||
NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidLoaded);
|
||||
NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileDidFailedLoad);
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
|
||||
|
||||
preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
|
||||
secretWebpagePreview = preferences.getInt("secretWebpage2", 2);
|
||||
ratingDecay = preferences.getInt("ratingDecay", 2419200);
|
||||
fontSize = preferences.getInt("msg_font_size", SettingsActivity.defMsgFontSize());
|
||||
}
|
||||
|
||||
/*
|
||||
public static TLRPC.InputUser getInputUser(TLRPC.User user) {
|
||||
if (user == null) {
|
||||
return new TLRPC.TL_inputUserEmpty();
|
||||
}
|
||||
TLRPC.InputUser inputUser;
|
||||
if (user.id == UserConfig.getClientUserId()) {
|
||||
inputUser = new TLRPC.TL_inputUserSelf();
|
||||
} else {
|
||||
inputUser = new TLRPC.TL_inputUser();
|
||||
inputUser.user_id = user.id;
|
||||
}
|
||||
return inputUser;
|
||||
}
|
||||
|
||||
public static TLRPC.InputUser getInputUser(int user_id) {
|
||||
TLRPC.User user = getInstance().getUser(user_id);
|
||||
return getInputUser(user);
|
||||
}
|
||||
*/
|
||||
|
||||
public static TLRPC.InputPeer getInputPeer(int id) {
|
||||
TLRPC.InputPeer inputPeer;
|
||||
{
|
||||
inputPeer = new TLRPC.TL_inputPeerUser();
|
||||
inputPeer.user_id = id;
|
||||
}
|
||||
return inputPeer;
|
||||
}
|
||||
|
||||
public static TLRPC.Peer getPeer(int id) {
|
||||
TLRPC.Peer inputPeer;
|
||||
/*if (id < 0) {
|
||||
inputPeer = new TLRPC.TL_peerChat();
|
||||
inputPeer.chat_id = -id;
|
||||
} else*/ {
|
||||
inputPeer = new TLRPC.TL_peerUser();
|
||||
inputPeer.user_id = id;
|
||||
}
|
||||
return inputPeer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didReceivedNotification(int id, Object... args) {
|
||||
if (id == NotificationCenter.FileDidUpload) {
|
||||
final String location = (String) args[0];
|
||||
final TLRPC.InputFile file = (TLRPC.InputFile) args[1];
|
||||
|
||||
if (uploadingAvatar != null && uploadingAvatar.equals(location)) {
|
||||
/*TLRPC.TL_photos_uploadProfilePhoto req = new TLRPC.TL_photos_uploadProfilePhoto();
|
||||
req.caption = "";
|
||||
req.crop = new TLRPC.TL_inputPhotoCropAuto();
|
||||
req.file = file;
|
||||
req.geo_point = new TLRPC.TL_inputGeoPointEmpty();*/
|
||||
/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
|
||||
@Override
|
||||
public void run(TLObject response, TLRPC.TL_error error) {
|
||||
if (error == null) {
|
||||
TLRPC.User user = getUser(UserConfig.getClientUserId());
|
||||
if (user == null) {
|
||||
user = UserConfig.getCurrentUser();
|
||||
putUser(user, true);
|
||||
} else {
|
||||
UserConfig.setCurrentUser(user);
|
||||
}
|
||||
if (user == null) {
|
||||
return;
|
||||
}
|
||||
TLRPC.TL_photos_photo photo = (TLRPC.TL_photos_photo) response;
|
||||
ArrayList<TLRPC.PhotoSize> sizes = photo.photo.sizes;
|
||||
TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 100);
|
||||
TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000);
|
||||
user.photo = new TLRPC.TL_userProfilePhoto();
|
||||
user.photo.photo_id = photo.photo.id;
|
||||
if (smallSize != null) {
|
||||
user.photo.photo_small = smallSize.location;
|
||||
}
|
||||
if (bigSize != null) {
|
||||
user.photo.photo_big = bigSize.location;
|
||||
} else if (smallSize != null) {
|
||||
user.photo.photo_small = smallSize.location;
|
||||
}
|
||||
//MessagesStorage.getInstance().clearUserPhotos(user.id);
|
||||
ArrayList<TLRPC.User> users = new ArrayList<>();
|
||||
users.add(user);
|
||||
//MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);
|
||||
AndroidUtilities.runOnUIThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_AVATAR);
|
||||
UserConfig.saveConfig(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});*/
|
||||
}
|
||||
} else if (id == NotificationCenter.FileDidFailUpload) {
|
||||
final String location = (String) args[0];
|
||||
if (uploadingAvatar != null && uploadingAvatar.equals(location)) {
|
||||
uploadingAvatar = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public TLRPC.User getUser(Integer id) {
|
||||
// EDIT BY MR - additional information should be loaded as needed by the caller
|
||||
TLRPC.User u = new TLRPC.User();
|
||||
u.id = id;
|
||||
return u;
|
||||
}
|
||||
|
||||
public TLRPC.Chat getChat(Integer id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void deleteMessages(ArrayList<Integer> messages, ArrayList<Long> randoms, Object encryptedChat, final int channelId) {
|
||||
|
||||
}
|
||||
|
||||
public MediaController.SearchImage saveGif(TLRPC.Document document) {
|
||||
MediaController.SearchImage searchImage = new MediaController.SearchImage();
|
||||
searchImage.type = 2;
|
||||
searchImage.document = document;
|
||||
searchImage.date = (int) (System.currentTimeMillis() / 1000);
|
||||
searchImage.id = "" + searchImage.document.id;
|
||||
|
||||
ArrayList<MediaController.SearchImage> arrayList = new ArrayList<>();
|
||||
arrayList.add(searchImage);
|
||||
//MessagesStorage.getInstance().putWebRecent(arrayList);
|
||||
/*TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
|
||||
req.id = new TLRPC.TL_inputDocument();
|
||||
req.id.id = searchImage.document.id;
|
||||
req.id.access_hash = searchImage.document.access_hash;
|
||||
req.unsave = false;
|
||||
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
|
||||
@Override
|
||||
public void run(TLObject response, TLRPC.TL_error error) {
|
||||
|
||||
}
|
||||
});*/
|
||||
return searchImage;
|
||||
}
|
||||
|
||||
public void cancelTyping(int action, long dialog_id) {
|
||||
}
|
||||
|
||||
public void sendTyping(final long dialog_id, final int action, int classGuid) {
|
||||
}
|
||||
|
||||
public void markMessageContentAsRead(final MessageObject messageObject) {
|
||||
}
|
||||
|
||||
public void addUserToChat(final int chat_id, final TLRPC.User user, final TLRPC.ChatFull info, int count_fwd, String botHash, final BaseFragment fragment) {
|
||||
}
|
||||
|
||||
public void changeChatAvatar(int chat_id, TLRPC.InputFile uploadedAvatar) {
|
||||
/*TLObject request;
|
||||
{
|
||||
TLRPC.TL_messages_editChatPhoto req = new TLRPC.TL_messages_editChatPhoto();
|
||||
req.chat_id = chat_id;
|
||||
if (uploadedAvatar != null) {
|
||||
req.photo = new TLRPC.TL_inputChatUploadedPhoto();
|
||||
req.photo.file = uploadedAvatar;
|
||||
req.photo.crop = new TLRPC.TL_inputPhotoCropAuto();
|
||||
} else {
|
||||
req.photo = new TLRPC.TL_inputChatPhotoEmpty();
|
||||
}
|
||||
request = req;
|
||||
}*/
|
||||
/*ConnectionsManager.getInstance().sendRequest(request, new RequestDelegate() {
|
||||
@Override
|
||||
public void run(TLObject response, TLRPC.TL_error error) {
|
||||
if (error != null) {
|
||||
return;
|
||||
}
|
||||
processUpdates((TLRPC.Updates) response, false);
|
||||
}
|
||||
}, ConnectionsManager.RequestFlagInvokeAfter);*/
|
||||
}
|
||||
|
||||
public boolean isDialogMuted(long dialog_id) {
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
|
||||
int mute_type = preferences.getInt("notify2_" + dialog_id, 0);
|
||||
if (mute_type == 2) {
|
||||
return true;
|
||||
} else if (mute_type == 3) {
|
||||
int mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0);
|
||||
if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
protected void updateInterfaceWithMessages(long uid, ArrayList<MessageObject> messages) {
|
||||
updateInterfaceWithMessages(uid, messages, false);
|
||||
}
|
||||
|
||||
protected static void addNewGifToRecent(TLRPC.Document document, int date) {
|
||||
ArrayList<MediaController.SearchImage> arrayList = new ArrayList<>();
|
||||
MediaController.SearchImage searchImage = new MediaController.SearchImage();
|
||||
searchImage.type = 2;
|
||||
searchImage.document = document;
|
||||
searchImage.date = date;
|
||||
searchImage.id = "" + searchImage.document.id;
|
||||
arrayList.add(searchImage);
|
||||
}
|
||||
|
||||
protected void updateInterfaceWithMessages(final long uid, final ArrayList<MessageObject> messages, boolean isBroadcast) {
|
||||
if (messages == null || messages.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final boolean isEncryptedChat = false;
|
||||
MessageObject lastMessage = null;
|
||||
int channelId = 0;
|
||||
for (int a = 0; a < messages.size(); a++) {
|
||||
MessageObject message = messages.get(a);
|
||||
if (lastMessage == null || (!isEncryptedChat && message.getId() > lastMessage.getId() || (isEncryptedChat || message.getId() < 0 && lastMessage.getId() < 0) && message.getId() < lastMessage.getId()) || message.messageOwner.date > lastMessage.messageOwner.date) {
|
||||
lastMessage = message;
|
||||
}
|
||||
if (message.isOut() && message.isNewGif() && !message.isSending() && !message.isForwarded()) {
|
||||
addNewGifToRecent(message.messageOwner.media.document, message.messageOwner.date);
|
||||
}
|
||||
}
|
||||
//MessagesQuery.loadReplyMessagesForMessages(messages, uid);
|
||||
NotificationCenter.getInstance().postNotificationName(NotificationCenter.didReceivedNewMessages, uid, messages);
|
||||
|
||||
if (lastMessage == null) {
|
||||
return;
|
||||
}
|
||||
TLRPC.TL_dialog dialog = dialogs_dict.get(uid);
|
||||
|
||||
if (dialog == null) {
|
||||
if (!isBroadcast) {
|
||||
TLRPC.Chat chat = getChat(channelId);
|
||||
if (channelId != 0 && chat == null || chat != null && false/*chat.left*/) {
|
||||
return;
|
||||
}
|
||||
dialog = new TLRPC.TL_dialog();
|
||||
dialog.id = uid;
|
||||
dialog.unread_count = 0;
|
||||
dialog.top_message = lastMessage.getId();
|
||||
dialog.last_message_date = lastMessage.messageOwner.date;
|
||||
//dialog.flags = ChatObject.isChannel(chat) ? 1 : 0;
|
||||
dialogs_dict.put(uid, dialog);
|
||||
dialogs.add(dialog);
|
||||
dialogMessage.put(uid, lastMessage);
|
||||
if (lastMessage.messageOwner.to_id.channel_id == 0) {
|
||||
dialogMessagesByIds.put(lastMessage.getId(), lastMessage);
|
||||
if (lastMessage.messageOwner.random_id != 0) {
|
||||
dialogMessagesByRandomIds.put(lastMessage.messageOwner.random_id, lastMessage);
|
||||
}
|
||||
}
|
||||
nextDialogsCacheOffset++;
|
||||
}
|
||||
} else {
|
||||
if ((dialog.top_message > 0 && lastMessage.getId() > 0 && lastMessage.getId() > dialog.top_message) ||
|
||||
(dialog.top_message < 0 && lastMessage.getId() < 0 && lastMessage.getId() < dialog.top_message) ||
|
||||
!dialogMessage.containsKey(uid) || dialog.top_message < 0 || dialog.last_message_date <= lastMessage.messageOwner.date) {
|
||||
MessageObject object = dialogMessagesByIds.remove(dialog.top_message);
|
||||
if (object != null && object.messageOwner.random_id != 0) {
|
||||
dialogMessagesByRandomIds.remove(object.messageOwner.random_id);
|
||||
}
|
||||
dialog.top_message = lastMessage.getId();
|
||||
if (!isBroadcast) {
|
||||
dialog.last_message_date = lastMessage.messageOwner.date;
|
||||
}
|
||||
dialogMessage.put(uid, lastMessage);
|
||||
if (lastMessage.messageOwner.to_id.channel_id == 0) {
|
||||
dialogMessagesByIds.put(lastMessage.getId(), lastMessage);
|
||||
if (lastMessage.messageOwner.random_id != 0) {
|
||||
dialogMessagesByRandomIds.put(lastMessage.messageOwner.random_id, lastMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,13 +76,9 @@ public class MrChat {
|
||||
return MrChatGetTotalMsgCount(m_hChat);
|
||||
}
|
||||
|
||||
public int sendText(String text) {
|
||||
return MrChatSendText(m_hChat, text);
|
||||
}
|
||||
public native int sendText(String text);
|
||||
|
||||
public int sendMedia(int type, String file, String mime, int w, int h, int time_ms) {
|
||||
return MrChatSendMedia(m_hChat, type, file, mime, w, h, time_ms);
|
||||
}
|
||||
public native int sendMedia(int type, String file, String mime, int w, int h, int time_ms, String author, String trackname);
|
||||
|
||||
private long m_hChat; // must not be renamed as referenced by JNI under the name "m_hChat"
|
||||
private native static void MrChatUnref (long hChat);
|
||||
@@ -92,8 +88,6 @@ public class MrChat {
|
||||
private native static int MrChatSetDraft (long hChat, String draft/*NULL=delete*/, long replyToMsgId);
|
||||
private native static int MrChatGetUnseenCount (long hChat);
|
||||
private native static int MrChatGetTotalMsgCount (long hChat);
|
||||
private native static int MrChatSendText (long hChat, String text); // returns message id
|
||||
private native static int MrChatSendMedia (long hChat, int type, String file, String mime, int w, int h, int time_ms);
|
||||
|
||||
|
||||
/* additional functions that are not 1:1 available in the backend
|
||||
|
||||
@@ -28,6 +28,22 @@
|
||||
package com.b44t.messenger;
|
||||
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.net.ConnectivityManager;
|
||||
import android.net.NetworkInfo;
|
||||
import android.util.Log;
|
||||
|
||||
import com.b44t.ui.Components.ForegroundDetector;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
public class MrMailbox {
|
||||
|
||||
public static void init () {
|
||||
@@ -38,53 +54,25 @@ public class MrMailbox {
|
||||
public native static void close();
|
||||
public native static String getBlobdir();
|
||||
|
||||
public static int configure() {
|
||||
return MrMailboxConfigure(m_hMailbox);
|
||||
}
|
||||
public native static void configureAndConnect();
|
||||
public native static void configureCancel();
|
||||
|
||||
public static int isConfigured() {
|
||||
return MrMailboxIsConfigured(m_hMailbox);
|
||||
}
|
||||
public native static int isConfigured();
|
||||
|
||||
public static int connect() {
|
||||
return MrMailboxConnect(m_hMailbox);
|
||||
}
|
||||
public native static void connect();
|
||||
public native static void disconnect();
|
||||
|
||||
public static void disconnect() {
|
||||
MrMailboxDisconnect(m_hMailbox);
|
||||
}
|
||||
|
||||
public static int fetch() {
|
||||
return MrMailboxFetch(m_hMailbox);
|
||||
}
|
||||
|
||||
public native static String getErrorDescr();
|
||||
|
||||
public static int setConfig(String key, String value) {
|
||||
return MrMailboxSetConfig(m_hMailbox, key, value);
|
||||
}
|
||||
|
||||
public static String getConfig(String key, String def) {
|
||||
return MrMailboxGetConfig(m_hMailbox, key, def);
|
||||
}
|
||||
|
||||
public static int getConfigInt(String key, int def) {
|
||||
return MrMailboxGetConfigInt(m_hMailbox, key, def);
|
||||
}
|
||||
public native static void setConfig(String key, String value);
|
||||
public native static void setConfigInt(String key, int value);
|
||||
public native static String getConfig(String key, String def);
|
||||
public native static int getConfigInt(String key, int def);
|
||||
|
||||
public native static String getInfo();
|
||||
public native static String cmdline(String cmd);
|
||||
public native static void heartbeat();
|
||||
|
||||
private static long m_hMailbox = 0; // do not rename this, is used in C-part
|
||||
private native static long MrMailboxNew (); // returns hMailbox which must be unref'd after usage (Names as mrmailbox_new don't work due to the additional underscore)
|
||||
private native static int MrMailboxConfigure (long hMailbox);
|
||||
private native static int MrMailboxIsConfigured (long hMailbox);
|
||||
private native static int MrMailboxConnect (long hMailbox);
|
||||
private native static void MrMailboxDisconnect (long hMailbox);
|
||||
private native static int MrMailboxFetch (long hMailbox);
|
||||
private native static int MrMailboxSetConfig (long hMailbox, String key, String value); // value may be NULL
|
||||
private native static String MrMailboxGetConfig (long hMailbox, String key, String def); // def may be NULL, returns empty string as NULL
|
||||
private native static int MrMailboxGetConfigInt (long hMailbox, String key, int def); // def may be NULL, returns empty string as NULL
|
||||
private native static long MrMailboxNew(); // returns hMailbox which must be unref'd after usage (Names as mrmailbox_new don't work due to the additional underscore)
|
||||
|
||||
// contacts
|
||||
public native static int[] getKnownContacts(String query);
|
||||
@@ -130,15 +118,11 @@ public class MrMailbox {
|
||||
public native static int markseenMsg (int msg_id);
|
||||
public native static int markseenChat (int chat_id);
|
||||
|
||||
public static int getChatIdByContactId (int contact_id) {
|
||||
return MrMailboxGetChatIdByContactId(m_hMailbox, contact_id);
|
||||
}
|
||||
|
||||
public static int createChatByContactId(int contact_id) {
|
||||
return MrMailboxCreateChatByContactId(m_hMailbox, contact_id);
|
||||
}
|
||||
public native static int getChatIdByContactId (int contact_id);
|
||||
public native static int createChatByContactId(int contact_id); // returns chat_id
|
||||
|
||||
public native static int createGroupChat (String name);
|
||||
public native static int isContactInChat (int chat_id, int contact_id);
|
||||
public native static int addContactToChat (int chat_id, int contact_id);
|
||||
public native static int removeContactFromChat (int chat_id, int contact_id);
|
||||
public native static int setChatName (int chat_id, String name);
|
||||
@@ -150,18 +134,13 @@ public class MrMailbox {
|
||||
|
||||
public native static int[] getUnseenMsgs();
|
||||
|
||||
public static int[] getChatMedia(int chat_id, int msg_type, int or_msg_type) {
|
||||
return MrMailboxGetChatMedia(m_hMailbox, chat_id, msg_type, or_msg_type);
|
||||
}
|
||||
|
||||
public native static int[] getChatMedia(int chat_id, int msg_type, int or_msg_type);
|
||||
public native static int getNextMedia(int msg_id, int dir);
|
||||
public native static int[] getChatContacts(int chat_id);
|
||||
public native static int deleteChat(int chat_id);
|
||||
|
||||
private native static long MrMailboxGetChatlist (long hMailbox, String query); // returns hChatlist which must be unref'd after usage
|
||||
private native static long MrMailboxGetChat (long hMailbox, int chat_id); // return hChat which must be unref'd after usage
|
||||
private native static int MrMailboxGetChatIdByContactId (long hMailbox, int contact_id);
|
||||
private native static int MrMailboxCreateChatByContactId(long hMailbox, int contact_id); // returns chat_id
|
||||
private native static int[] MrMailboxGetChatMedia (long hMailbox, int chat_id, int msg_type, int or_msg_type);
|
||||
|
||||
|
||||
// msgs
|
||||
@@ -180,33 +159,58 @@ public class MrMailbox {
|
||||
private native static String MrMailboxGetMsgInfo (long hMailbox, int id);
|
||||
|
||||
// static
|
||||
private native static void MrStockAddStr (int id, String str);
|
||||
public native static String MrGetVersionStr ();
|
||||
public native static String CPtr2String (long hString); // get strings eg. from data1 from the callback
|
||||
|
||||
public native static long String2CPtr (String str);
|
||||
|
||||
/* receive events
|
||||
**********************************************************************************************/
|
||||
|
||||
public final static int MR_EVENT_INFO = 100;
|
||||
public final static int MR_EVENT_WARNING = 300;
|
||||
public final static int MR_EVENT_ERROR = 400; // INFO and WARNING are blocked in the mrwrapper.c
|
||||
|
||||
public final static int MR_EVENT_MSGS_CHANGED = 2000;
|
||||
public final static int MR_EVENT_INCOMING_MSG = 2005;
|
||||
public final static int MR_EVENT_MSG_DELIVERED = 2010;
|
||||
public final static int MR_EVENT_MSG_READ = 2015;
|
||||
public final static int MR_EVENT_CHAT_MODIFIED = 2020;
|
||||
public final static int MR_EVENT_CONTACTS_CHANGED = 2030;
|
||||
public final static int MR_EVENT_CONNECTION_STATE_CHANGED = 2040;
|
||||
public final static int MR_EVENT_REPORT = 2050;
|
||||
|
||||
public final static int MR_REPORT_ERR_SELF_NOT_IN_GROUP = 1;
|
||||
public final static int MR_EVENT_CHAT_MODIFIED = 2020;
|
||||
|
||||
public final static int MR_EVENT_CONTACTS_CHANGED = 2030;
|
||||
|
||||
public final static int MR_EVENT_CONFIGURE_ENDED = 2040;
|
||||
public final static int MR_EVENT_CONFIGURE_PROGRESS = 2041;
|
||||
|
||||
public final static int MR_EVENT_IS_ONLINE = 2080;
|
||||
public final static int MR_EVENT_GET_STRING = 2091;
|
||||
public final static int MR_EVENT_GET_QUANTITIY_STRING = 2092;
|
||||
public final static int MR_EVENT_HTTP_GET = 2100;
|
||||
public final static int MR_EVENT_WAKE_LOCK = 2110;
|
||||
|
||||
|
||||
public static final Object m_lastErrorLock = new Object();
|
||||
public static int m_lastErrorCode = 0;
|
||||
public static String m_lastErrorString = "";
|
||||
public static boolean m_showNextErrorAsToast = true;
|
||||
|
||||
public static long MrCallback(final int event, final long data1, final long data2) // this function is called from within the C-wrapper
|
||||
{
|
||||
switch(event) {
|
||||
case MR_EVENT_CONNECTION_STATE_CHANGED:
|
||||
case MR_EVENT_CONFIGURE_ENDED:
|
||||
AndroidUtilities.runOnUIThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
NotificationCenter.getInstance().postNotificationName(NotificationCenter.connectionStateChanged, (int)data1);
|
||||
NotificationCenter.getInstance().postNotificationName(NotificationCenter.configureEnded, (int)data1);
|
||||
}
|
||||
});
|
||||
return 0;
|
||||
|
||||
case MR_EVENT_CONFIGURE_PROGRESS:
|
||||
AndroidUtilities.runOnUIThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
NotificationCenter.getInstance().postNotificationName(NotificationCenter.configureProgress, (int)data1);
|
||||
}
|
||||
});
|
||||
return 0;
|
||||
@@ -255,22 +259,121 @@ public class MrMailbox {
|
||||
public void run() {
|
||||
reloadMainChatlist();
|
||||
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces,
|
||||
MessagesController.UPDATE_MASK_NAME|MessagesController.UPDATE_MASK_CHAT_NAME|
|
||||
MessagesController.UPDATE_MASK_CHAT_MEMBERS|MessagesController.UPDATE_MASK_AVATAR);
|
||||
UPDATE_MASK_NAME|UPDATE_MASK_CHAT_NAME|
|
||||
UPDATE_MASK_CHAT_MEMBERS|UPDATE_MASK_AVATAR);
|
||||
}
|
||||
});
|
||||
return 0;
|
||||
|
||||
case MR_EVENT_REPORT:
|
||||
case MR_EVENT_INFO:
|
||||
Log.i("DeltaChat", CPtr2String(data2));
|
||||
if( BuildConfig.BUILD_TYPE.equals("debug") ) {
|
||||
FileLog.i("DeltaChat", CPtr2String(data2)); // TODO: Can be removed as soon as notifications are reliable.
|
||||
}
|
||||
break;
|
||||
|
||||
case MR_EVENT_WARNING:
|
||||
Log.w("DeltaChat", CPtr2String(data2));
|
||||
if( BuildConfig.BUILD_TYPE.equals("debug") ) {
|
||||
FileLog.w("DeltaChat", CPtr2String(data2)); // TODO: Can be removed as soon as notifications are reliable.
|
||||
}
|
||||
break;
|
||||
|
||||
case MR_EVENT_ERROR:
|
||||
Log.e("DeltaChat", CPtr2String(data2));
|
||||
if( BuildConfig.BUILD_TYPE.equals("debug") ) {
|
||||
FileLog.e("DeltaChat", CPtr2String(data2)); // TODO: Can be removed as soon as notifications are reliable.
|
||||
}
|
||||
synchronized (m_lastErrorLock) {
|
||||
m_lastErrorCode = (int)data1;
|
||||
m_lastErrorString = CPtr2String(data2);
|
||||
}
|
||||
AndroidUtilities.runOnUIThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if(data1==MR_REPORT_ERR_SELF_NOT_IN_GROUP) {
|
||||
NotificationCenter.getInstance().postNotificationName(NotificationCenter.errSelfNotInGroup);
|
||||
synchronized (m_lastErrorLock) {
|
||||
if( m_showNextErrorAsToast ) {
|
||||
if(ForegroundDetector.getInstance().isForeground()) {
|
||||
AndroidUtilities.showHint(ApplicationLoader.applicationContext, m_lastErrorString);
|
||||
}
|
||||
}
|
||||
m_showNextErrorAsToast = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
return 0;
|
||||
|
||||
case MR_EVENT_GET_STRING:
|
||||
String s = "ErrStrBadId";
|
||||
switch( (int)data1 ) {
|
||||
// the string-IDs are defined in the backend; as this is the only place where they're used, there is no benefit in creating an enum or sth. like that.
|
||||
case 1: s = ApplicationLoader.applicationContext.getString(R.string.NoMessages); break;
|
||||
case 2: s = ApplicationLoader.applicationContext.getString(R.string.FromSelf); break;
|
||||
case 3: s = ApplicationLoader.applicationContext.getString(R.string.Draft); break;
|
||||
case 7: s = ApplicationLoader.applicationContext.getString(R.string.AttachVoiceMessage); break;
|
||||
case 8: s = ApplicationLoader.applicationContext.getString(R.string.Deaddrop); break;
|
||||
case 9: s = ApplicationLoader.applicationContext.getString(R.string.AttachPhoto); break;
|
||||
case 10: s = ApplicationLoader.applicationContext.getString(R.string.AttachVideo); break;
|
||||
case 11: s = ApplicationLoader.applicationContext.getString(R.string.Audio); break;
|
||||
case 12: s = ApplicationLoader.applicationContext.getString(R.string.AttachDocument); break;
|
||||
case 13: s = ApplicationLoader.applicationContext.getString(R.string.DefaultStatusText); break;
|
||||
case 14: s = ApplicationLoader.applicationContext.getString(R.string.MsgNewGroupDraft); break;
|
||||
case 15: s = ApplicationLoader.applicationContext.getString(R.string.MsgGroupNameChanged); break;
|
||||
case 16: s = ApplicationLoader.applicationContext.getString(R.string.MsgGroupImageChanged); break;
|
||||
case 17: s = ApplicationLoader.applicationContext.getString(R.string.MsgMemberAddedToGroup); break;
|
||||
case 18: s = ApplicationLoader.applicationContext.getString(R.string.MsgMemberRemovedFromToGroup); break;
|
||||
case 19: s = ApplicationLoader.applicationContext.getString(R.string.MsgGroupLeft); break;
|
||||
case 20: s = ApplicationLoader.applicationContext.getString(R.string.Error); break;
|
||||
case 21: s = ApplicationLoader.applicationContext.getString(R.string.ErrSelfNotInGroup); break;
|
||||
case 22: s = ApplicationLoader.applicationContext.getString(R.string.NoNetwork); break;
|
||||
}
|
||||
return String2CPtr(s);
|
||||
|
||||
case MR_EVENT_GET_QUANTITIY_STRING:
|
||||
String sp = "ErrQtyStrBadId";
|
||||
switch( (int)data1 ) {
|
||||
// the string-IDs are defined in the backend; as this is the only place where they're used, there is no benefit in creating an enum or sth. like that.
|
||||
case 4: sp = ApplicationLoader.applicationContext.getResources().getQuantityString(R.plurals.Members, (int)data2, (int)data2); break;
|
||||
case 6: sp = ApplicationLoader.applicationContext.getResources().getQuantityString(R.plurals.Contacts, (int)data2, (int)data2); break;
|
||||
}
|
||||
return String2CPtr(sp);
|
||||
|
||||
case MR_EVENT_IS_ONLINE:
|
||||
return ApplicationLoader.isNetworkOnline()? 1 : 0;
|
||||
|
||||
case MR_EVENT_HTTP_GET:
|
||||
String httpContent = null;
|
||||
try {
|
||||
URL url = new URL(CPtr2String(data1));
|
||||
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
|
||||
try {
|
||||
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
|
||||
|
||||
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
|
||||
StringBuilder total = new StringBuilder();
|
||||
String line;
|
||||
while ((line = r.readLine()) != null) {
|
||||
total.append(line).append('\n');
|
||||
}
|
||||
httpContent = total.toString();
|
||||
} finally {
|
||||
urlConnection.disconnect();
|
||||
}
|
||||
}
|
||||
catch(Exception e) {}
|
||||
return String2CPtr(httpContent);
|
||||
|
||||
case MR_EVENT_WAKE_LOCK:
|
||||
if( data1 != 0 ) {
|
||||
ApplicationLoader.backendWakeLock.acquire();
|
||||
}
|
||||
else {
|
||||
if( !ApplicationLoader.wakeupWakeLock.isHeld()) {
|
||||
ApplicationLoader.wakeupWakeLock.acquire(1 * 1000); /* make sure, subsequent release/acquires do not make the CPU sleep */
|
||||
}
|
||||
ApplicationLoader.backendWakeLock.release();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -279,6 +382,14 @@ public class MrMailbox {
|
||||
/* additional functions that are not 1:1 available in the backend
|
||||
**********************************************************************************************/
|
||||
|
||||
public static void log_i(String tag, String msg)
|
||||
{
|
||||
Log.i(tag, msg);
|
||||
if( BuildConfig.BUILD_TYPE.equals("debug") ) {
|
||||
FileLog.i(tag, msg); // TODO: Can be removed as soon as notifications are reliable.
|
||||
}
|
||||
}
|
||||
|
||||
public static MrChatlist m_currChatlist = new MrChatlist(0);
|
||||
public native static int getCurrentTime ();
|
||||
public static void reloadMainChatlist()
|
||||
@@ -304,33 +415,50 @@ public class MrMailbox {
|
||||
});
|
||||
}
|
||||
|
||||
public static void initStockStrings()
|
||||
{
|
||||
MrStockAddStr(1, LocaleController.getString("NoMessages", R.string.NoMessages));
|
||||
MrStockAddStr(2, LocaleController.getString("FromSelf", R.string.FromSelf));
|
||||
MrStockAddStr(3, LocaleController.getString("Draft", R.string.Draft));
|
||||
MrStockAddStr(4, LocaleController.getString("MemberSg", R.string.MemberSg));
|
||||
MrStockAddStr(5, LocaleController.getString("MemberPl", R.string.MemberPl));
|
||||
MrStockAddStr(6, LocaleController.getString("ContactSg", R.string.ContactSg));
|
||||
MrStockAddStr(7, LocaleController.getString("ContactPl", R.string.ContactPl));
|
||||
MrStockAddStr(8, LocaleController.getString("Deaddrop", R.string.Deaddrop));
|
||||
MrStockAddStr(9, LocaleController.getString("AttachPhoto", R.string.AttachPhoto));
|
||||
MrStockAddStr(10, LocaleController.getString("AttachVideo", R.string.AttachVideo));
|
||||
MrStockAddStr(11, LocaleController.getString("AttachAudio", R.string.AttachAudio));
|
||||
MrStockAddStr(12, LocaleController.getString("AttachDocument", R.string.AttachDocument));
|
||||
MrStockAddStr(13, LocaleController.getString("DefaultStatusText", R.string.DefaultStatusText));
|
||||
MrStockAddStr(14, LocaleController.getString("MsgNewGroupDraft", R.string.MsgNewGroupDraft));
|
||||
MrStockAddStr(15, LocaleController.getString("MsgGroupNameChanged", R.string.MsgGroupNameChanged));
|
||||
MrStockAddStr(16, LocaleController.getString("MsgGroupImageChanged", R.string.MsgGroupImageChanged));
|
||||
MrStockAddStr(17, LocaleController.getString("MsgMemberAddedToGroup", R.string.MsgMemberAddedToGroup));
|
||||
MrStockAddStr(18, LocaleController.getString("MsgMemberRemovedFromToGroup", R.string.MsgMemberRemovedFromToGroup));
|
||||
MrStockAddStr(19, LocaleController.getString("MsgGroupLeft", R.string.MsgGroupLeft));
|
||||
}
|
||||
|
||||
public static String getInviteText() {
|
||||
String url = "https://getdelta.org";
|
||||
String email = getConfig("addr", "");
|
||||
String text = LocaleController.formatString("InviteText", R.string.InviteText, url, email);
|
||||
return text;
|
||||
}
|
||||
|
||||
public static TLRPC.User getUser(Integer id) {
|
||||
TLRPC.User u = new TLRPC.User(); // legacy function, information should be loaded as needed by the caller
|
||||
u.id = id;
|
||||
return u;
|
||||
}
|
||||
|
||||
public static void cancelTyping(int action, long dialog_id) {
|
||||
}
|
||||
|
||||
public static void sendTyping(final long dialog_id, final int action, int classGuid) {
|
||||
}
|
||||
|
||||
public static void markMessageContentAsRead(final MessageObject messageObject) {
|
||||
}
|
||||
|
||||
public static boolean isDialogMuted(long dialog_id) {
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
|
||||
int mute_type = preferences.getInt("notify2_" + dialog_id, 0);
|
||||
if (mute_type == 2) {
|
||||
return true;
|
||||
} else if (mute_type == 3) {
|
||||
int mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0);
|
||||
if (mute_until >= MrMailbox.getCurrentTime()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// legacy update masks
|
||||
public static final int UPDATE_MASK_NAME = 1;
|
||||
public static final int UPDATE_MASK_AVATAR = 2;
|
||||
public static final int UPDATE_MASK_STATUS = 4;
|
||||
public static final int UPDATE_MASK_CHAT_AVATAR = 8;
|
||||
public static final int UPDATE_MASK_CHAT_NAME = 16;
|
||||
public static final int UPDATE_MASK_CHAT_MEMBERS = 32;
|
||||
public static final int UPDATE_MASK_SELECT_DIALOG = 512;
|
||||
public static final int UPDATE_MASK_NEW_MESSAGE = 2048;
|
||||
public static final int UPDATE_MASK_SEND_STATE = 4096;
|
||||
}
|
||||
|
||||
@@ -27,8 +27,13 @@
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
import android.media.ThumbnailUtils;
|
||||
import android.provider.MediaStore;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class MrMsg {
|
||||
|
||||
private static final String TAG = "MrMsg";
|
||||
@@ -37,6 +42,7 @@ public class MrMsg {
|
||||
public final static int MR_MSG_TEXT = 10;
|
||||
public final static int MR_MSG_IMAGE = 20;
|
||||
public final static int MR_MSG_AUDIO = 40;
|
||||
public final static int MR_MSG_VOICE = 41;
|
||||
public final static int MR_MSG_VIDEO = 50;
|
||||
public final static int MR_MSG_FILE = 60;
|
||||
|
||||
@@ -90,17 +96,19 @@ public class MrMsg {
|
||||
return MrMsgGetToId(m_hMsg);
|
||||
}
|
||||
|
||||
public String getParam (int key, String def) {
|
||||
return MrMsgGetParam(m_hMsg, key, def);
|
||||
}
|
||||
public int getParamInt(int key, int def) {
|
||||
return MrMsgGetParamInt(m_hMsg, key, def);
|
||||
}
|
||||
public native String getParam(int key, String def);
|
||||
public native int getParamInt(int key, int def);
|
||||
public native void setParamInt(int key, int def);
|
||||
public native void saveParamToDisk();
|
||||
|
||||
public native int getBytes();
|
||||
public MrPoortext getSummary(MrChat chat) { return new MrPoortext(getSummaryCPtr(chat.getCPtr())); }
|
||||
private native long getSummaryCPtr(long hChat);
|
||||
public native String getSummarytext(int approx_characters);
|
||||
public MrPoortext getMediainfo() { return new MrPoortext(getMediainfoCPtr()); }
|
||||
private native long getMediainfoCPtr();
|
||||
public native String getFilename();
|
||||
public native int isIncreation();
|
||||
|
||||
private long m_hMsg; // must not be renamed as referenced by JNI under the name "m_hMsg"
|
||||
private native static void MrMsgUnref (long hMsg);
|
||||
@@ -112,8 +120,6 @@ public class MrMsg {
|
||||
private native static int MrMsgGetChatId (long hMsg);
|
||||
private native static int MrMsgGetFromId (long hMsg);
|
||||
private native static int MrMsgGetToId (long hMsg);
|
||||
private native static String MrMsgGetParam (long hMsg, int key, String def);
|
||||
private native static int MrMsgGetParamInt (long hMsg, int key, int def);
|
||||
|
||||
|
||||
/* additional functions that are not 1:1 available in the backend
|
||||
@@ -143,7 +149,6 @@ public class MrMsg {
|
||||
ret.unread = state!=MR_OUT_READ; // the state of outgoing messages
|
||||
ret.media_unread = ret.unread;
|
||||
ret.flags = 0; // posible flags: MESSAGE_FLAG_HAS_FROM_ID, however, this seems to be read only
|
||||
ret.post = false; // ? true=avatar wird in gruppen nicht angezeigt, wird aber in isFromUser() auch überprüft...
|
||||
ret.out = ret.from_id==MrContact.MR_CONTACT_ID_SELF; // true=outgoing message, read eg. in MessageObject.isOutOwner()
|
||||
ret.created_by_mr = true;
|
||||
|
||||
@@ -190,31 +195,63 @@ public class MrMsg {
|
||||
ret.message = "<cannot load image>";
|
||||
}
|
||||
}
|
||||
else if( type == MR_MSG_AUDIO || type == MR_MSG_VIDEO ) {
|
||||
else if( type == MR_MSG_AUDIO || type == MR_MSG_VOICE || type == MR_MSG_VIDEO || type == MR_MSG_FILE ) {
|
||||
String path = getParam('f', "");
|
||||
if( !path.isEmpty()) {
|
||||
ret.message = "-1"; // may be misused for video editing information
|
||||
ret.media = new TLRPC.TL_messageMediaDocument();
|
||||
ret.media.caption = "";
|
||||
ret.media.document = new TLRPC.TL_document();
|
||||
ret.media.document.file_name = getFilename();
|
||||
ret.media.document.mr_path = path;
|
||||
if( type == MR_MSG_AUDIO ) {
|
||||
ret.media.document.size = getBytes();
|
||||
if( type == MR_MSG_AUDIO || type == MR_MSG_VOICE ) {
|
||||
TLRPC.TL_documentAttributeAudio attr = new TLRPC.TL_documentAttributeAudio();
|
||||
attr.voice = true; // !voice = music
|
||||
attr.voice = type == MR_MSG_VOICE;
|
||||
attr.duration = getParamInt('d', 0) / 1000;
|
||||
ret.media.document.attributes.add(attr);
|
||||
}
|
||||
else if( type == MR_MSG_VIDEO) {
|
||||
else if( type == MR_MSG_VIDEO ) {
|
||||
File vfile = new File(path);
|
||||
File tfile = new File(MrMailbox.getBlobdir(), vfile.getName()+"-preview.jpg");
|
||||
if( !tfile.exists() ) {
|
||||
try {
|
||||
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.MINI_KIND);
|
||||
TLRPC.PhotoSize size = ImageLoader.scaleAndSaveImage(tfile, thumb, 90, 90, 55, false);
|
||||
size.location.mr_path = tfile.getAbsolutePath();
|
||||
size.type = "s";
|
||||
ret.media.document.thumb = size;
|
||||
|
||||
setParamInt('w', size.w);
|
||||
setParamInt('h', size.h);
|
||||
saveParamToDisk();
|
||||
}
|
||||
catch (Exception e) {}
|
||||
}
|
||||
else {
|
||||
TLRPC.PhotoSize size = new TLRPC.PhotoSize();
|
||||
size.location = new TLRPC.TL_fileLocation();
|
||||
size.location.mr_path = tfile.getAbsolutePath();
|
||||
size.location.local_id = -ret.id;
|
||||
size.w = getParamInt('w', 320);
|
||||
size.h = getParamInt('h', 240);
|
||||
size.type = "s";
|
||||
ret.media.document.thumb = size;
|
||||
}
|
||||
|
||||
TLRPC.TL_documentAttributeVideo attr = new TLRPC.TL_documentAttributeVideo();
|
||||
attr.duration = getParamInt('d', 0) / 1000;
|
||||
attr.w = getParamInt('w', 0);
|
||||
attr.h = getParamInt('h', 0);
|
||||
attr.w = getParamInt('w', 320);
|
||||
attr.h = getParamInt('h', 240);
|
||||
ret.media.document.attributes.add(attr);
|
||||
}
|
||||
else {
|
||||
ret.media.document.mime_type = getParam('m', "application/octet-stream");
|
||||
}
|
||||
|
||||
}
|
||||
else {
|
||||
ret.message = "<path missing>";
|
||||
ret.message = "<file path missing>";
|
||||
}
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -30,10 +30,10 @@ package com.b44t.messenger;
|
||||
|
||||
public class MrPoortext {
|
||||
|
||||
public final static int MR_TITLE_NORMAL = 0;
|
||||
public final static int MR_TITLE_DRAFT = 1;
|
||||
public final static int MR_TITLE_USERNAME = 2;
|
||||
public final static int MR_TITLE_SELF = 3;
|
||||
public final static int MR_TEXT1_NORMAL = 0;
|
||||
public final static int MR_TEXT1_DRAFT = 1;
|
||||
public final static int MR_TEXT1_USERNAME = 2;
|
||||
public final static int MR_TEXT1_SELF = 3;
|
||||
|
||||
public MrPoortext(long hPoortext) {
|
||||
m_hPoortext = hPoortext;
|
||||
@@ -44,16 +44,16 @@ public class MrPoortext {
|
||||
MrPoortextUnref(m_hPoortext);
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return MrPoortextGetTitle(m_hPoortext);
|
||||
public String getText1() {
|
||||
return MrPoortextGetText1(m_hPoortext);
|
||||
}
|
||||
|
||||
public int getTitleMeaning() {
|
||||
return MrPoortextGetTitleMeaning(m_hPoortext);
|
||||
public int getText1Meaning() {
|
||||
return MrPoortextGetText1Meaning(m_hPoortext);
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return MrPoortextGetText(m_hPoortext);
|
||||
public String getText2() {
|
||||
return MrPoortextGetText2(m_hPoortext);
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
@@ -66,9 +66,9 @@ public class MrPoortext {
|
||||
|
||||
private long m_hPoortext;
|
||||
private native static void MrPoortextUnref (long hPoortext);
|
||||
private native static String MrPoortextGetTitle (long hPoortext);
|
||||
private native static int MrPoortextGetTitleMeaning (long hPoortext);
|
||||
private native static String MrPoortextGetText (long hPoortext);
|
||||
private native static String MrPoortextGetText1 (long hPoortext);
|
||||
private native static int MrPoortextGetText1Meaning (long hPoortext);
|
||||
private native static String MrPoortextGetText2 (long hPoortext);
|
||||
private native static long MrPoortextGetTimestamp (long hPoortext);
|
||||
private native static int MrPoortextGetState (long hPoortext);
|
||||
}
|
||||
|
||||
@@ -1,604 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.Activity;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.BitmapShader;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.Shader;
|
||||
import android.media.MediaDescription;
|
||||
import android.media.MediaMetadata;
|
||||
import android.media.browse.MediaBrowser;
|
||||
import android.media.session.MediaSession;
|
||||
import android.media.session.PlaybackState;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Message;
|
||||
import android.os.Process;
|
||||
import android.os.SystemClock;
|
||||
import android.service.media.MediaBrowserService;
|
||||
|
||||
import com.b44t.messenger.audioinfo.AudioInfo;
|
||||
import com.b44t.ui.LaunchActivity;
|
||||
|
||||
import java.io.File;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public class MusicBrowserService extends MediaBrowserService implements NotificationCenter.NotificationCenterDelegate {
|
||||
|
||||
private static final String AUTO_APP_PACKAGE_NAME = "com.google.android.projection.gearhead";
|
||||
private static final String SLOT_RESERVATION_SKIP_TO_NEXT = "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_SKIP_TO_NEXT";
|
||||
private static final String SLOT_RESERVATION_SKIP_TO_PREV = "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_SKIP_TO_PREVIOUS";
|
||||
private static final String SLOT_RESERVATION_QUEUE = "com.google.android.gms.car.media.ALWAYS_RESERVE_SPACE_FOR.ACTION_QUEUE";
|
||||
|
||||
private MediaSession mediaSession;
|
||||
private static final String MEDIA_ID_ROOT = "__ROOT__";
|
||||
|
||||
private boolean chatsLoaded;
|
||||
private boolean loadingChats;
|
||||
private ArrayList<Integer> dialogs = new ArrayList<>();
|
||||
private HashMap<Integer, TLRPC.User> users = new HashMap<>();
|
||||
private HashMap<Integer, TLRPC.Chat> chats = new HashMap<>();
|
||||
private HashMap<Integer, ArrayList<MessageObject>> musicObjects = new HashMap<>();
|
||||
private HashMap<Integer, ArrayList<MediaSession.QueueItem>> musicQueues = new HashMap<>();
|
||||
|
||||
public static final String ACTION_CMD = "com.example.android.mediabrowserservice.ACTION_CMD";
|
||||
public static final String CMD_NAME = "CMD_NAME";
|
||||
public static final String CMD_PAUSE = "CMD_PAUSE";
|
||||
|
||||
private Paint roundPaint;
|
||||
private RectF bitmapRect;
|
||||
|
||||
private boolean serviceStarted;
|
||||
|
||||
private int lastSelectedDialog;
|
||||
|
||||
private static final int STOP_DELAY = 30000;
|
||||
|
||||
private DelayedStopHandler delayedStopHandler = new DelayedStopHandler(this);
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
ApplicationLoader.postInitApplication();
|
||||
|
||||
lastSelectedDialog = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE).getInt("auto_lastSelectedDialog", 0);
|
||||
|
||||
mediaSession = new MediaSession(this, "MusicService");
|
||||
setSessionToken(mediaSession.getSessionToken());
|
||||
mediaSession.setCallback(new MediaSessionCallback());
|
||||
mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
|
||||
|
||||
Context context = getApplicationContext();
|
||||
Intent intent = new Intent(context, LaunchActivity.class);
|
||||
PendingIntent pi = PendingIntent.getActivity(context, 99, intent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
mediaSession.setSessionActivity(pi);
|
||||
|
||||
Bundle extras = new Bundle();
|
||||
extras.putBoolean(SLOT_RESERVATION_QUEUE, true);
|
||||
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_PREV, true);
|
||||
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_NEXT, true);
|
||||
mediaSession.setExtras(extras);
|
||||
|
||||
updatePlaybackState(null);
|
||||
|
||||
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioPlayStateChanged);
|
||||
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidStarted);
|
||||
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidReset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent startIntent, int flags, int startId) {
|
||||
/*if (startIntent != null) {
|
||||
String action = startIntent.getAction();
|
||||
String command = startIntent.getStringExtra(CMD_NAME);
|
||||
if (ACTION_CMD.equals(action)) {
|
||||
if (CMD_PAUSE.equals(command)) {
|
||||
if (mPlayback != null && mPlayback.isPlaying()) {
|
||||
handlePauseRequest();
|
||||
}
|
||||
}
|
||||
}
|
||||
}*/
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
handleStopRequest(null);
|
||||
delayedStopHandler.removeCallbacksAndMessages(null);
|
||||
mediaSession.release();
|
||||
}
|
||||
|
||||
@Override
|
||||
public BrowserRoot onGetRoot(String clientPackageName, int clientUid, Bundle rootHints) {
|
||||
if (clientPackageName == null || Process.SYSTEM_UID != clientUid && Process.myUid() != clientUid && !clientPackageName.equals("com.google.android.mediasimulator") && !clientPackageName.equals("com.google.android.projection.gearhead")) {
|
||||
return null;
|
||||
}
|
||||
return new BrowserRoot(MEDIA_ID_ROOT, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoadChildren(final String parentMediaId, final Result<List<MediaBrowser.MediaItem>> result) {
|
||||
if (!chatsLoaded) {
|
||||
result.detach();
|
||||
if (loadingChats) {
|
||||
return;
|
||||
}
|
||||
loadingChats = true;
|
||||
/*
|
||||
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
ArrayList<Integer> usersToLoad = new ArrayList<>();
|
||||
ArrayList<Integer> chatsToLoad = new ArrayList<>();
|
||||
SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT DISTINCT uid FROM media_v2 WHERE uid != 0 AND mid > 0 AND type = %d", SharedMediaQuery.MEDIA_MUSIC));
|
||||
while (cursor.next()) {
|
||||
int lower_part = (int) cursor.longValue(0);
|
||||
if (lower_part == 0) {
|
||||
continue;
|
||||
}
|
||||
dialogs.add(lower_part);
|
||||
if (lower_part > 0) {
|
||||
usersToLoad.add(lower_part);
|
||||
} else {
|
||||
chatsToLoad.add(-lower_part);
|
||||
}
|
||||
}
|
||||
cursor.dispose();
|
||||
if (!dialogs.isEmpty()) {
|
||||
String ids = TextUtils.join(",", dialogs);
|
||||
cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT uid, data, mid FROM media_v2 WHERE uid IN (%s) AND mid > 0 AND type = %d ORDER BY date DESC, mid DESC", ids, SharedMediaQuery.MEDIA_MUSIC));
|
||||
while (cursor.next()) {
|
||||
NativeByteBuffer data = cursor.byteBufferValue(1);
|
||||
if (data != null) {
|
||||
TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
|
||||
data.reuse();
|
||||
if (MessageObject.isMusicMessage(message)) {
|
||||
int did = cursor.intValue(0);
|
||||
message.id = cursor.intValue(2);
|
||||
message.dialog_id = did;
|
||||
ArrayList<MessageObject> arrayList = musicObjects.get(did);
|
||||
ArrayList<MediaSession.QueueItem> arrayList1 = musicQueues.get(did);
|
||||
if (arrayList == null) {
|
||||
arrayList = new ArrayList<>();
|
||||
musicObjects.put(did, arrayList);
|
||||
arrayList1 = new ArrayList<>();
|
||||
musicQueues.put(did, arrayList1);
|
||||
}
|
||||
MessageObject messageObject = new MessageObject(message, null, false);
|
||||
arrayList.add(0, messageObject);
|
||||
MediaDescription.Builder builder = new MediaDescription.Builder().setMediaId(did + "_" + arrayList.size());
|
||||
builder.setTitle(messageObject.getMusicTitle());
|
||||
builder.setSubtitle(messageObject.getMusicAuthor());
|
||||
arrayList1.add(0, new MediaSession.QueueItem(builder.build(), arrayList1.size()));
|
||||
}
|
||||
}
|
||||
}
|
||||
cursor.dispose();
|
||||
if (!usersToLoad.isEmpty()) {
|
||||
ArrayList<TLRPC.User> usersArrayList = new ArrayList<>();
|
||||
//MessagesStorage.getInstance().getUsersInternal(TextUtils.join(",", usersToLoad), usersArrayList);
|
||||
for (int a = 0; a < usersArrayList.size(); a++) {
|
||||
TLRPC.User user = usersArrayList.get(a);
|
||||
users.put(user.id, user);
|
||||
}
|
||||
}
|
||||
if (!chatsToLoad.isEmpty()) {
|
||||
ArrayList<TLRPC.Chat> chatsArrayList = new ArrayList<>();
|
||||
//MessagesStorage.getInstance().getChatsInternal(TextUtils.join(",", chatsToLoad), chatsArrayList);
|
||||
for (int a = 0; a < chatsArrayList.size(); a++) {
|
||||
TLRPC.Chat chat = chatsArrayList.get(a);
|
||||
chats.put(chat.id, chat);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
AndroidUtilities.runOnUIThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
chatsLoaded = true;
|
||||
loadingChats = false;
|
||||
loadChildrenImpl(parentMediaId, result);
|
||||
if (lastSelectedDialog == 0 && !dialogs.isEmpty()) {
|
||||
lastSelectedDialog = dialogs.get(0);
|
||||
}
|
||||
if (lastSelectedDialog != 0) {
|
||||
ArrayList<MessageObject> arrayList = musicObjects.get(lastSelectedDialog);
|
||||
ArrayList<MediaSession.QueueItem> arrayList1 = musicQueues.get(lastSelectedDialog);
|
||||
if (arrayList != null && !arrayList.isEmpty()) {
|
||||
mediaSession.setQueue(arrayList1);
|
||||
if (lastSelectedDialog > 0) {
|
||||
TLRPC.User user = users.get(lastSelectedDialog);
|
||||
if (user != null) {
|
||||
mediaSession.setQueueTitle(ContactsController.formatName(user.first_name, user.last_name));
|
||||
} else {
|
||||
mediaSession.setQueueTitle("DELETED USER");
|
||||
}
|
||||
} else {
|
||||
TLRPC.Chat chat = chats.get(-lastSelectedDialog);
|
||||
if (chat != null) {
|
||||
mediaSession.setQueueTitle(chat.title);
|
||||
} else {
|
||||
mediaSession.setQueueTitle("DELETED CHAT");
|
||||
}
|
||||
}
|
||||
MessageObject messageObject = arrayList.get(0);
|
||||
MediaMetadata.Builder builder = new MediaMetadata.Builder();
|
||||
builder.putLong(MediaMetadata.METADATA_KEY_DURATION, messageObject.getDuration() * 1000);
|
||||
builder.putString(MediaMetadata.METADATA_KEY_ARTIST, messageObject.getMusicAuthor());
|
||||
builder.putString(MediaMetadata.METADATA_KEY_TITLE, messageObject.getMusicTitle());
|
||||
mediaSession.setMetadata(builder.build());
|
||||
}
|
||||
}
|
||||
updatePlaybackState(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
*/
|
||||
} else {
|
||||
loadChildrenImpl(parentMediaId, result);
|
||||
}
|
||||
}
|
||||
|
||||
private void loadChildrenImpl(final String parentMediaId, final Result<List<MediaBrowser.MediaItem>> result) {
|
||||
List<MediaBrowser.MediaItem> mediaItems = new ArrayList<>();
|
||||
|
||||
if (MEDIA_ID_ROOT.equals(parentMediaId)) {
|
||||
for (int a = 0; a < dialogs.size(); a++) {
|
||||
int did = dialogs.get(a);
|
||||
MediaDescription.Builder builder = new MediaDescription.Builder().setMediaId("__CHAT_" + did);
|
||||
TLRPC.FileLocation avatar = null;
|
||||
if (did > 0) {
|
||||
TLRPC.User user = users.get(did);
|
||||
if (user != null) {
|
||||
builder.setTitle(ContactsController.formatName(user.first_name, user.last_name));
|
||||
if (user.photo != null && user.photo.photo_small instanceof TLRPC.TL_fileLocation) {
|
||||
avatar = user.photo.photo_small;
|
||||
}
|
||||
} else {
|
||||
builder.setTitle("DELETED USER");
|
||||
}
|
||||
} else {
|
||||
TLRPC.Chat chat = chats.get(-did);
|
||||
if (chat != null) {
|
||||
builder.setTitle(chat.title);
|
||||
if (chat.photo != null && chat.photo.photo_small instanceof TLRPC.TL_fileLocation) {
|
||||
avatar = chat.photo.photo_small;
|
||||
}
|
||||
} else {
|
||||
builder.setTitle("DELETED CHAT");
|
||||
}
|
||||
}
|
||||
Bitmap bitmap = null;
|
||||
if (avatar != null) {
|
||||
bitmap = createRoundBitmap(FileLoader.getPathToAttach(avatar, true));
|
||||
if (bitmap != null) {
|
||||
builder.setIconBitmap(bitmap);
|
||||
}
|
||||
}
|
||||
if (avatar == null || bitmap == null) {
|
||||
builder.setIconUri(Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/drawable/contact_blue"));
|
||||
}
|
||||
mediaItems.add(new MediaBrowser.MediaItem(builder.build(), MediaBrowser.MediaItem.FLAG_BROWSABLE));
|
||||
}
|
||||
} else if (parentMediaId != null && parentMediaId.startsWith("__CHAT_")) {
|
||||
int did = 0;
|
||||
try {
|
||||
did = Integer.parseInt(parentMediaId.replace("__CHAT_", ""));
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
ArrayList<MessageObject> arrayList = musicObjects.get(did);
|
||||
if (arrayList != null) {
|
||||
for (int a = 0; a < arrayList.size(); a++) {
|
||||
MessageObject messageObject = arrayList.get(a);
|
||||
MediaDescription.Builder builder = new MediaDescription.Builder().setMediaId(did + "_" + a);
|
||||
builder.setTitle(messageObject.getMusicTitle());
|
||||
builder.setSubtitle(messageObject.getMusicAuthor());
|
||||
mediaItems.add(new MediaBrowser.MediaItem(builder.build(), MediaBrowser.MediaItem.FLAG_PLAYABLE));
|
||||
}
|
||||
}
|
||||
}
|
||||
result.sendResult(mediaItems);
|
||||
}
|
||||
|
||||
private Bitmap createRoundBitmap(File path) {
|
||||
try {
|
||||
BitmapFactory.Options options = new BitmapFactory.Options();
|
||||
options.inSampleSize = 2;
|
||||
Bitmap bitmap = BitmapFactory.decodeFile(path.toString(), options);
|
||||
if (bitmap != null) {
|
||||
Bitmap result = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
|
||||
result.eraseColor(Color.TRANSPARENT);
|
||||
Canvas canvas = new Canvas(result);
|
||||
BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
|
||||
if (roundPaint == null) {
|
||||
roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
bitmapRect = new RectF();
|
||||
}
|
||||
roundPaint.setShader(shader);
|
||||
bitmapRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
|
||||
canvas.drawRoundRect(bitmapRect, bitmap.getWidth(), bitmap.getHeight(), roundPaint);
|
||||
return result;
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private final class MediaSessionCallback extends MediaSession.Callback {
|
||||
@Override
|
||||
public void onPlay() {
|
||||
MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
|
||||
if (messageObject == null) {
|
||||
onPlayFromMediaId(lastSelectedDialog + "_" + 0, null);
|
||||
} else {
|
||||
MediaController.getInstance().playAudio(messageObject);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSkipToQueueItem(long queueId) {
|
||||
MediaController.getInstance().playMessageAtIndex((int) queueId);
|
||||
handlePlayRequest();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSeekTo(long position) {
|
||||
MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
|
||||
if (messageObject != null) {
|
||||
MediaController.getInstance().seekToProgress(messageObject, position / 1000 / (float) messageObject.getDuration());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPlayFromMediaId(String mediaId, Bundle extras) {
|
||||
String args[] = mediaId.split("_");
|
||||
if (args.length != 2) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
int did = Integer.parseInt(args[0]);
|
||||
int id = Integer.parseInt(args[1]);
|
||||
ArrayList<MessageObject> arrayList = musicObjects.get(did);
|
||||
ArrayList<MediaSession.QueueItem> arrayList1 = musicQueues.get(did);
|
||||
if (arrayList == null || id < 0 || id >= arrayList.size()) {
|
||||
return;
|
||||
}
|
||||
lastSelectedDialog = did;
|
||||
ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE).edit().putInt("auto_lastSelectedDialog", did).commit();
|
||||
MediaController.getInstance().setPlaylist(arrayList, arrayList.get(id), false);
|
||||
mediaSession.setQueue(arrayList1);
|
||||
if (did > 0) {
|
||||
TLRPC.User user = users.get(did);
|
||||
if (user != null) {
|
||||
mediaSession.setQueueTitle(ContactsController.formatName(user.first_name, user.last_name));
|
||||
} else {
|
||||
mediaSession.setQueueTitle("DELETED USER");
|
||||
}
|
||||
} else {
|
||||
TLRPC.Chat chat = chats.get(-did);
|
||||
if (chat != null) {
|
||||
mediaSession.setQueueTitle(chat.title);
|
||||
} else {
|
||||
mediaSession.setQueueTitle("DELETED CHAT");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
handlePlayRequest();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPause() {
|
||||
handlePauseRequest();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop() {
|
||||
handleStopRequest(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSkipToNext() {
|
||||
MediaController.getInstance().playNextMessage();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSkipToPrevious() {
|
||||
MediaController.getInstance().playPreviousMessage();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPlayFromSearch(String query, Bundle extras) {
|
||||
if (query == null || query.length() == 0) {
|
||||
return;
|
||||
}
|
||||
query = query.toLowerCase();
|
||||
for (int a = 0; a < dialogs.size(); a++) {
|
||||
int did = dialogs.get(a);
|
||||
if (did > 0) {
|
||||
TLRPC.User user = users.get(did);
|
||||
if (user == null) {
|
||||
continue;
|
||||
}
|
||||
if (user.first_name != null && user.first_name.startsWith(query) || user.last_name != null && user.last_name.startsWith(query)) {
|
||||
onPlayFromMediaId(did + "_" + 0, null);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
TLRPC.Chat chat = chats.get(-did);
|
||||
if (chat == null) {
|
||||
continue;
|
||||
}
|
||||
if (chat.title != null && chat.title.toLowerCase().contains(query)) {
|
||||
onPlayFromMediaId(did + "_" + 0, null);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void updatePlaybackState(String error) {
|
||||
long position = PlaybackState.PLAYBACK_POSITION_UNKNOWN;
|
||||
MessageObject playingMessageObject = MediaController.getInstance().getPlayingMessageObject();
|
||||
if (playingMessageObject != null) {
|
||||
position = playingMessageObject.audioProgressSec * 1000;
|
||||
}
|
||||
|
||||
PlaybackState.Builder stateBuilder = new PlaybackState.Builder().setActions(getAvailableActions());
|
||||
int state;
|
||||
if (playingMessageObject == null) {
|
||||
state = PlaybackState.STATE_STOPPED;
|
||||
} else {
|
||||
if (MediaController.getInstance().isDownloadingCurrentMessage()) {
|
||||
state = PlaybackState.STATE_BUFFERING;
|
||||
} else {
|
||||
state = MediaController.getInstance().isAudioPaused() ? PlaybackState.STATE_PAUSED : PlaybackState.STATE_PLAYING;
|
||||
}
|
||||
}
|
||||
|
||||
if (error != null) {
|
||||
stateBuilder.setErrorMessage(error);
|
||||
state = PlaybackState.STATE_ERROR;
|
||||
}
|
||||
stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());
|
||||
if (playingMessageObject != null) {
|
||||
stateBuilder.setActiveQueueItemId(MediaController.getInstance().getPlayingMessageObjectNum());
|
||||
} else {
|
||||
stateBuilder.setActiveQueueItemId(0);
|
||||
}
|
||||
|
||||
mediaSession.setPlaybackState(stateBuilder.build());
|
||||
}
|
||||
|
||||
private long getAvailableActions() {
|
||||
long actions = PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_FROM_MEDIA_ID | PlaybackState.ACTION_PLAY_FROM_SEARCH;
|
||||
MessageObject playingMessageObject = MediaController.getInstance().getPlayingMessageObject();
|
||||
if (playingMessageObject != null) {
|
||||
if (!MediaController.getInstance().isAudioPaused()) {
|
||||
actions |= PlaybackState.ACTION_PAUSE;
|
||||
}
|
||||
actions |= PlaybackState.ACTION_SKIP_TO_PREVIOUS;
|
||||
actions |= PlaybackState.ACTION_SKIP_TO_NEXT;
|
||||
}
|
||||
return actions;
|
||||
}
|
||||
|
||||
private void handleStopRequest(String withError) {
|
||||
delayedStopHandler.removeCallbacksAndMessages(null);
|
||||
delayedStopHandler.sendEmptyMessageDelayed(0, STOP_DELAY);
|
||||
updatePlaybackState(withError);
|
||||
stopSelf();
|
||||
serviceStarted = false;
|
||||
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioPlayStateChanged);
|
||||
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidStarted);
|
||||
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidReset);
|
||||
}
|
||||
|
||||
private void handlePlayRequest() {
|
||||
delayedStopHandler.removeCallbacksAndMessages(null);
|
||||
if (!serviceStarted) {
|
||||
startService(new Intent(getApplicationContext(), MusicBrowserService.class));
|
||||
serviceStarted = true;
|
||||
}
|
||||
|
||||
if (!mediaSession.isActive()) {
|
||||
mediaSession.setActive(true);
|
||||
}
|
||||
|
||||
MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
|
||||
if (messageObject == null) {
|
||||
return;
|
||||
}
|
||||
MediaMetadata.Builder builder = new MediaMetadata.Builder();
|
||||
builder.putLong(MediaMetadata.METADATA_KEY_DURATION, messageObject.getDuration() * 1000);
|
||||
builder.putString(MediaMetadata.METADATA_KEY_ARTIST, messageObject.getMusicAuthor());
|
||||
builder.putString(MediaMetadata.METADATA_KEY_TITLE, messageObject.getMusicTitle());
|
||||
AudioInfo audioInfo = MediaController.getInstance().getAudioInfo();
|
||||
if (audioInfo != null) {
|
||||
Bitmap bitmap = audioInfo.getCover();
|
||||
if (bitmap != null) {
|
||||
builder.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmap);
|
||||
}
|
||||
}
|
||||
mediaSession.setMetadata(builder.build());
|
||||
}
|
||||
|
||||
private void handlePauseRequest() {
|
||||
MediaController.getInstance().pauseAudio(MediaController.getInstance().getPlayingMessageObject());
|
||||
delayedStopHandler.removeCallbacksAndMessages(null);
|
||||
delayedStopHandler.sendEmptyMessageDelayed(0, STOP_DELAY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didReceivedNotification(int id, Object... args) {
|
||||
updatePlaybackState(null);
|
||||
handlePlayRequest();
|
||||
}
|
||||
|
||||
private static class DelayedStopHandler extends Handler {
|
||||
private final WeakReference<MusicBrowserService> mWeakReference;
|
||||
|
||||
private DelayedStopHandler(MusicBrowserService service) {
|
||||
mWeakReference = new WeakReference<>(service);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
MusicBrowserService service = mWeakReference.get();
|
||||
if (service != null) {
|
||||
MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
|
||||
if (messageObject != null && !MediaController.getInstance().isAudioPaused()) {
|
||||
return;
|
||||
}
|
||||
service.stopSelf();
|
||||
service.serviceStarted = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,10 +61,10 @@ public class MusicPlayerReceiver extends BroadcastReceiver {
|
||||
case KeyEvent.KEYCODE_MEDIA_STOP:
|
||||
break;
|
||||
case KeyEvent.KEYCODE_MEDIA_NEXT:
|
||||
MediaController.getInstance().playNextMessage();
|
||||
MediaController.getInstance().playNextMessage(+1, false);
|
||||
break;
|
||||
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
|
||||
MediaController.getInstance().playPreviousMessage();
|
||||
MediaController.getInstance().playNextMessage(-1, false);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
@@ -73,11 +73,11 @@ public class MusicPlayerReceiver extends BroadcastReceiver {
|
||||
} else if (intent.getAction().equals(MusicPlayerService.NOTIFY_PAUSE) || intent.getAction().equals(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
|
||||
MediaController.getInstance().pauseAudio(MediaController.getInstance().getPlayingMessageObject());
|
||||
} else if (intent.getAction().equals(MusicPlayerService.NOTIFY_NEXT)) {
|
||||
MediaController.getInstance().playNextMessage();
|
||||
MediaController.getInstance().playNextMessage(+1, false);
|
||||
} else if (intent.getAction().equals(MusicPlayerService.NOTIFY_CLOSE)) {
|
||||
MediaController.getInstance().cleanupPlayer(true, true);
|
||||
} else if (intent.getAction().equals(MusicPlayerService.NOTIFY_PREVIOUS)) {
|
||||
MediaController.getInstance().playPreviousMessage();
|
||||
MediaController.getInstance().playNextMessage(-1, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,6 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
|
||||
private RemoteControlClient remoteControlClient;
|
||||
private AudioManager audioManager;
|
||||
|
||||
private static boolean supportBigNotifications = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
|
||||
private static boolean supportLockScreenControls = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
|
||||
|
||||
@Override
|
||||
@@ -97,7 +96,7 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
|
||||
remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE |
|
||||
RemoteControlClient.FLAG_KEY_MEDIA_STOP | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
createNotification(messageObject);
|
||||
@@ -108,95 +107,70 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
|
||||
}
|
||||
|
||||
@SuppressLint("NewApi")
|
||||
private void createNotification(MessageObject messageObject) {
|
||||
String songName = messageObject.getMusicTitle();
|
||||
String authorName = messageObject.getMusicAuthor();
|
||||
private void createNotification(MessageObject messageObject)
|
||||
{
|
||||
AudioInfo audioInfo = MediaController.getInstance().getAudioInfo();
|
||||
|
||||
RemoteViews simpleContentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.player_small_notification);
|
||||
RemoteViews expandedView = null;
|
||||
if (supportBigNotifications) {
|
||||
expandedView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.player_big_notification);
|
||||
MrPoortext pt = MrMailbox.getMsg(messageObject.getId()).getMediainfo();
|
||||
String authorName = pt.getText1();
|
||||
String songName = pt.getText2();
|
||||
if( songName == null || songName.length()==0 ) {
|
||||
TLRPC.Document document = messageObject.messageOwner.media.document;
|
||||
for (int i = 0; i < document.attributes.size(); i++) {
|
||||
TLRPC.DocumentAttribute attr = document.attributes.get(i);
|
||||
if (attr instanceof TLRPC.TL_documentAttributeAudio) {
|
||||
authorName = attr.performer;
|
||||
songName = attr.title;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
|
||||
intent.setAction("com.b44t.messenger.openplayer");
|
||||
intent.setFlags(32768);
|
||||
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, 0);
|
||||
if( songName == null || songName.length()==0 ) {
|
||||
// preview of just recorded and not send voice messages
|
||||
authorName = ApplicationLoader.applicationContext.getString(R.string.FromSelf);
|
||||
songName = ApplicationLoader.applicationContext.getString(R.string.AttachVoiceMessage);
|
||||
}
|
||||
|
||||
RemoteViews simpleContentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.player_small_notification);
|
||||
|
||||
//Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
|
||||
//intent.setAction("com.b44t.messenger.openchat"+messageObject.getDialogId());
|
||||
//intent.setFlags(32768);
|
||||
//PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, 0);
|
||||
|
||||
Notification notification = new NotificationCompat.Builder(getApplicationContext())
|
||||
.setSmallIcon(R.drawable.player)
|
||||
.setContentIntent(contentIntent)
|
||||
.setSmallIcon(R.drawable.notification_player)
|
||||
//.setContentIntent(contentIntent)
|
||||
.setContentTitle(songName).build();
|
||||
|
||||
notification.contentView = simpleContentView;
|
||||
if (supportBigNotifications) {
|
||||
notification.bigContentView = expandedView;
|
||||
}
|
||||
|
||||
setListeners(simpleContentView);
|
||||
if (supportBigNotifications) {
|
||||
setListeners(expandedView);
|
||||
}
|
||||
|
||||
Bitmap albumArt = audioInfo != null ? audioInfo.getSmallCover() : null;
|
||||
if (albumArt != null) {
|
||||
notification.contentView.setImageViewBitmap(R.id.player_album_art, albumArt);
|
||||
if (supportBigNotifications) {
|
||||
notification.bigContentView.setImageViewBitmap(R.id.player_album_art, albumArt);
|
||||
}
|
||||
notification.contentView.setViewVisibility(R.id.player_album_art, View.VISIBLE);
|
||||
} else {
|
||||
notification.contentView.setImageViewResource(R.id.player_album_art, R.drawable.nocover_small);
|
||||
if (supportBigNotifications) {
|
||||
notification.bigContentView.setImageViewResource(R.id.player_album_art, R.drawable.nocover_big);
|
||||
}
|
||||
notification.contentView.setViewVisibility(R.id.player_album_art, View.GONE);
|
||||
}
|
||||
if (MediaController.getInstance().isDownloadingCurrentMessage()) {
|
||||
notification.contentView.setViewVisibility(R.id.player_pause, View.GONE);
|
||||
notification.contentView.setViewVisibility(R.id.player_play, View.GONE);
|
||||
notification.contentView.setViewVisibility(R.id.player_next, View.GONE);
|
||||
notification.contentView.setViewVisibility(R.id.player_previous, View.GONE);
|
||||
notification.contentView.setViewVisibility(R.id.player_progress_bar, View.VISIBLE);
|
||||
if (supportBigNotifications) {
|
||||
notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE);
|
||||
notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE);
|
||||
notification.bigContentView.setViewVisibility(R.id.player_next, View.GONE);
|
||||
notification.bigContentView.setViewVisibility(R.id.player_previous, View.GONE);
|
||||
notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.VISIBLE);
|
||||
}
|
||||
} else {
|
||||
notification.contentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
|
||||
|
||||
{
|
||||
notification.contentView.setViewVisibility(R.id.player_next, View.VISIBLE);
|
||||
notification.contentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
|
||||
if (supportBigNotifications) {
|
||||
notification.bigContentView.setViewVisibility(R.id.player_next, View.VISIBLE);
|
||||
notification.bigContentView.setViewVisibility(R.id.player_previous, View.VISIBLE);
|
||||
notification.bigContentView.setViewVisibility(R.id.player_progress_bar, View.GONE);
|
||||
}
|
||||
|
||||
if (MediaController.getInstance().isAudioPaused()) {
|
||||
notification.contentView.setViewVisibility(R.id.player_pause, View.GONE);
|
||||
notification.contentView.setViewVisibility(R.id.player_play, View.VISIBLE);
|
||||
if (supportBigNotifications) {
|
||||
notification.bigContentView.setViewVisibility(R.id.player_pause, View.GONE);
|
||||
notification.bigContentView.setViewVisibility(R.id.player_play, View.VISIBLE);
|
||||
}
|
||||
} else {
|
||||
notification.contentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
|
||||
notification.contentView.setViewVisibility(R.id.player_play, View.GONE);
|
||||
if (supportBigNotifications) {
|
||||
notification.bigContentView.setViewVisibility(R.id.player_pause, View.VISIBLE);
|
||||
notification.bigContentView.setViewVisibility(R.id.player_play, View.GONE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
notification.contentView.setTextViewText(R.id.player_song_name, songName);
|
||||
notification.contentView.setTextViewText(R.id.player_author_name, authorName);
|
||||
if (supportBigNotifications) {
|
||||
notification.bigContentView.setTextViewText(R.id.player_song_name, songName);
|
||||
notification.bigContentView.setTextViewText(R.id.player_author_name, authorName);
|
||||
}
|
||||
notification.flags |= Notification.FLAG_ONGOING_EVENT;
|
||||
startForeground(5, notification);
|
||||
|
||||
@@ -208,7 +182,7 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
|
||||
try {
|
||||
metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, audioInfo.getCover());
|
||||
} catch (Throwable e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
metadataEditor.apply();
|
||||
@@ -218,12 +192,16 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
|
||||
public void setListeners(RemoteViews view) {
|
||||
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PREVIOUS), PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
view.setOnClickPendingIntent(R.id.player_previous, pendingIntent);
|
||||
|
||||
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_CLOSE), PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
view.setOnClickPendingIntent(R.id.player_close, pendingIntent);
|
||||
|
||||
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PAUSE), PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
view.setOnClickPendingIntent(R.id.player_pause, pendingIntent);
|
||||
|
||||
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_NEXT), PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
view.setOnClickPendingIntent(R.id.player_next, pendingIntent);
|
||||
|
||||
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PLAY), PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
view.setOnClickPendingIntent(R.id.player_play, pendingIntent);
|
||||
}
|
||||
|
||||
@@ -1,212 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.os.Build;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
public class NativeLoader {
|
||||
|
||||
private final static int LIB_VERSION = 1;
|
||||
private final static String LIB_NAME = "messenger." + LIB_VERSION;
|
||||
private final static String LIB_SO_NAME = "lib" + LIB_NAME + ".so";
|
||||
private final static String LOCALE_LIB_SO_NAME = "lib" + LIB_NAME + "loc.so";
|
||||
//private String crashPath = "";
|
||||
|
||||
private static volatile boolean nativeLoaded = false;
|
||||
|
||||
private static File getNativeLibraryDir(Context context) {
|
||||
File f = null;
|
||||
if (context != null) {
|
||||
try {
|
||||
f = new File((String)ApplicationInfo.class.getField("nativeLibraryDir").get(context.getApplicationInfo()));
|
||||
} catch (Throwable th) {
|
||||
th.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (f == null) {
|
||||
f = new File(context.getApplicationInfo().dataDir, "lib");
|
||||
}
|
||||
if (f.isDirectory()) {
|
||||
return f;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean loadFromZip(Context context, File destDir, File destLocalFile, String folder) {
|
||||
try {
|
||||
for (File file : destDir.listFiles()) {
|
||||
file.delete();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
|
||||
ZipFile zipFile = null;
|
||||
InputStream stream = null;
|
||||
try {
|
||||
zipFile = new ZipFile(context.getApplicationInfo().sourceDir);
|
||||
ZipEntry entry = zipFile.getEntry("lib/" + folder + "/" + LIB_SO_NAME);
|
||||
if (entry == null) {
|
||||
throw new Exception("Unable to find file in apk:" + "lib/" + folder + "/" + LIB_NAME);
|
||||
}
|
||||
stream = zipFile.getInputStream(entry);
|
||||
|
||||
OutputStream out = new FileOutputStream(destLocalFile);
|
||||
byte[] buf = new byte[4096];
|
||||
int len;
|
||||
while ((len = stream.read(buf)) > 0) {
|
||||
Thread.yield();
|
||||
out.write(buf, 0, len);
|
||||
}
|
||||
out.close();
|
||||
|
||||
destLocalFile.setReadable(true, false);
|
||||
destLocalFile.setExecutable(true, false);
|
||||
destLocalFile.setWritable(true);
|
||||
|
||||
try {
|
||||
System.load(destLocalFile.getAbsolutePath());
|
||||
//init(context.getCacheDir().getAbsolutePath(), BuildVars.DEBUG_VERSION);
|
||||
nativeLoaded = true;
|
||||
} catch (Error e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
} finally {
|
||||
if (stream != null) {
|
||||
try {
|
||||
stream.close();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
if (zipFile != null) {
|
||||
try {
|
||||
zipFile.close();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static synchronized void initNativeLibs(Context context) {
|
||||
if (nativeLoaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
//String crashDir = context.getCacheDir().getAbsolutePath();
|
||||
|
||||
try {
|
||||
String folder;
|
||||
try {
|
||||
if (Build.CPU_ABI.equalsIgnoreCase("armeabi-v7a")) {
|
||||
folder = "armeabi-v7a";
|
||||
} else if (Build.CPU_ABI.equalsIgnoreCase("armeabi")) {
|
||||
folder = "armeabi";
|
||||
} else if (Build.CPU_ABI.equalsIgnoreCase("x86")) {
|
||||
folder = "x86";
|
||||
} else if (Build.CPU_ABI.equalsIgnoreCase("mips")) {
|
||||
folder = "mips";
|
||||
} else {
|
||||
folder = "armeabi";
|
||||
FileLog.e("messenger", "Unsupported arch: " + Build.CPU_ABI);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
folder = "armeabi";
|
||||
}
|
||||
|
||||
String javaArch = System.getProperty("os.arch");
|
||||
if (javaArch != null && javaArch.contains("686")) {
|
||||
folder = "x86";
|
||||
}
|
||||
|
||||
|
||||
File destFile = getNativeLibraryDir(context);
|
||||
if (destFile != null) {
|
||||
destFile = new File(destFile, LIB_SO_NAME);
|
||||
if (destFile.exists()) {
|
||||
FileLog.d("messenger", "load normal lib");
|
||||
try {
|
||||
System.loadLibrary(LIB_NAME);
|
||||
//init(crashDir, BuildVars.DEBUG_VERSION);
|
||||
nativeLoaded = true;
|
||||
return;
|
||||
} catch (Error e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File destDir = new File(context.getFilesDir(), "lib");
|
||||
destDir.mkdirs();
|
||||
|
||||
File destLocalFile = new File(destDir, LOCALE_LIB_SO_NAME);
|
||||
if (destLocalFile.exists()) {
|
||||
try {
|
||||
FileLog.d("messenger", "Load local lib");
|
||||
System.load(destLocalFile.getAbsolutePath());
|
||||
//init(crashDir, BuildVars.DEBUG_VERSION);
|
||||
nativeLoaded = true;
|
||||
return;
|
||||
} catch (Error e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
destLocalFile.delete();
|
||||
}
|
||||
|
||||
FileLog.e("messenger", "Library not found, arch = " + folder);
|
||||
|
||||
if (loadFromZip(context, destDir, destLocalFile, folder)) {
|
||||
return;
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
try {
|
||||
System.loadLibrary(LIB_NAME);
|
||||
//init(crashDir, BuildVars.DEBUG_VERSION);
|
||||
nativeLoaded = true;
|
||||
} catch (Error e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
}
|
||||
|
||||
//private static native void init(String path, boolean enableGoglBreakpad); // not needed
|
||||
//public static native void crash();
|
||||
}
|
||||
@@ -31,7 +31,8 @@ public class NotificationCenter {
|
||||
|
||||
private static int totalEvents = 1;
|
||||
|
||||
public static final int connectionStateChanged = totalEvents++;
|
||||
public static final int configureEnded = totalEvents++;
|
||||
public static final int configureProgress = totalEvents++;
|
||||
public static final int didReceivedNewMessages = totalEvents++;
|
||||
public static final int updateInterfaces = totalEvents++;
|
||||
public static final int dialogsNeedReload = totalEvents++;
|
||||
@@ -43,40 +44,22 @@ public class NotificationCenter {
|
||||
public static final int chatDidCreated = totalEvents++;
|
||||
public static final int mediaDidLoaded = totalEvents++;
|
||||
public static final int mediaCountDidLoaded = totalEvents++;
|
||||
public static final int dialogPhotosLoaded = totalEvents++;
|
||||
public static final int notificationsSettingsUpdated = totalEvents++;
|
||||
//public static final int pushMessagesUpdated = totalEvents++;
|
||||
public static final int blockedUsersDidLoaded = totalEvents++;
|
||||
public static final int openedChatChanged = totalEvents++;
|
||||
public static final int stopEncodingService = totalEvents++;
|
||||
public static final int mainUserInfoChanged = totalEvents++;
|
||||
public static final int recentImagesDidLoaded = totalEvents++;
|
||||
public static final int replaceMessagesObjects = totalEvents++;
|
||||
public static final int waveformCalculated = totalEvents++;
|
||||
public static final int didSetPasscode = totalEvents++;
|
||||
//public static final int screenStateChanged = totalEvents++; -- currently not used, but this may get handy
|
||||
public static final int stickersDidLoaded = totalEvents++;
|
||||
public static final int didReplacedPhotoInMemCache = totalEvents++;
|
||||
public static final int musicDidLoaded = totalEvents++;
|
||||
public static final int locationPermissionGranted = totalEvents++;
|
||||
public static final int wasUnableToFindCurrentLocation = totalEvents++;
|
||||
public static final int reloadHints = totalEvents++;
|
||||
|
||||
public static final int httpFileDidLoaded = totalEvents++;
|
||||
public static final int httpFileDidFailedLoad = totalEvents++;
|
||||
|
||||
public static final int messageThumbGenerated = totalEvents++;
|
||||
|
||||
public static final int wallpapersDidLoaded = totalEvents++;
|
||||
public static final int closeOtherAppActivities = totalEvents++;
|
||||
public static final int didUpdatedConnectionState = totalEvents++;
|
||||
public static final int emojiDidLoaded = totalEvents++;
|
||||
|
||||
public static final int FileDidUpload = totalEvents++;
|
||||
public static final int FileDidFailUpload = totalEvents++;
|
||||
public static final int FileUploadProgressChanged = totalEvents++;
|
||||
public static final int FileLoadProgressChanged = totalEvents++;
|
||||
public static final int FileDidLoaded = totalEvents++;
|
||||
public static final int FileDidFailedLoad = totalEvents++;
|
||||
public static final int FilePreparingStarted = totalEvents++;
|
||||
public static final int FileNewChunkAvailable = totalEvents++;
|
||||
public static final int FilePreparingFailed = totalEvents++;
|
||||
@@ -88,14 +71,11 @@ public class NotificationCenter {
|
||||
public static final int recordStarted = totalEvents++;
|
||||
public static final int recordStartError = totalEvents++;
|
||||
public static final int recordStopped = totalEvents++;
|
||||
public static final int screenshotTook = totalEvents++;
|
||||
public static final int albumsDidLoaded = totalEvents++;
|
||||
public static final int audioDidSent = totalEvents++;
|
||||
public static final int audioDidStarted = totalEvents++;
|
||||
public static final int audioRouteChanged = totalEvents++;
|
||||
|
||||
public static final int errSelfNotInGroup = totalEvents++;
|
||||
|
||||
private SparseArray<ArrayList<Object>> observers = new SparseArray<>();
|
||||
private SparseArray<ArrayList<Object>> removeAfterBroadcast = new SparseArray<>();
|
||||
private SparseArray<ArrayList<Object>> addAfterBroadcast = new SparseArray<>();
|
||||
@@ -170,17 +150,18 @@ public class NotificationCenter {
|
||||
}
|
||||
|
||||
public void postNotificationNameInternal(int id, boolean allowDuringAnimation, Object... args) {
|
||||
if (BuildVars.DEBUG_VERSION) {
|
||||
/*if (BuildConfig.BUILD_TYPE.equals("debug")) {
|
||||
if (Thread.currentThread() != ApplicationLoader.applicationHandler.getLooper().getThread()) {
|
||||
throw new RuntimeException("postNotificationName allowed only from MAIN thread");
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
if (!allowDuringAnimation && animationInProgress) {
|
||||
DelayedPost delayedPost = new DelayedPost(id, args);
|
||||
delayedPosts.add(delayedPost);
|
||||
if (BuildVars.DEBUG_VERSION) {
|
||||
FileLog.e("messenger", "delay post notification " + id + " with args count = " + args.length);
|
||||
}
|
||||
/*if (BuildConfig.BUILD_TYPE.equals("debug")) {
|
||||
Log.i("DeltaChat", "delay post notification " + id + " with args count = " + args.length);
|
||||
}*/
|
||||
return;
|
||||
}
|
||||
broadcasting++;
|
||||
@@ -217,11 +198,11 @@ public class NotificationCenter {
|
||||
}
|
||||
|
||||
public void addObserver(Object observer, int id) {
|
||||
if (BuildVars.DEBUG_VERSION) {
|
||||
/*if (BuildConfig.BUILD_TYPE.equals("debug")) {
|
||||
if (Thread.currentThread() != ApplicationLoader.applicationHandler.getLooper().getThread()) {
|
||||
throw new RuntimeException("addObserver allowed only from MAIN thread");
|
||||
}
|
||||
}
|
||||
}*/
|
||||
if (broadcasting != 0) {
|
||||
ArrayList<Object> arrayList = addAfterBroadcast.get(id);
|
||||
if (arrayList == null) {
|
||||
@@ -242,11 +223,11 @@ public class NotificationCenter {
|
||||
}
|
||||
|
||||
public void removeObserver(Object observer, int id) {
|
||||
if (BuildVars.DEBUG_VERSION) {
|
||||
/*if (BuildConfig.BUILD_TYPE.equals("debug")) {
|
||||
if (Thread.currentThread() != ApplicationLoader.applicationHandler.getLooper().getThread()) {
|
||||
throw new RuntimeException("removeObserver allowed only from MAIN thread");
|
||||
}
|
||||
}
|
||||
}*/
|
||||
if (broadcasting != 0) {
|
||||
ArrayList<Object> arrayList = removeAfterBroadcast.get(id);
|
||||
if (arrayList == null) {
|
||||
|
||||
@@ -33,6 +33,6 @@ public class NotificationDismissReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
|
||||
preferences.edit().putInt("dismissDate", intent.getIntExtra("messageDate", 0)).commit();
|
||||
preferences.edit().putInt("dismissDate", intent.getIntExtra("messageDate", 0)).apply();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,8 @@ import java.util.List;
|
||||
|
||||
public class NotificationsController {
|
||||
|
||||
private Context mContext;
|
||||
|
||||
public static final String EXTRA_VOICE_REPLY = "extra_voice_reply";
|
||||
|
||||
private DispatchQueue notificationsQueue = new DispatchQueue("notificationsQueue");
|
||||
@@ -68,7 +70,6 @@ public class NotificationsController {
|
||||
private HashMap<Long, Integer> autoNotificationsIds = new HashMap<>();
|
||||
private int wearNotificationId = 10000;
|
||||
private int autoNotificationId = 20000;
|
||||
public ArrayList<MessageObject> popupMessages = new ArrayList<>();
|
||||
private long opened_dialog_id = 0;
|
||||
private int total_unread_count = 0;
|
||||
private int personal_count = 0;
|
||||
@@ -93,7 +94,7 @@ public class NotificationsController {
|
||||
public static NotificationsController getInstance() {
|
||||
NotificationsController localInstance = Instance;
|
||||
if (localInstance == null) {
|
||||
synchronized (MessagesController.class) {
|
||||
synchronized (NotificationsController.class) {
|
||||
localInstance = Instance;
|
||||
if (localInstance == null) {
|
||||
Instance = localInstance = new NotificationsController();
|
||||
@@ -104,6 +105,7 @@ public class NotificationsController {
|
||||
}
|
||||
|
||||
public NotificationsController() {
|
||||
mContext = ApplicationLoader.applicationContext;
|
||||
notificationManager = NotificationManagerCompat.from(ApplicationLoader.applicationContext);
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
|
||||
inChatSoundEnabled = preferences.getBoolean("EnableInChatSound", true);
|
||||
@@ -111,26 +113,26 @@ public class NotificationsController {
|
||||
try {
|
||||
audioManager = (AudioManager) ApplicationLoader.applicationContext.getSystemService(Context.AUDIO_SERVICE);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
try {
|
||||
alarmManager = (AlarmManager) ApplicationLoader.applicationContext.getSystemService(Context.ALARM_SERVICE);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
|
||||
try {
|
||||
PowerManager pm = (PowerManager) ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE);
|
||||
notificationDelayWakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
|
||||
notificationDelayWakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "notificationDelayWakelock" /*any name*/);
|
||||
notificationDelayWakelock.setReferenceCounted(false);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
|
||||
notificationDelayRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
FileLog.e("messenger", "delay reached");
|
||||
//Log.i("DeltaChat", "delay reached");
|
||||
if (!delayedPushMessages.isEmpty()) {
|
||||
showOrUpdateNotification(true);
|
||||
delayedPushMessages.clear();
|
||||
@@ -140,7 +142,7 @@ public class NotificationsController {
|
||||
notificationDelayWakelock.release();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -168,7 +170,7 @@ public class NotificationsController {
|
||||
notificationDelayWakelock.release();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
setBadge(0);
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
|
||||
@@ -405,7 +407,7 @@ public class NotificationsController {
|
||||
return;
|
||||
}
|
||||
TLRPC.Message tmsg = mrMsg.get_TLRPC_Message();
|
||||
MessageObject msgDrawObj = new MessageObject(tmsg, null, true);
|
||||
MessageObject msgDrawObj = new MessageObject(tmsg, true);
|
||||
|
||||
delayedPushMessages.add(msgDrawObj);
|
||||
pushMessages.add(0, msgDrawObj);
|
||||
@@ -767,12 +769,12 @@ public class NotificationsController {
|
||||
intent.putExtra("badge_count_class_name", launcherClassName);
|
||||
ApplicationLoader.applicationContext.sendBroadcast(intent);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (Throwable e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -817,7 +819,7 @@ public class NotificationsController {
|
||||
alarmManager.cancel(pintent);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -836,7 +838,7 @@ public class NotificationsController {
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -845,7 +847,7 @@ public class NotificationsController {
|
||||
int notifyOverride = preferences.getInt("notify2_" + dialog_id, 0);
|
||||
if (notifyOverride == 3) {
|
||||
int muteUntil = preferences.getInt("notifyuntil_" + dialog_id, 0);
|
||||
if (muteUntil >= ConnectionsManager.getInstance().getCurrentTime()) {
|
||||
if (muteUntil >= MrMailbox.getCurrentTime()) {
|
||||
notifyOverride = 2;
|
||||
}
|
||||
}
|
||||
@@ -874,7 +876,7 @@ public class NotificationsController {
|
||||
total_unread_count = 0;
|
||||
setBadge(0);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -887,7 +889,7 @@ public class NotificationsController {
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -923,26 +925,26 @@ public class NotificationsController {
|
||||
soundPool.play(soundIn, 1.0f, 1.0f, 1, 0, 1.0f);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void scheduleNotificationDelay(boolean onlineReason) {
|
||||
/*private void scheduleNotificationDelay(boolean onlineReason) {
|
||||
try {
|
||||
FileLog.e("messenger", "delay notification start, onlineReason = " + onlineReason);
|
||||
//Log.i("DeltaChat", "delay notification start, onlineReason = " + onlineReason);
|
||||
notificationDelayWakelock.acquire(10000);
|
||||
AndroidUtilities.cancelRunOnUIThread(notificationDelayRunnable);
|
||||
AndroidUtilities.runOnUIThread(notificationDelayRunnable, (onlineReason ? 3 * 1000 : 1000));
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
showOrUpdateNotification(notifyCheck);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
protected void repeatNotificationMaybe() {
|
||||
notificationsQueue.postRunnable(new Runnable() {
|
||||
@@ -966,8 +968,6 @@ public class NotificationsController {
|
||||
}
|
||||
|
||||
try {
|
||||
ConnectionsManager.getInstance().resumeNetworkMaybe();
|
||||
|
||||
MessageObject lastMessageObject = pushMessages.get(0);
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
|
||||
int dismissDate = preferences.getInt("dismissDate", 0);
|
||||
@@ -1088,7 +1088,7 @@ public class NotificationsController {
|
||||
needVibrate = 2;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1106,7 +1106,7 @@ public class NotificationsController {
|
||||
|
||||
String name;
|
||||
if ( pushDialogs.size() > 1 || !showPreview ) {
|
||||
name = LocaleController.getString("AppName", R.string.AppName);
|
||||
name = mContext.getString(R.string.AppName);
|
||||
} else {
|
||||
if ( isGroupChat ) {
|
||||
name = mrChat.getName();
|
||||
@@ -1117,11 +1117,10 @@ public class NotificationsController {
|
||||
|
||||
String detailText;
|
||||
if (pushDialogs.size() == 1) {
|
||||
detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
|
||||
detailText = mContext.getResources().getQuantityString(R.plurals.NewMessages, total_unread_count, total_unread_count);
|
||||
} else {
|
||||
detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder", R.string.NotificationMessagesPeopleDisplayOrder,
|
||||
LocaleController.formatPluralString("NewMessages", total_unread_count),
|
||||
LocaleController.formatPluralString("FromChats", pushDialogs.size()));
|
||||
String newMessages = mContext.getResources().getQuantityString(R.plurals.NewMessages, total_unread_count, total_unread_count);
|
||||
detailText = mContext.getResources().getQuantityString(R.plurals.NewMessagesInChats, pushDialogs.size(), newMessages, pushDialogs.size());
|
||||
}
|
||||
|
||||
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ApplicationLoader.applicationContext)
|
||||
@@ -1273,7 +1272,7 @@ public class NotificationsController {
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1320,24 +1319,24 @@ public class NotificationsController {
|
||||
TLRPC.User user = null;
|
||||
String name;
|
||||
if (dialog_id > 0) {
|
||||
user = MessagesController.getInstance().getUser((int)dialog_id);
|
||||
user = MrMailbox.getUser((int)dialog_id);
|
||||
if (user == null) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
chat = MessagesController.getInstance().getChat(-(int)dialog_id);
|
||||
if (chat == null) {
|
||||
/*chat = MessagesController.getInstance().getChat(-(int)dialog_id);
|
||||
if (chat == null) {*/
|
||||
continue;
|
||||
}
|
||||
//}
|
||||
}
|
||||
TLRPC.FileLocation photoPath = null;
|
||||
if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
|
||||
name = LocaleController.getString("AppName", R.string.AppName);
|
||||
name = mContext.getString(R.string.AppName);
|
||||
} else {
|
||||
if (chat != null) {
|
||||
name = chat.title;
|
||||
} else {
|
||||
name = UserObject.getUserName(user);
|
||||
name = "ErrName"; // use MrContact.getName(), if really needed
|
||||
}
|
||||
/*if (chat != null) {
|
||||
if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) {
|
||||
@@ -1383,19 +1382,19 @@ public class NotificationsController {
|
||||
msgReplyIntent.putExtra("dialog_id", dialog_id);
|
||||
msgReplyIntent.putExtra("max_id", max_id);
|
||||
PendingIntent msgReplyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, notificationIdAuto, msgReplyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
RemoteInput remoteInputAuto = new RemoteInput.Builder(NotificationsController.EXTRA_VOICE_REPLY).setLabel(LocaleController.getString("Reply", R.string.Reply)).build();
|
||||
RemoteInput remoteInputAuto = new RemoteInput.Builder(NotificationsController.EXTRA_VOICE_REPLY).setLabel(mContext.getString(R.string.Reply)).build();
|
||||
unreadConvBuilder.setReplyAction(msgReplyPendingIntent, remoteInputAuto);
|
||||
|
||||
Intent replyIntent = new Intent(ApplicationLoader.applicationContext, WearReplyReceiver.class);
|
||||
replyIntent.putExtra("dialog_id", dialog_id);
|
||||
replyIntent.putExtra("max_id", max_id);
|
||||
PendingIntent replyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, notificationIdWear, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
|
||||
RemoteInput remoteInputWear = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel(LocaleController.getString("Reply", R.string.Reply)).build();
|
||||
RemoteInput remoteInputWear = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel(mContext.getString(R.string.Reply)).build();
|
||||
String replyToString;
|
||||
if (chat != null) {
|
||||
replyToString = LocaleController.formatString("ReplyToGroup", R.string.ReplyToGroup, name);
|
||||
replyToString = String.format(mContext.getString(R.string.ReplyToGroup), name);
|
||||
} else {
|
||||
replyToString = LocaleController.formatString("ReplyToUser", R.string.ReplyToUser, name);
|
||||
replyToString = String.format(mContext.getString(R.string.ReplyToContact), name);
|
||||
}
|
||||
wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon, replyToString, replyPendingIntent).addRemoteInput(remoteInputWear).build();
|
||||
}
|
||||
@@ -1472,7 +1471,7 @@ public class NotificationsController {
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
notificationsQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
@@ -1501,40 +1500,9 @@ public class NotificationsController {
|
||||
soundPool.play(soundOut, 1.0f, 1.0f, 1, 0, 1.0f);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void updateServerNotificationsSettings(long dialog_id) {
|
||||
// the following command is needed to reflect the changes in the GUI
|
||||
NotificationCenter.getInstance().postNotificationName(NotificationCenter.notificationsSettingsUpdated);
|
||||
|
||||
/*
|
||||
if ((int) dialog_id == 0) {
|
||||
return;
|
||||
}
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
|
||||
TLRPC.TL_account_updateNotifySettings req = new TLRPC.TL_account_updateNotifySettings();
|
||||
req.settings = new TLRPC.TL_inputPeerNotifySettings();
|
||||
req.settings.sound = "default";
|
||||
int mute_type = preferences.getInt("notify2_" + dialog_id, 0);
|
||||
if (mute_type == 3) {
|
||||
req.settings.mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0);
|
||||
} else {
|
||||
req.settings.mute_until = mute_type != 2 ? 0 : Integer.MAX_VALUE;
|
||||
}
|
||||
req.settings.show_previews = preferences.getBoolean("preview_" + dialog_id, true);
|
||||
req.settings.silent = preferences.getBoolean("silent_" + dialog_id, false);
|
||||
req.peer = new TLRPC.TL_inputNotifyPeer();
|
||||
((TLRPC.TL_inputNotifyPeer) req.peer).peer = MessagesController.getInputPeer((int) dialog_id);
|
||||
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
|
||||
@Override
|
||||
public void run(TLObject response, TLRPC.TL_error error) {
|
||||
|
||||
}
|
||||
});
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.IBinder;
|
||||
|
||||
public class NotificationsService extends Service {
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
FileLog.e("messenger", "service started");
|
||||
ApplicationLoader.postInitApplication();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void onDestroy() {
|
||||
FileLog.e("messenger", "service destroyed");
|
||||
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", MODE_PRIVATE);
|
||||
if (preferences.getBoolean("pushService", true)) {
|
||||
Intent intent = new Intent("com.b44t.start");
|
||||
sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,18 +26,17 @@ package com.b44t.messenger;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.util.Log;
|
||||
|
||||
public class ScreenReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
|
||||
FileLog.e("messenger", "screen off");
|
||||
ConnectionsManager.getInstance().setAppPaused(true, true);
|
||||
MrMailbox.log_i("DeltaChat", "*** Screen off");
|
||||
ApplicationLoader.isScreenOn = false;
|
||||
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
|
||||
FileLog.e("messenger", "screen on");
|
||||
ConnectionsManager.getInstance().setAppPaused(false, true);
|
||||
MrMailbox.log_i("DeltaChat", "*** Screen on");
|
||||
ApplicationLoader.isScreenOn = true;
|
||||
}
|
||||
//NotificationCenter.getInstance().postNotificationName(NotificationCenter.screenStateChanged);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,44 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
public class ShareBroadcastReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String url = intent.getDataString();
|
||||
if (url != null) {
|
||||
Intent shareIntent = new Intent(Intent.ACTION_SEND);
|
||||
shareIntent.setType("text/plain");
|
||||
shareIntent.putExtra(Intent.EXTRA_TEXT, url);
|
||||
Intent chooserIntent = Intent.createChooser(shareIntent, LocaleController.getString("ShareLink", R.string.ShareLink));
|
||||
chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
context.startActivity(chooserIntent);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,6 @@ public class TLRPC {
|
||||
}
|
||||
|
||||
public static class ChatPhoto extends TLObject {
|
||||
public FileLocation photo_small;
|
||||
public FileLocation photo_big;
|
||||
}
|
||||
|
||||
@@ -51,7 +50,6 @@ public class TLRPC {
|
||||
public int duration;
|
||||
public String alt;
|
||||
public InputStickerSet stickerset;
|
||||
public int flags;
|
||||
public boolean voice;
|
||||
public String title;
|
||||
public String performer;
|
||||
@@ -77,20 +75,7 @@ public class TLRPC {
|
||||
public static class TL_documentAttributeFilename extends DocumentAttribute {
|
||||
}
|
||||
|
||||
public static class messages_Messages extends TLObject {
|
||||
public ArrayList<Message> messages = new ArrayList<>();
|
||||
public ArrayList<Chat> chats = new ArrayList<>();
|
||||
public ArrayList<User> users = new ArrayList<>();
|
||||
public int flags;
|
||||
public int pts;
|
||||
public int count;
|
||||
}
|
||||
|
||||
public static class TL_messages_messages extends messages_Messages {
|
||||
}
|
||||
|
||||
public static class Peer extends TLObject {
|
||||
public final int channel_id = 0;
|
||||
public int user_id;
|
||||
public final int chat_id = 0;
|
||||
}
|
||||
@@ -98,99 +83,27 @@ public class TLRPC {
|
||||
public static class TL_peerUser extends Peer {
|
||||
}
|
||||
|
||||
public static class GeoPoint extends TLObject {
|
||||
public double _long;
|
||||
public double lat;
|
||||
}
|
||||
|
||||
public static class TL_geoPoint extends GeoPoint {
|
||||
}
|
||||
|
||||
public static class TL_messageMediaEmpty extends MessageMedia {
|
||||
}
|
||||
|
||||
public static class TL_messageMediaVenue extends MessageMedia {
|
||||
}
|
||||
|
||||
public static class TL_messageMediaDocument extends MessageMedia {
|
||||
}
|
||||
|
||||
public static class TL_messageMediaContact extends MessageMedia {
|
||||
}
|
||||
|
||||
public static class TL_messageMediaPhoto extends MessageMedia {
|
||||
}
|
||||
|
||||
public static class TL_messageMediaGeo extends MessageMedia {
|
||||
}
|
||||
|
||||
public static class PeerNotifySettings extends TLObject {
|
||||
public int flags;
|
||||
public boolean silent;
|
||||
public int mute_until;
|
||||
public String sound;
|
||||
}
|
||||
|
||||
public static class TL_peerNotifySettings extends PeerNotifySettings {
|
||||
}
|
||||
|
||||
public static class TL_messages_stickerSet extends TLObject {
|
||||
public StickerSet set;
|
||||
public ArrayList<Document> documents = new ArrayList<>();
|
||||
}
|
||||
|
||||
public static class InputGeoPoint extends TLObject {
|
||||
public double lat;
|
||||
public double _long;
|
||||
}
|
||||
|
||||
public static class TL_inputGeoPoint extends InputGeoPoint {
|
||||
}
|
||||
|
||||
public static class Audio extends TLObject {
|
||||
public long id;
|
||||
public int date;
|
||||
public int duration;
|
||||
public String mime_type;
|
||||
public int size;
|
||||
public int dc_id;
|
||||
public int user_id;
|
||||
public byte[] key;
|
||||
public byte[] iv;
|
||||
}
|
||||
|
||||
public static class ChatFull extends TLObject {
|
||||
public int flags;
|
||||
public int id;
|
||||
public String about;
|
||||
}
|
||||
|
||||
public static class WebPage extends TLObject {
|
||||
public int flags;
|
||||
public long id;
|
||||
public String url;
|
||||
public String type;
|
||||
public String title;
|
||||
public String description;
|
||||
public Photo photo;
|
||||
public int duration;
|
||||
public String author;
|
||||
public int date;
|
||||
public Document document;
|
||||
}
|
||||
|
||||
public static class InputFileLocation extends TLObject {
|
||||
public long id;
|
||||
public long access_hash;
|
||||
public long volume_id;
|
||||
public int local_id;
|
||||
public long secret;
|
||||
}
|
||||
|
||||
public static class TL_inputDocumentFileLocation extends InputFileLocation {
|
||||
}
|
||||
|
||||
public static class TL_inputFileLocation extends InputFileLocation {
|
||||
}
|
||||
|
||||
public static class User extends TLObject {
|
||||
@@ -198,17 +111,10 @@ public class TLRPC {
|
||||
public String first_name;
|
||||
public String last_name;
|
||||
public String username;
|
||||
public String phone;
|
||||
public UserProfilePhoto photo;
|
||||
public int flags;
|
||||
public boolean self;
|
||||
public boolean contact;
|
||||
public boolean min;
|
||||
}
|
||||
|
||||
public static class TL_userContact_old2 extends User {
|
||||
}
|
||||
|
||||
public static class Video extends TLObject {
|
||||
public long id;
|
||||
public int user_id;
|
||||
@@ -216,21 +122,10 @@ public class TLRPC {
|
||||
public int duration;
|
||||
public int size;
|
||||
public PhotoSize thumb;
|
||||
public int dc_id;
|
||||
public int w;
|
||||
public int h;
|
||||
public String mime_type;
|
||||
public String caption;
|
||||
public byte[] key;
|
||||
public byte[] iv;
|
||||
}
|
||||
|
||||
public static class InputDocument extends TLObject {
|
||||
public long id;
|
||||
public long access_hash;
|
||||
}
|
||||
|
||||
public static class TL_inputDocument extends InputDocument {
|
||||
}
|
||||
|
||||
public static class Document extends TLObject {
|
||||
@@ -253,53 +148,6 @@ public class TLRPC {
|
||||
public static class TL_document extends Document {
|
||||
}
|
||||
|
||||
public static class InputMedia extends TLObject {
|
||||
public InputFile file;
|
||||
public InputFile thumb;
|
||||
public String mime_type;
|
||||
public ArrayList<DocumentAttribute> attributes = new ArrayList<>();
|
||||
public String caption;
|
||||
public InputGeoPoint geo_point;
|
||||
public String title;
|
||||
public String address;
|
||||
public String provider;
|
||||
public String venue_id;
|
||||
public String phone_number;
|
||||
public String first_name;
|
||||
public String last_name;
|
||||
public String url;
|
||||
public String q;
|
||||
}
|
||||
|
||||
public static class TL_inputMediaContact extends InputMedia {
|
||||
}
|
||||
|
||||
public static class TL_inputMediaUploadedThumbDocument extends InputMedia {
|
||||
}
|
||||
|
||||
public static class TL_inputMediaDocument extends InputMedia {
|
||||
public InputDocument id;
|
||||
}
|
||||
|
||||
public static class TL_inputMediaGifExternal extends InputMedia {
|
||||
}
|
||||
|
||||
public static class TL_inputMediaGeoPoint extends InputMedia {
|
||||
}
|
||||
|
||||
public static class TL_inputMediaUploadedPhoto extends InputMedia {
|
||||
}
|
||||
|
||||
public static class TL_inputMediaVenue extends InputMedia {
|
||||
}
|
||||
|
||||
public static class TL_inputMediaUploadedDocument extends InputMedia {
|
||||
}
|
||||
|
||||
public static class TL_inputMediaPhoto extends InputMedia {
|
||||
public InputPhoto id;
|
||||
}
|
||||
|
||||
public static class InputStickerSet extends TLObject {
|
||||
public long id;
|
||||
public String short_name;
|
||||
@@ -308,11 +156,6 @@ public class TLRPC {
|
||||
public static class TL_inputStickerSetEmpty extends InputStickerSet {
|
||||
}
|
||||
|
||||
public static class InputEncryptedFile extends TLObject {
|
||||
public long id;
|
||||
public int parts;
|
||||
}
|
||||
|
||||
public static class UserProfilePhoto extends TLObject {
|
||||
public FileLocation photo_small;
|
||||
public FileLocation photo_big;
|
||||
@@ -320,7 +163,6 @@ public class TLRPC {
|
||||
|
||||
public static class Photo extends TLObject {
|
||||
public long id;
|
||||
public long access_hash;
|
||||
public int user_id;
|
||||
public int date;
|
||||
public String caption;
|
||||
@@ -335,17 +177,16 @@ public class TLRPC {
|
||||
|
||||
public static class Chat extends TLObject {
|
||||
public int flags;
|
||||
public boolean creator;
|
||||
public int id;
|
||||
public String title;
|
||||
public final ChatPhoto photo = null;
|
||||
public int date;
|
||||
public int version;
|
||||
public boolean editor;
|
||||
public final int version = 0;
|
||||
public final boolean editor = false;
|
||||
public String username;
|
||||
public boolean signatures;
|
||||
public boolean min;
|
||||
public String address;
|
||||
public final boolean signatures = false;
|
||||
public final boolean min = false;
|
||||
public final String address = null;
|
||||
}
|
||||
|
||||
public static class StickerSet extends TLObject {
|
||||
@@ -417,38 +258,15 @@ public class TLRPC {
|
||||
public static class TL_wallPaperSolid extends WallPaper {
|
||||
}
|
||||
|
||||
public static class InputPhoto extends TLObject {
|
||||
public long id;
|
||||
public long access_hash;
|
||||
}
|
||||
|
||||
public static class TL_inputPhoto extends InputPhoto {
|
||||
}
|
||||
|
||||
public static class InputPeer extends TLObject {
|
||||
public int user_id;
|
||||
public int chat_id;
|
||||
public int channel_id;
|
||||
}
|
||||
|
||||
public static class TL_inputPeerUser extends InputPeer {
|
||||
}
|
||||
|
||||
public static class MessageMedia extends TLObject {
|
||||
public byte[] bytes;
|
||||
public Photo photo;
|
||||
public GeoPoint geo;
|
||||
public String title;
|
||||
public String address;
|
||||
public String provider;
|
||||
public String venue_id;
|
||||
public Document document;
|
||||
public String caption;
|
||||
public String phone_number;
|
||||
public String first_name;
|
||||
public String last_name;
|
||||
public int user_id;
|
||||
public WebPage webpage;
|
||||
}
|
||||
|
||||
public static class Message extends TLObject {
|
||||
@@ -456,47 +274,35 @@ public class TLRPC {
|
||||
public int from_id;
|
||||
public Peer to_id;
|
||||
public int date;
|
||||
public int reply_to_msg_id;
|
||||
public long reply_to_random_id;
|
||||
public final int reply_to_msg_id = 0;
|
||||
public String message;
|
||||
public MessageMedia media;
|
||||
public int flags;
|
||||
public boolean media_unread;
|
||||
public boolean out;
|
||||
public boolean unread;
|
||||
public int views;
|
||||
public boolean silent;
|
||||
public boolean post;
|
||||
public final int views = 0;
|
||||
public final boolean silent = false;
|
||||
public final boolean post = false;// ? true=avatar wird in gruppen nicht angezeigt, wird aber in isFromUser() auch überprüft...
|
||||
public TL_messageFwdHeader fwd_from;
|
||||
public int send_state = 0; //custom
|
||||
public String attachPath = ""; //custom
|
||||
public HashMap<String, String> params; //custom
|
||||
public long random_id; //custom
|
||||
public long dialog_id; //custom
|
||||
public int layer; //custom
|
||||
public TLRPC.Message replyMessage; //custom
|
||||
public final int layer = 0; //custom
|
||||
public boolean created_by_mr;
|
||||
}
|
||||
|
||||
public static class TL_messageEmpty extends Message {
|
||||
}
|
||||
|
||||
public static class TL_message extends Message {
|
||||
}
|
||||
|
||||
public static class TL_dialog extends TLObject {
|
||||
final public int flags = 0;
|
||||
public Peer peer;
|
||||
public int top_message;
|
||||
public int unread_count;
|
||||
public PeerNotifySettings notify_settings;
|
||||
public int pts;
|
||||
public final int top_message = 0;
|
||||
public final int unread_count = 0;
|
||||
public final int pts = 0;
|
||||
public DraftMessage draft;
|
||||
public int last_message_date; //custom
|
||||
public long id; //custom
|
||||
}
|
||||
|
||||
public static class Vector extends TLObject {
|
||||
public ArrayList<Object> objects = new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
// ChooserTargetService, see https://developer.android.com/reference/android/service/chooser/ChooserTargetService.html
|
||||
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.Activity;
|
||||
import android.content.ComponentName;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Build;
|
||||
import android.service.chooser.ChooserTarget;
|
||||
import android.service.chooser.ChooserTargetService;
|
||||
|
||||
import com.b44t.ui.LaunchActivity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.M)
|
||||
public class TgChooserTargetService extends ChooserTargetService {
|
||||
|
||||
@Override
|
||||
public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) {
|
||||
final List<ChooserTarget> targets = new ArrayList<>();
|
||||
if (!UserConfig.isClientActivated()) {
|
||||
return targets;
|
||||
}
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
|
||||
if (!preferences.getBoolean("direct_share", true)) {
|
||||
return targets;
|
||||
}
|
||||
|
||||
ImageLoader imageLoader = ImageLoader.getInstance();
|
||||
final Semaphore semaphore = new Semaphore(0);
|
||||
final ComponentName componentName = new ComponentName(getPackageName(), LaunchActivity.class.getCanonicalName());
|
||||
/*
|
||||
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ArrayList<Integer> dialogs = new ArrayList<>();
|
||||
ArrayList<TLRPC.Chat> chats = new ArrayList<>();
|
||||
ArrayList<TLRPC.User> users = new ArrayList<>();
|
||||
try {
|
||||
ArrayList<Integer> usersToLoad = new ArrayList<>();
|
||||
usersToLoad.add(UserConfig.getClientUserId());
|
||||
ArrayList<Integer> chatsToLoad = new ArrayList<>();
|
||||
SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT did FROM dialogs ORDER BY date DESC LIMIT %d,%d", 0, 30));
|
||||
while (cursor.next()) {
|
||||
long id = cursor.longValue(0);
|
||||
|
||||
int lower_id = (int) id;
|
||||
int high_id = (int) (id >> 32);
|
||||
if (lower_id != 0) {
|
||||
if (high_id == 1) {
|
||||
continue;
|
||||
} else {
|
||||
if (lower_id > 0) {
|
||||
if (!usersToLoad.contains(lower_id)) {
|
||||
usersToLoad.add(lower_id);
|
||||
}
|
||||
} else {
|
||||
if (!chatsToLoad.contains(-lower_id)) {
|
||||
chatsToLoad.add(-lower_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
dialogs.add(lower_id);
|
||||
if (dialogs.size() == 8) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
cursor.dispose();
|
||||
if (!chatsToLoad.isEmpty()) {
|
||||
//MessagesStorage.getInstance().getChatsInternal(TextUtils.join(",", chatsToLoad), chats);
|
||||
}
|
||||
if (!usersToLoad.isEmpty()) {
|
||||
//MessagesStorage.getInstance().getUsersInternal(TextUtils.join(",", usersToLoad), users);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
for (int a = 0; a < dialogs.size(); a++) {
|
||||
Bundle extras = new Bundle();
|
||||
Icon icon = null;
|
||||
String name = null;
|
||||
int id = dialogs.get(a);
|
||||
if (id > 0) {
|
||||
for (int b = 0; b < users.size(); b++) {
|
||||
TLRPC.User user = users.get(b);
|
||||
if (user.id == id) {
|
||||
if (!user.bot) {
|
||||
extras.putLong("dialogId", (long) id);
|
||||
if (user.photo != null && user.photo.photo_small != null) {
|
||||
icon = createRoundBitmap(FileLoader.getPathToAttach(user.photo.photo_small, true));
|
||||
}
|
||||
name = ContactsController.formatName(user.first_name, user.last_name);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (int b = 0; b < chats.size(); b++) {
|
||||
TLRPC.Chat chat = chats.get(b);
|
||||
if (chat.id == -id) {
|
||||
if (!ChatObject.isNotInChat(chat) && (!ChatObject.isChannel(chat) || chat.megagroup)) {
|
||||
extras.putLong("dialogId", (long) id);
|
||||
if (chat.photo != null && chat.photo.photo_small != null) {
|
||||
icon = createRoundBitmap(FileLoader.getPathToAttach(chat.photo.photo_small, true));
|
||||
}
|
||||
name = chat.title;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (name != null) {
|
||||
if (icon == null) {
|
||||
icon = Icon.createWithResource(ApplicationLoader.applicationContext, R.drawable.logo_avatar);
|
||||
}
|
||||
targets.add(new ChooserTarget(name, icon, 1.0f, componentName, extras));
|
||||
}
|
||||
}
|
||||
semaphore.release();
|
||||
}
|
||||
});
|
||||
*/
|
||||
try {
|
||||
semaphore.acquire();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
/*
|
||||
private Icon createRoundBitmap(File path) {
|
||||
try {
|
||||
Bitmap bitmap = BitmapFactory.decodeFile(path.toString());
|
||||
if (bitmap != null) {
|
||||
Bitmap result = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
|
||||
result.eraseColor(Color.TRANSPARENT);
|
||||
Canvas canvas = new Canvas(result);
|
||||
BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
|
||||
if (roundPaint == null) {
|
||||
roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
bitmapRect = new RectF();
|
||||
}
|
||||
roundPaint.setShader(shader);
|
||||
bitmapRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
|
||||
canvas.drawRoundRect(bitmapRect, bitmap.getWidth(), bitmap.getHeight(), roundPaint);
|
||||
return Icon.createWithBitmap(result);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlarmManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
|
||||
public class TimerReceiver extends BroadcastReceiver {
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
|
||||
// acquire for 3 seconds, this should wake up the threads,
|
||||
// _if_ there is more to do, the backend acquires an additional wakelock using MR_EVENT_WAKE_LOCK
|
||||
ApplicationLoader.wakeupWakeLock.acquire(3*1000); // do this first!
|
||||
MrMailbox.log_i("DeltaChat", "*** TimerReceiver.onReceive()");
|
||||
|
||||
// we assume, the IMAP thread is alive. I cannot imagine, the thread was killed with the App being running.
|
||||
// (if the whole App was killed, the IMAP thread is already started by MrMailbox.connect() if we're here)
|
||||
// (the thread itself will reconnect to the IMAP server as needed)
|
||||
// however, it seems as if the threads sleep longer than ususal, check this by calling heartbeat() manually
|
||||
MrMailbox.heartbeat();
|
||||
|
||||
// create the next alarm in about a minute
|
||||
scheduleNextAlarm();
|
||||
}
|
||||
|
||||
public static void scheduleNextAlarm()
|
||||
{
|
||||
try {
|
||||
Intent intent = new Intent(ApplicationLoader.applicationContext, TimerReceiver.class);
|
||||
PendingIntent alarmIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 0, intent, 0);
|
||||
|
||||
long triggerAtMillis = System.currentTimeMillis() + 60 * 1000;
|
||||
|
||||
AlarmManager alarmManager = (AlarmManager) ApplicationLoader.applicationContext.getSystemService(Activity.ALARM_SERVICE);
|
||||
if( Build.VERSION.SDK_INT >= 23 ) {
|
||||
// a simple AlarmManager.set() is no longer send in the new DOZE mode
|
||||
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, alarmIntent);
|
||||
}
|
||||
else {
|
||||
alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, alarmIntent);
|
||||
}
|
||||
}
|
||||
catch(Exception e) { Log.e("DeltaChat", "Cannot create alarm.", e); }
|
||||
}
|
||||
}
|
||||
@@ -31,16 +31,8 @@ import java.io.File;
|
||||
|
||||
public class UserConfig {
|
||||
|
||||
private static TLRPC.User currentUser;
|
||||
public static boolean registeredForPush;
|
||||
public static String pushString = "";
|
||||
public static int lastSendMessageId = -210000;
|
||||
public static int lastLocalId = -210000;
|
||||
public static int lastBroadcastId = -1;
|
||||
public static String contactsHash = "";
|
||||
public static boolean blockedUsersLoaded;
|
||||
private final static Object sync = new Object();
|
||||
public static boolean saveIncomingPhotos;
|
||||
public static String passcodeHash = "";
|
||||
public static byte[] passcodeSalt = new byte[0];
|
||||
public static boolean appLocked;
|
||||
@@ -49,228 +41,38 @@ public class UserConfig {
|
||||
public static int lastPauseTime;
|
||||
public static boolean isWaitingForPasscodeEnter;
|
||||
public static boolean useFingerprint = true;
|
||||
public static String lastUpdateVersion;
|
||||
public static int lastContactsSyncTime;
|
||||
public static int lastHintsSyncTime;
|
||||
public static boolean draftsLoaded;
|
||||
|
||||
public static int migrateOffsetId = -1;
|
||||
public static int migrateOffsetDate = -1;
|
||||
public static int migrateOffsetUserId = -1;
|
||||
public static int migrateOffsetChatId = -1;
|
||||
public static int migrateOffsetChannelId = -1;
|
||||
public static long migrateOffsetAccess = -1;
|
||||
|
||||
public static int getNewMessageId() {
|
||||
int id;
|
||||
synchronized (sync) {
|
||||
id = lastSendMessageId;
|
||||
lastSendMessageId--;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
public static void saveConfig(boolean withFile) {
|
||||
saveConfig(withFile, null);
|
||||
}
|
||||
|
||||
public static void saveConfig(boolean withFile, File oldFile) {
|
||||
public static void saveConfig() {
|
||||
synchronized (sync) {
|
||||
try {
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE);
|
||||
SharedPreferences.Editor editor = preferences.edit();
|
||||
editor.putBoolean("registeredForPush", registeredForPush);
|
||||
editor.putString("pushString2", pushString);
|
||||
editor.putInt("lastSendMessageId", lastSendMessageId);
|
||||
editor.putInt("lastLocalId", lastLocalId);
|
||||
editor.putString("contactsHash", contactsHash);
|
||||
editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos);
|
||||
editor.putInt("lastBroadcastId", lastBroadcastId);
|
||||
editor.putBoolean("blockedUsersLoaded", blockedUsersLoaded);
|
||||
editor.putString("passcodeHash1", passcodeHash);
|
||||
editor.putString("passcodeSalt", passcodeSalt.length > 0 ? Base64.encodeToString(passcodeSalt, Base64.DEFAULT) : "");
|
||||
editor.putBoolean("appLocked", appLocked);
|
||||
editor.putInt("passcodeType", passcodeType);
|
||||
editor.putInt("autoLockIn", autoLockIn);
|
||||
editor.putInt("lastPauseTime", lastPauseTime);
|
||||
editor.putString("lastUpdateVersion2", lastUpdateVersion);
|
||||
editor.putInt("lastContactsSyncTime", lastContactsSyncTime);
|
||||
editor.putBoolean("useFingerprint", useFingerprint);
|
||||
editor.putInt("lastHintsSyncTime", lastHintsSyncTime);
|
||||
editor.putBoolean("draftsLoaded", draftsLoaded);
|
||||
|
||||
editor.putInt("migrateOffsetId", migrateOffsetId);
|
||||
if (migrateOffsetId != -1) {
|
||||
editor.putInt("migrateOffsetDate", migrateOffsetDate);
|
||||
editor.putInt("migrateOffsetUserId", migrateOffsetUserId);
|
||||
editor.putInt("migrateOffsetChatId", migrateOffsetChatId);
|
||||
editor.putInt("migrateOffsetChannelId", migrateOffsetChannelId);
|
||||
editor.putLong("migrateOffsetAccess", migrateOffsetAccess);
|
||||
}
|
||||
|
||||
/*
|
||||
if (currentUser != null) {
|
||||
if (withFile) {
|
||||
SerializedData data = new SerializedData();
|
||||
currentUser.serializeToStream(data);
|
||||
String userString = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT);
|
||||
editor.putString("user", userString);
|
||||
data.cleanup();
|
||||
}
|
||||
} else {
|
||||
editor.remove("user");
|
||||
}
|
||||
*/
|
||||
|
||||
editor.commit();
|
||||
if (oldFile != null) {
|
||||
oldFile.delete();
|
||||
}
|
||||
editor.apply();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isClientActivated() {
|
||||
return true; // EDIT BY MR -- for "real" checking, call MrMailbox.MrMailboxIsConfigured()
|
||||
/* EDIT BY MR
|
||||
synchronized (sync) {
|
||||
return currentUser != null;
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
public static int getClientUserId() {
|
||||
return 1; // we are user #1 by definition
|
||||
/* EDIT BY MR
|
||||
synchronized (sync) {
|
||||
return currentUser != null ? currentUser.id : 0;
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
public static TLRPC.User getCurrentUser() {
|
||||
synchronized (sync) {
|
||||
if( currentUser==null ) {
|
||||
currentUser = MrContact.contactId2user(1);
|
||||
}
|
||||
return currentUser;
|
||||
}
|
||||
}
|
||||
|
||||
public static void setCurrentUser(TLRPC.User user) {
|
||||
synchronized (sync) {
|
||||
currentUser = MrContact.contactId2user(1); // EDIT BY MR - force the current user to be user #1, normally this function should not be called at all
|
||||
}
|
||||
}
|
||||
|
||||
public static void loadConfig() {
|
||||
synchronized (sync) {
|
||||
/*
|
||||
final File configFile = new File(ApplicationLoader.getFilesDirFixed(), "user.dat");
|
||||
if (configFile.exists()) {
|
||||
try {
|
||||
SerializedData data = new SerializedData(configFile);
|
||||
int ver = data.readInt32(false);
|
||||
if (ver == 1) {
|
||||
int constructor = data.readInt32(false);
|
||||
currentUser = TLRPC.User.TLdeserialize(data, constructor, false);
|
||||
MessagesStorage.lastDateValue = data.readInt32(false);
|
||||
MessagesStorage.lastPtsValue = data.readInt32(false);
|
||||
MessagesStorage.lastSeqValue = data.readInt32(false);
|
||||
registeredForPush = data.readBool(false);
|
||||
pushString = data.readString(false);
|
||||
lastSendMessageId = data.readInt32(false);
|
||||
lastLocalId = data.readInt32(false);
|
||||
contactsHash = data.readString(false);
|
||||
data.readString(false);
|
||||
saveIncomingPhotos = data.readBool(false);
|
||||
//MessagesStorage.lastQtsValue = data.readInt32(false);
|
||||
//MessagesStorage.lastSecretVersion = data.readInt32(false);
|
||||
int val = data.readInt32(false);
|
||||
//if (val == 1) {
|
||||
// MessagesStorage.secretPBytes = data.readByteArray(false);
|
||||
//}
|
||||
//MessagesStorage.secretG = data.readInt32(false);
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
saveConfig(true, configFile);
|
||||
}
|
||||
});
|
||||
} else if (ver == 2) {
|
||||
int constructor = data.readInt32(false);
|
||||
currentUser = TLRPC.User.TLdeserialize(data, constructor, false);
|
||||
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE);
|
||||
registeredForPush = preferences.getBoolean("registeredForPush", false);
|
||||
pushString = preferences.getString("pushString2", "");
|
||||
lastSendMessageId = preferences.getInt("lastSendMessageId", -210000);
|
||||
lastLocalId = preferences.getInt("lastLocalId", -210000);
|
||||
contactsHash = preferences.getString("contactsHash", "");
|
||||
saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false);
|
||||
}
|
||||
if (lastLocalId > -210000) {
|
||||
lastLocalId = -210000;
|
||||
}
|
||||
if (lastSendMessageId > -210000) {
|
||||
lastSendMessageId = -210000;
|
||||
}
|
||||
data.cleanup();
|
||||
Utilities.stageQueue.postRunnable(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
saveConfig(true, configFile);
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
} else
|
||||
*/
|
||||
{
|
||||
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE);
|
||||
registeredForPush = preferences.getBoolean("registeredForPush", false);
|
||||
pushString = preferences.getString("pushString2", "");
|
||||
lastSendMessageId = preferences.getInt("lastSendMessageId", -210000);
|
||||
lastLocalId = preferences.getInt("lastLocalId", -210000);
|
||||
contactsHash = preferences.getString("contactsHash", "");
|
||||
saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false);
|
||||
lastBroadcastId = preferences.getInt("lastBroadcastId", -1);
|
||||
blockedUsersLoaded = preferences.getBoolean("blockedUsersLoaded", false);
|
||||
passcodeHash = preferences.getString("passcodeHash1", "");
|
||||
appLocked = preferences.getBoolean("appLocked", false);
|
||||
passcodeType = preferences.getInt("passcodeType", 0);
|
||||
autoLockIn = preferences.getInt("autoLockIn", 60 * 60);
|
||||
lastPauseTime = preferences.getInt("lastPauseTime", 0);
|
||||
useFingerprint = preferences.getBoolean("useFingerprint", true);
|
||||
lastUpdateVersion = preferences.getString("lastUpdateVersion2", "3.5");
|
||||
lastContactsSyncTime = preferences.getInt("lastContactsSyncTime", (int) (System.currentTimeMillis() / 1000) - 23 * 60 * 60);
|
||||
lastHintsSyncTime = preferences.getInt("lastHintsSyncTime", (int) (System.currentTimeMillis() / 1000) - 25 * 60 * 60);
|
||||
draftsLoaded = preferences.getBoolean("draftsLoaded", false);
|
||||
|
||||
migrateOffsetId = preferences.getInt("migrateOffsetId", 0);
|
||||
if (migrateOffsetId != -1) {
|
||||
migrateOffsetDate = preferences.getInt("migrateOffsetDate", 0);
|
||||
migrateOffsetUserId = preferences.getInt("migrateOffsetUserId", 0);
|
||||
migrateOffsetChatId = preferences.getInt("migrateOffsetChatId", 0);
|
||||
migrateOffsetChannelId = preferences.getInt("migrateOffsetChannelId", 0);
|
||||
migrateOffsetAccess = preferences.getLong("migrateOffsetAccess", 0);
|
||||
}
|
||||
|
||||
/*
|
||||
String user = preferences.getString("user", null);
|
||||
if (user != null) {
|
||||
byte[] userBytes = Base64.decode(user, Base64.DEFAULT);
|
||||
if (userBytes != null) {
|
||||
SerializedData data = new SerializedData(userBytes);
|
||||
currentUser = TLRPC.User.TLdeserialize(data, data.readInt32(false), false);
|
||||
data.cleanup();
|
||||
}
|
||||
}
|
||||
*/
|
||||
setCurrentUser(null);
|
||||
|
||||
String passcodeSaltString = preferences.getString("passcodeSalt", "");
|
||||
if (passcodeSaltString.length() > 0) {
|
||||
@@ -278,7 +80,6 @@ public class UserConfig {
|
||||
} else {
|
||||
passcodeSalt = new byte[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,9 +96,9 @@ public class UserConfig {
|
||||
System.arraycopy(passcodeBytes, 0, bytes, 16, passcodeBytes.length);
|
||||
System.arraycopy(passcodeSalt, 0, bytes, passcodeBytes.length + 16, 16);
|
||||
passcodeHash = Utilities.bytesToHex(Utilities.computeSHA256(bytes, 0, bytes.length));
|
||||
saveConfig(false);
|
||||
saveConfig();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
return result;
|
||||
@@ -311,7 +112,7 @@ public class UserConfig {
|
||||
String hash = Utilities.bytesToHex(Utilities.computeSHA256(bytes, 0, bytes.length));
|
||||
return passcodeHash.equals(hash);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
public class UserObject {
|
||||
|
||||
public static boolean isUserSelf(TLRPC.User user) {
|
||||
return user.self;
|
||||
}
|
||||
|
||||
public static String getUserName(TLRPC.User user) {
|
||||
return "ErrName"; // use MrContact.getName() instead
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,7 @@ public class Utilities {
|
||||
sUrandomIn.close();
|
||||
random.setSeed(buffer);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,15 +67,8 @@ public class Utilities {
|
||||
public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer);
|
||||
public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin);
|
||||
public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap);
|
||||
//private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
|
||||
public native static String readlink(String path);
|
||||
|
||||
/*
|
||||
public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
|
||||
aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);
|
||||
}
|
||||
*/
|
||||
|
||||
public static Integer parseInt(String value) {
|
||||
if (value == null) {
|
||||
return 0;
|
||||
@@ -88,7 +81,7 @@ public class Utilities {
|
||||
val = Integer.parseInt(num);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return val;
|
||||
}
|
||||
@@ -105,19 +98,11 @@ public class Utilities {
|
||||
val = Long.parseLong(num);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
public static String parseIntToString(String value) {
|
||||
Matcher matcher = pattern.matcher(value);
|
||||
if (matcher.find()) {
|
||||
return matcher.group(0);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
if (bytes == null) {
|
||||
return "";
|
||||
@@ -132,138 +117,17 @@ public class Utilities {
|
||||
return new String(hexChars);
|
||||
}
|
||||
|
||||
public static byte[] hexToBytes(String hex) {
|
||||
if (hex == null) {
|
||||
return null;
|
||||
}
|
||||
int len = hex.length();
|
||||
byte[] data = new byte[len / 2];
|
||||
for (int i = 0; i < len; i += 2) {
|
||||
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public static boolean isGoodPrime(byte[] prime, int g) {
|
||||
if (!(g >= 2 && g <= 7)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (prime.length != 256 || prime[0] >= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
BigInteger dhBI = new BigInteger(1, prime);
|
||||
|
||||
if (g == 2) { // p mod 8 = 7 for g = 2;
|
||||
BigInteger res = dhBI.mod(BigInteger.valueOf(8));
|
||||
if (res.intValue() != 7) {
|
||||
return false;
|
||||
}
|
||||
} else if (g == 3) { // p mod 3 = 2 for g = 3;
|
||||
BigInteger res = dhBI.mod(BigInteger.valueOf(3));
|
||||
if (res.intValue() != 2) {
|
||||
return false;
|
||||
}
|
||||
} else if (g == 5) { // p mod 5 = 1 or 4 for g = 5;
|
||||
BigInteger res = dhBI.mod(BigInteger.valueOf(5));
|
||||
int val = res.intValue();
|
||||
if (val != 1 && val != 4) {
|
||||
return false;
|
||||
}
|
||||
} else if (g == 6) { // p mod 24 = 19 or 23 for g = 6;
|
||||
BigInteger res = dhBI.mod(BigInteger.valueOf(24));
|
||||
int val = res.intValue();
|
||||
if (val != 19 && val != 23) {
|
||||
return false;
|
||||
}
|
||||
} else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7.
|
||||
BigInteger res = dhBI.mod(BigInteger.valueOf(7));
|
||||
int val = res.intValue();
|
||||
if (val != 3 && val != 5 && val != 6) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
String hex = bytesToHex(prime);
|
||||
if (hex.equals("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2));
|
||||
return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30));
|
||||
}
|
||||
|
||||
public static boolean isGoodGaAndGb(BigInteger g_a, BigInteger p) {
|
||||
return !(g_a.compareTo(BigInteger.valueOf(1)) != 1 || g_a.compareTo(p.subtract(BigInteger.valueOf(1))) != -1);
|
||||
}
|
||||
|
||||
public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) {
|
||||
if (arr1 == null || arr2 == null || offset1 < 0 || offset2 < 0 || arr1.length - offset1 != arr2.length - offset2 || arr1.length - offset1 < 0 || arr2.length - offset2 < 0) {
|
||||
return false;
|
||||
}
|
||||
boolean result = true;
|
||||
for (int a = offset1; a < arr1.length; a++) {
|
||||
if (arr1[a + offset1] != arr2[a + offset2]) {
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static byte[] computeSHA1(byte[] convertme, int offset, int len) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-1");
|
||||
md.update(convertme, offset, len);
|
||||
return md.digest();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return new byte[20];
|
||||
}
|
||||
|
||||
public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) {
|
||||
int oldp = convertme.position();
|
||||
int oldl = convertme.limit();
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-1");
|
||||
convertme.position(offset);
|
||||
convertme.limit(len);
|
||||
md.update(convertme);
|
||||
return md.digest();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
} finally {
|
||||
convertme.limit(oldl);
|
||||
convertme.position(oldp);
|
||||
}
|
||||
return new byte[20];
|
||||
}
|
||||
|
||||
public static byte[] computeSHA1(ByteBuffer convertme) {
|
||||
return computeSHA1(convertme, 0, convertme.limit());
|
||||
}
|
||||
|
||||
public static byte[] computeSHA1(byte[] convertme) {
|
||||
return computeSHA1(convertme, 0, convertme.length);
|
||||
}
|
||||
|
||||
public static byte[] computeSHA256(byte[] convertme, int offset, int len) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
md.update(convertme, offset, len);
|
||||
return md.digest();
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static long bytesToLong(byte[] bytes) {
|
||||
return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32)
|
||||
+ (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF);
|
||||
}
|
||||
|
||||
public static String MD5(String md5) {
|
||||
if (md5 == null) {
|
||||
return null;
|
||||
@@ -277,7 +141,7 @@ public class Utilities {
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (java.security.NoSuchAlgorithmException e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -23,50 +23,15 @@
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public class VideoEditedInfo {
|
||||
public long startTime;
|
||||
public long endTime;
|
||||
public int rotationValue;
|
||||
public int originalWidth;
|
||||
public int originalHeight;
|
||||
public int originalBitrate;
|
||||
public int resultWidth;
|
||||
public int resultHeight;
|
||||
public int bitrate;
|
||||
public int resultBitrate;
|
||||
public String originalPath;
|
||||
|
||||
public String getString() {
|
||||
return String.format(Locale.US, "-1_%d_%d_%d_%d_%d_%d_%d_%d_%s", startTime, endTime, rotationValue, originalWidth, originalHeight, bitrate, resultWidth, resultHeight, originalPath);
|
||||
}
|
||||
|
||||
public boolean parseString(String string) {
|
||||
if (string.length() < 6) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
String args[] = string.split("_");
|
||||
if (args.length >= 10) {
|
||||
startTime = Long.parseLong(args[1]);
|
||||
endTime = Long.parseLong(args[2]);
|
||||
rotationValue = Integer.parseInt(args[3]);
|
||||
originalWidth = Integer.parseInt(args[4]);
|
||||
originalHeight = Integer.parseInt(args[5]);
|
||||
bitrate = Integer.parseInt(args[6]);
|
||||
resultWidth = Integer.parseInt(args[7]);
|
||||
resultHeight = Integer.parseInt(args[8]);
|
||||
for (int a = 9; a < args.length; a++) {
|
||||
if (originalPath == null) {
|
||||
originalPath = args[a];
|
||||
} else {
|
||||
originalPath += "_" + args[a];
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Messenger Android Frontend
|
||||
* (C) 2013-2016 Nikolai Kudashov
|
||||
* (C) 2017 Björn Petersen
|
||||
* Contact: r10s@b44t.com, http://b44t.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License as published by the Free Software
|
||||
* Foundation, either version 3 of the License, or (at your option) any later
|
||||
* version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
* details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License along with
|
||||
* this program. If not, see http://www.gnu.org/licenses/ .
|
||||
*
|
||||
******************************************************************************/
|
||||
|
||||
|
||||
package com.b44t.messenger;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.IBinder;
|
||||
import android.support.v4.app.NotificationCompat;
|
||||
import android.support.v4.app.NotificationManagerCompat;
|
||||
|
||||
public class VideoEncodingService extends Service implements NotificationCenter.NotificationCenterDelegate {
|
||||
|
||||
private NotificationCompat.Builder builder = null;
|
||||
private String path = null;
|
||||
private int currentProgress = 0;
|
||||
|
||||
public VideoEncodingService() {
|
||||
super();
|
||||
NotificationCenter.getInstance().addObserver(this, NotificationCenter.FileUploadProgressChanged);
|
||||
NotificationCenter.getInstance().addObserver(this, NotificationCenter.stopEncodingService);
|
||||
}
|
||||
|
||||
public IBinder onBind(Intent arg2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void onDestroy() {
|
||||
stopForeground(true);
|
||||
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.FileUploadProgressChanged);
|
||||
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.stopEncodingService);
|
||||
FileLog.e("messenger", "destroy video service");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void didReceivedNotification(int id, Object... args) {
|
||||
if (id == NotificationCenter.FileUploadProgressChanged) {
|
||||
String fileName = (String)args[0];
|
||||
if (path != null && path.equals(fileName)) {
|
||||
Float progress = (Float) args[1];
|
||||
Boolean enc = (Boolean) args[2];
|
||||
currentProgress = (int)(progress * 100);
|
||||
builder.setProgress(100, currentProgress, currentProgress == 0);
|
||||
NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build());
|
||||
}
|
||||
} else if (id == NotificationCenter.stopEncodingService) {
|
||||
String filepath = (String)args[0];
|
||||
if (filepath == null || filepath.equals(path)) {
|
||||
stopSelf();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
path = intent.getStringExtra("path");
|
||||
if (path == null) {
|
||||
stopSelf();
|
||||
return Service.START_NOT_STICKY;
|
||||
}
|
||||
FileLog.e("messenger", "start video service");
|
||||
if (builder == null) {
|
||||
builder = new NotificationCompat.Builder(ApplicationLoader.applicationContext);
|
||||
builder.setSmallIcon(android.R.drawable.stat_sys_upload);
|
||||
builder.setWhen(System.currentTimeMillis());
|
||||
builder.setContentTitle(LocaleController.getString("AppName", R.string.AppName));
|
||||
builder.setTicker(LocaleController.getString("SendingVideo", R.string.SendingVideo));
|
||||
builder.setContentText(LocaleController.getString("SendingVideo", R.string.SendingVideo));
|
||||
}
|
||||
currentProgress = 0;
|
||||
builder.setProgress(100, currentProgress, currentProgress == 0);
|
||||
startForeground(4, builder.build());
|
||||
NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build());
|
||||
return Service.START_NOT_STICKY;
|
||||
}
|
||||
}
|
||||
@@ -28,12 +28,13 @@ import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.support.v4.app.RemoteInput;
|
||||
import android.util.Log;
|
||||
|
||||
public class WearReplyReceiver extends BroadcastReceiver {
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
ApplicationLoader.postInitApplication();
|
||||
|
||||
Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
|
||||
if (remoteInput == null) {
|
||||
return;
|
||||
@@ -47,7 +48,7 @@ public class WearReplyReceiver extends BroadcastReceiver {
|
||||
if (dialog_id == 0 || max_id == 0) {
|
||||
return;
|
||||
}
|
||||
SendMessagesHelper.getInstance().sendMessageText(text.toString(), dialog_id, null, null);
|
||||
SendMessagesHelper.getInstance().sendMessageText(text.toString(), dialog_id, null);
|
||||
MrMailbox.markseenChat((int)dialog_id);
|
||||
NotificationsController.getInstance().removeSeenMessages();
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
|
||||
import com.b44t.messenger.FileLog;
|
||||
import com.b44t.ui.LaunchActivity;
|
||||
|
||||
public class Browser {
|
||||
@@ -55,7 +54,7 @@ public class Browser {
|
||||
intent.putExtra(android.provider.Browser.EXTRA_APPLICATION_ID, context.getPackageName());
|
||||
context.startActivity(intent);
|
||||
} catch (Exception e) {
|
||||
FileLog.e("messenger", e);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.AttributeSet;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
/**
|
||||
* A {@link FrameLayout} that resizes itself to match a specified aspect ratio.
|
||||
*/
|
||||
public final class AspectRatioFrameLayout extends FrameLayout {
|
||||
|
||||
/**
|
||||
* The {@link FrameLayout} will not resize itself if the fractional difference between its natural
|
||||
* aspect ratio and the requested aspect ratio falls below this threshold.
|
||||
* <p>
|
||||
* This tolerance allows the view to occupy the whole of the screen when the requested aspect
|
||||
* ratio is very close, but not exactly equal to, the aspect ratio of the screen. This may reduce
|
||||
* the number of view layers that need to be composited by the underlying system, which can help
|
||||
* to reduce power consumption.
|
||||
*/
|
||||
private static final float MAX_ASPECT_RATIO_DEFORMATION_FRACTION = 0.01f;
|
||||
|
||||
private float videoAspectRatio;
|
||||
|
||||
public AspectRatioFrameLayout(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public AspectRatioFrameLayout(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the aspect ratio that this view should satisfy.
|
||||
*
|
||||
* @param widthHeightRatio The width to height ratio.
|
||||
*/
|
||||
public void setAspectRatio(float widthHeightRatio) {
|
||||
if (this.videoAspectRatio != widthHeightRatio) {
|
||||
this.videoAspectRatio = widthHeightRatio;
|
||||
requestLayout();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
|
||||
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
|
||||
if (videoAspectRatio == 0) {
|
||||
// Aspect ratio not set.
|
||||
return;
|
||||
}
|
||||
|
||||
int width = getMeasuredWidth();
|
||||
int height = getMeasuredHeight();
|
||||
float viewAspectRatio = (float) width / height;
|
||||
float aspectDeformation = videoAspectRatio / viewAspectRatio - 1;
|
||||
if (Math.abs(aspectDeformation) <= MAX_ASPECT_RATIO_DEFORMATION_FRACTION) {
|
||||
// We're within the allowed tolerance.
|
||||
return;
|
||||
}
|
||||
|
||||
if (aspectDeformation > 0) {
|
||||
height = (int) (width / videoAspectRatio);
|
||||
} else {
|
||||
width = (int) (height * videoAspectRatio);
|
||||
}
|
||||
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
|
||||
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
|
||||
}
|
||||
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Thrown when a live playback falls behind the available media window.
|
||||
*/
|
||||
public final class BehindLiveWindowException extends IOException {
|
||||
|
||||
public BehindLiveWindowException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public BehindLiveWindowException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.util.Util;
|
||||
|
||||
import android.media.AudioFormat;
|
||||
import android.media.MediaCodec;
|
||||
import android.media.MediaExtractor;
|
||||
|
||||
/**
|
||||
* Defines constants that are generally useful throughout the library.
|
||||
*/
|
||||
public final class C {
|
||||
|
||||
/**
|
||||
* Represents an unknown microsecond time or duration.
|
||||
*/
|
||||
public static final long UNKNOWN_TIME_US = -1L;
|
||||
|
||||
/**
|
||||
* Represents a microsecond duration whose exact value is unknown, but which should match the
|
||||
* longest of some other known durations.
|
||||
*/
|
||||
public static final long MATCH_LONGEST_US = -2L;
|
||||
|
||||
/**
|
||||
* The number of microseconds in one second.
|
||||
*/
|
||||
public static final long MICROS_PER_SECOND = 1000000L;
|
||||
|
||||
/**
|
||||
* Represents an unbounded length of data.
|
||||
*/
|
||||
public static final int LENGTH_UNBOUNDED = -1;
|
||||
|
||||
/**
|
||||
* The name of the UTF-8 charset.
|
||||
*/
|
||||
public static final String UTF8_NAME = "UTF-8";
|
||||
|
||||
/**
|
||||
* @see MediaCodec#CRYPTO_MODE_AES_CTR
|
||||
*/
|
||||
@SuppressWarnings("InlinedApi")
|
||||
public static final int CRYPTO_MODE_AES_CTR = MediaCodec.CRYPTO_MODE_AES_CTR;
|
||||
|
||||
/**
|
||||
* @see AudioFormat#ENCODING_INVALID
|
||||
*/
|
||||
public static final int ENCODING_INVALID = AudioFormat.ENCODING_INVALID;
|
||||
|
||||
/**
|
||||
* @see AudioFormat#ENCODING_PCM_8BIT
|
||||
*/
|
||||
public static final int ENCODING_PCM_8BIT = AudioFormat.ENCODING_PCM_8BIT;
|
||||
|
||||
/**
|
||||
* @see AudioFormat#ENCODING_PCM_16BIT
|
||||
*/
|
||||
public static final int ENCODING_PCM_16BIT = AudioFormat.ENCODING_PCM_16BIT;
|
||||
|
||||
/**
|
||||
* PCM encoding with 24 bits per sample.
|
||||
*/
|
||||
public static final int ENCODING_PCM_24BIT = 0x80000000;
|
||||
|
||||
/**
|
||||
* PCM encoding with 32 bits per sample.
|
||||
*/
|
||||
public static final int ENCODING_PCM_32BIT = 0x40000000;
|
||||
|
||||
/**
|
||||
* @see AudioFormat#ENCODING_AC3
|
||||
*/
|
||||
@SuppressWarnings("InlinedApi")
|
||||
public static final int ENCODING_AC3 = AudioFormat.ENCODING_AC3;
|
||||
|
||||
/**
|
||||
* @see AudioFormat#ENCODING_E_AC3
|
||||
*/
|
||||
@SuppressWarnings("InlinedApi")
|
||||
public static final int ENCODING_E_AC3 = AudioFormat.ENCODING_E_AC3;
|
||||
|
||||
/**
|
||||
* @see AudioFormat#ENCODING_DTS
|
||||
*/
|
||||
@SuppressWarnings("InlinedApi")
|
||||
public static final int ENCODING_DTS = AudioFormat.ENCODING_DTS;
|
||||
|
||||
/**
|
||||
* @see AudioFormat#ENCODING_DTS_HD
|
||||
*/
|
||||
@SuppressWarnings("InlinedApi")
|
||||
public static final int ENCODING_DTS_HD = AudioFormat.ENCODING_DTS_HD;
|
||||
|
||||
/**
|
||||
* @see AudioFormat#CHANNEL_OUT_7POINT1_SURROUND
|
||||
*/
|
||||
@SuppressWarnings({"InlinedApi", "deprecation"})
|
||||
public static final int CHANNEL_OUT_7POINT1_SURROUND = Util.SDK_INT < 23
|
||||
? AudioFormat.CHANNEL_OUT_7POINT1 : AudioFormat.CHANNEL_OUT_7POINT1_SURROUND;
|
||||
|
||||
/**
|
||||
* @see MediaExtractor#SAMPLE_FLAG_SYNC
|
||||
*/
|
||||
@SuppressWarnings("InlinedApi")
|
||||
public static final int SAMPLE_FLAG_SYNC = MediaExtractor.SAMPLE_FLAG_SYNC;
|
||||
|
||||
/**
|
||||
* @see MediaExtractor#SAMPLE_FLAG_ENCRYPTED
|
||||
*/
|
||||
@SuppressWarnings("InlinedApi")
|
||||
public static final int SAMPLE_FLAG_ENCRYPTED = MediaExtractor.SAMPLE_FLAG_ENCRYPTED;
|
||||
|
||||
/**
|
||||
* Indicates that a sample should be decoded but not rendered.
|
||||
*/
|
||||
public static final int SAMPLE_FLAG_DECODE_ONLY = 0x8000000;
|
||||
|
||||
/**
|
||||
* A return value for methods where the end of an input was encountered.
|
||||
*/
|
||||
public static final int RESULT_END_OF_INPUT = -1;
|
||||
|
||||
/**
|
||||
* A return value for methods where the length of parsed data exceeds the maximum length allowed.
|
||||
*/
|
||||
public static final int RESULT_MAX_LENGTH_EXCEEDED = -2;
|
||||
|
||||
private C() {}
|
||||
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
/**
|
||||
* Maintains codec event counts, for debugging purposes only.
|
||||
* <p>
|
||||
* Counters should be written from the playback thread only. Counters may be read from any thread.
|
||||
* To ensure that the counter values are correctly reflected between threads, users of this class
|
||||
* should invoke {@link #ensureUpdated()} prior to reading and after writing.
|
||||
*/
|
||||
public final class CodecCounters {
|
||||
|
||||
public int codecInitCount;
|
||||
public int codecReleaseCount;
|
||||
public int inputBufferCount;
|
||||
public int outputFormatChangedCount;
|
||||
public int outputBuffersChangedCount;
|
||||
public int renderedOutputBufferCount;
|
||||
public int skippedOutputBufferCount;
|
||||
public int droppedOutputBufferCount;
|
||||
public int maxConsecutiveDroppedOutputBufferCount;
|
||||
|
||||
/**
|
||||
* Should be invoked from the playback thread after the counters have been updated. Should also
|
||||
* be invoked from any other thread that wishes to read the counters, before reading. These calls
|
||||
* ensure that counter updates are made visible to the reading threads.
|
||||
*/
|
||||
public synchronized void ensureUpdated() {
|
||||
// Do nothing. The use of synchronized ensures a memory barrier should another thread also
|
||||
// call this method.
|
||||
}
|
||||
|
||||
public String getDebugString() {
|
||||
ensureUpdated();
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("cic:").append(codecInitCount);
|
||||
builder.append(" crc:").append(codecReleaseCount);
|
||||
builder.append(" ibc:").append(inputBufferCount);
|
||||
builder.append(" ofc:").append(outputFormatChangedCount);
|
||||
builder.append(" obc:").append(outputBuffersChangedCount);
|
||||
builder.append(" ren:").append(renderedOutputBufferCount);
|
||||
builder.append(" sob:").append(skippedOutputBufferCount);
|
||||
builder.append(" dob:").append(droppedOutputBufferCount);
|
||||
builder.append(" mcdob:").append(maxConsecutiveDroppedOutputBufferCount);
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.util.Util;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.media.MediaExtractor;
|
||||
|
||||
/**
|
||||
* Compatibility wrapper around {@link android.media.MediaCodec.CryptoInfo}.
|
||||
*/
|
||||
public final class CryptoInfo {
|
||||
|
||||
/**
|
||||
* @see android.media.MediaCodec.CryptoInfo#iv
|
||||
*/
|
||||
public byte[] iv;
|
||||
/**
|
||||
* @see android.media.MediaCodec.CryptoInfo#key
|
||||
*/
|
||||
public byte[] key;
|
||||
/**
|
||||
* @see android.media.MediaCodec.CryptoInfo#mode
|
||||
*/
|
||||
public int mode;
|
||||
/**
|
||||
* @see android.media.MediaCodec.CryptoInfo#numBytesOfClearData
|
||||
*/
|
||||
public int[] numBytesOfClearData;
|
||||
/**
|
||||
* @see android.media.MediaCodec.CryptoInfo#numBytesOfEncryptedData
|
||||
*/
|
||||
public int[] numBytesOfEncryptedData;
|
||||
/**
|
||||
* @see android.media.MediaCodec.CryptoInfo#numSubSamples
|
||||
*/
|
||||
public int numSubSamples;
|
||||
|
||||
private final android.media.MediaCodec.CryptoInfo frameworkCryptoInfo;
|
||||
|
||||
public CryptoInfo() {
|
||||
frameworkCryptoInfo = Util.SDK_INT >= 16 ? newFrameworkCryptoInfoV16() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see android.media.MediaCodec.CryptoInfo#set(int, int[], int[], byte[], byte[], int)
|
||||
*/
|
||||
public void set(int numSubSamples, int[] numBytesOfClearData, int[] numBytesOfEncryptedData,
|
||||
byte[] key, byte[] iv, int mode) {
|
||||
this.numSubSamples = numSubSamples;
|
||||
this.numBytesOfClearData = numBytesOfClearData;
|
||||
this.numBytesOfEncryptedData = numBytesOfEncryptedData;
|
||||
this.key = key;
|
||||
this.iv = iv;
|
||||
this.mode = mode;
|
||||
if (Util.SDK_INT >= 16) {
|
||||
updateFrameworkCryptoInfoV16();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Equivalent to {@link MediaExtractor#getSampleCryptoInfo(android.media.MediaCodec.CryptoInfo)}.
|
||||
*
|
||||
* @param extractor The extractor from which to retrieve the crypto information.
|
||||
*/
|
||||
@TargetApi(16)
|
||||
public void setFromExtractorV16(MediaExtractor extractor) {
|
||||
extractor.getSampleCryptoInfo(frameworkCryptoInfo);
|
||||
numSubSamples = frameworkCryptoInfo.numSubSamples;
|
||||
numBytesOfClearData = frameworkCryptoInfo.numBytesOfClearData;
|
||||
numBytesOfEncryptedData = frameworkCryptoInfo.numBytesOfEncryptedData;
|
||||
key = frameworkCryptoInfo.key;
|
||||
iv = frameworkCryptoInfo.iv;
|
||||
mode = frameworkCryptoInfo.mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an equivalent {@link android.media.MediaCodec.CryptoInfo} instance.
|
||||
* <p>
|
||||
* Successive calls to this method on a single {@link CryptoInfo} will return the same instance.
|
||||
* Changes to the {@link CryptoInfo} will be reflected in the returned object. The return object
|
||||
* should not be modified directly.
|
||||
*
|
||||
* @return The equivalent {@link android.media.MediaCodec.CryptoInfo} instance.
|
||||
*/
|
||||
@TargetApi(16)
|
||||
public android.media.MediaCodec.CryptoInfo getFrameworkCryptoInfoV16() {
|
||||
return frameworkCryptoInfo;
|
||||
}
|
||||
|
||||
@TargetApi(16)
|
||||
private android.media.MediaCodec.CryptoInfo newFrameworkCryptoInfoV16() {
|
||||
return new android.media.MediaCodec.CryptoInfo();
|
||||
}
|
||||
|
||||
@TargetApi(16)
|
||||
private void updateFrameworkCryptoInfoV16() {
|
||||
frameworkCryptoInfo.set(numSubSamples, numBytesOfClearData, numBytesOfEncryptedData, key, iv,
|
||||
mode);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.util.Util;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.media.MediaCodecInfo.CodecCapabilities;
|
||||
|
||||
/**
|
||||
* Contains information about a media decoder.
|
||||
*/
|
||||
@TargetApi(16)
|
||||
public final class DecoderInfo {
|
||||
|
||||
/**
|
||||
* The name of the decoder.
|
||||
* <p>
|
||||
* May be passed to {@link android.media.MediaCodec#createByCodecName(String)} to create an
|
||||
* instance of the decoder.
|
||||
*/
|
||||
public final String name;
|
||||
|
||||
/**
|
||||
* {@link CodecCapabilities} for this decoder.
|
||||
*/
|
||||
public final CodecCapabilities capabilities;
|
||||
|
||||
/**
|
||||
* Whether the decoder supports seamless resolution switches.
|
||||
*
|
||||
* @see android.media.MediaCodecInfo.CodecCapabilities#isFeatureSupported(String)
|
||||
* @see android.media.MediaCodecInfo.CodecCapabilities#FEATURE_AdaptivePlayback
|
||||
*/
|
||||
public final boolean adaptive;
|
||||
|
||||
/**
|
||||
* @param name The name of the decoder.
|
||||
* @param capabilities {@link CodecCapabilities} of the decoder.
|
||||
*/
|
||||
/* package */ DecoderInfo(String name, CodecCapabilities capabilities) {
|
||||
this.name = name;
|
||||
this.capabilities = capabilities;
|
||||
this.adaptive = isAdaptive(capabilities);
|
||||
}
|
||||
|
||||
private static boolean isAdaptive(CodecCapabilities capabilities) {
|
||||
return capabilities != null && Util.SDK_INT >= 19 && isAdaptiveV19(capabilities);
|
||||
}
|
||||
|
||||
@TargetApi(19)
|
||||
private static boolean isAdaptiveV19(CodecCapabilities capabilities) {
|
||||
return capabilities.isFeatureSupported(CodecCapabilities.FEATURE_AdaptivePlayback);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.upstream.Allocator;
|
||||
import com.b44t.messenger.exoplayer.upstream.NetworkLock;
|
||||
|
||||
import android.os.Handler;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A {@link LoadControl} implementation that allows loads to continue in a sequence that prevents
|
||||
* any loader from getting too far ahead or behind any of the other loaders.
|
||||
* <p>
|
||||
* Loads are scheduled so as to fill the available buffer space as rapidly as possible. Once the
|
||||
* duration of buffered media and the buffer utilization both exceed respective thresholds, the
|
||||
* control switches to a draining state during which no loads are permitted to start. During
|
||||
* draining periods, resources such as the device radio have an opportunity to switch into low
|
||||
* power modes. The control reverts back to the loading state when either the duration of buffered
|
||||
* media or the buffer utilization fall below respective thresholds.
|
||||
* <p>
|
||||
* This implementation of {@link LoadControl} integrates with {@link NetworkLock}, by registering
|
||||
* itself as a task with priority {@link NetworkLock#STREAMING_PRIORITY} during loading periods,
|
||||
* and unregistering itself during draining periods.
|
||||
*/
|
||||
public final class DefaultLoadControl implements LoadControl {
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be notified of {@link DefaultLoadControl} events.
|
||||
*/
|
||||
public interface EventListener {
|
||||
|
||||
/**
|
||||
* Invoked when the control transitions from a loading to a draining state, or vice versa.
|
||||
*
|
||||
* @param loading Whether the control is now in a loading state.
|
||||
*/
|
||||
void onLoadingChanged(boolean loading);
|
||||
|
||||
}
|
||||
|
||||
public static final int DEFAULT_LOW_WATERMARK_MS = 15000;
|
||||
public static final int DEFAULT_HIGH_WATERMARK_MS = 30000;
|
||||
public static final float DEFAULT_LOW_BUFFER_LOAD = 0.2f;
|
||||
public static final float DEFAULT_HIGH_BUFFER_LOAD = 0.8f;
|
||||
|
||||
private static final int ABOVE_HIGH_WATERMARK = 0;
|
||||
private static final int BETWEEN_WATERMARKS = 1;
|
||||
private static final int BELOW_LOW_WATERMARK = 2;
|
||||
|
||||
private final Allocator allocator;
|
||||
private final List<Object> loaders;
|
||||
private final HashMap<Object, LoaderState> loaderStates;
|
||||
private final Handler eventHandler;
|
||||
private final EventListener eventListener;
|
||||
|
||||
private final long lowWatermarkUs;
|
||||
private final long highWatermarkUs;
|
||||
private final float lowBufferLoad;
|
||||
private final float highBufferLoad;
|
||||
|
||||
private int targetBufferSize;
|
||||
private long maxLoadStartPositionUs;
|
||||
private int bufferState;
|
||||
private boolean fillingBuffers;
|
||||
private boolean streamingPrioritySet;
|
||||
|
||||
/**
|
||||
* Constructs a new instance, using the {@code DEFAULT_*} constants defined in this class.
|
||||
*
|
||||
* @param allocator The {@link Allocator} used by the loader.
|
||||
*/
|
||||
public DefaultLoadControl(Allocator allocator) {
|
||||
this(allocator, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new instance, using the {@code DEFAULT_*} constants defined in this class.
|
||||
*
|
||||
* @param allocator The {@link Allocator} used by the loader.
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
*/
|
||||
public DefaultLoadControl(Allocator allocator, Handler eventHandler,
|
||||
EventListener eventListener) {
|
||||
this(allocator, eventHandler, eventListener, DEFAULT_LOW_WATERMARK_MS,
|
||||
DEFAULT_HIGH_WATERMARK_MS, DEFAULT_LOW_BUFFER_LOAD, DEFAULT_HIGH_BUFFER_LOAD);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new instance.
|
||||
*
|
||||
* @param allocator The {@link Allocator} used by the loader.
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
* @param lowWatermarkMs The minimum duration of media that can be buffered for the control to
|
||||
* be in the draining state. If less media is buffered, then the control will transition to
|
||||
* the filling state.
|
||||
* @param highWatermarkMs The minimum duration of media that can be buffered for the control to
|
||||
* transition from filling to draining.
|
||||
* @param lowBufferLoad The minimum fraction of the buffer that must be utilized for the control
|
||||
* to be in the draining state. If the utilization is lower, then the control will transition
|
||||
* to the filling state.
|
||||
* @param highBufferLoad The minimum fraction of the buffer that must be utilized for the control
|
||||
* to transition from the loading state to the draining state.
|
||||
*/
|
||||
public DefaultLoadControl(Allocator allocator, Handler eventHandler, EventListener eventListener,
|
||||
int lowWatermarkMs, int highWatermarkMs, float lowBufferLoad, float highBufferLoad) {
|
||||
this.allocator = allocator;
|
||||
this.eventHandler = eventHandler;
|
||||
this.eventListener = eventListener;
|
||||
this.loaders = new ArrayList<>();
|
||||
this.loaderStates = new HashMap<>();
|
||||
this.lowWatermarkUs = lowWatermarkMs * 1000L;
|
||||
this.highWatermarkUs = highWatermarkMs * 1000L;
|
||||
this.lowBufferLoad = lowBufferLoad;
|
||||
this.highBufferLoad = highBufferLoad;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void register(Object loader, int bufferSizeContribution) {
|
||||
loaders.add(loader);
|
||||
loaderStates.put(loader, new LoaderState(bufferSizeContribution));
|
||||
targetBufferSize += bufferSizeContribution;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregister(Object loader) {
|
||||
loaders.remove(loader);
|
||||
LoaderState state = loaderStates.remove(loader);
|
||||
targetBufferSize -= state.bufferSizeContribution;
|
||||
updateControlState();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void trimAllocator() {
|
||||
allocator.trim(targetBufferSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Allocator getAllocator() {
|
||||
return allocator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean update(Object loader, long playbackPositionUs, long nextLoadPositionUs,
|
||||
boolean loading) {
|
||||
// Update the loader state.
|
||||
int loaderBufferState = getLoaderBufferState(playbackPositionUs, nextLoadPositionUs);
|
||||
LoaderState loaderState = loaderStates.get(loader);
|
||||
boolean loaderStateChanged = loaderState.bufferState != loaderBufferState
|
||||
|| loaderState.nextLoadPositionUs != nextLoadPositionUs || loaderState.loading != loading;
|
||||
if (loaderStateChanged) {
|
||||
loaderState.bufferState = loaderBufferState;
|
||||
loaderState.nextLoadPositionUs = nextLoadPositionUs;
|
||||
loaderState.loading = loading;
|
||||
}
|
||||
|
||||
// Update the buffer state.
|
||||
int currentBufferSize = allocator.getTotalBytesAllocated();
|
||||
int bufferState = getBufferState(currentBufferSize);
|
||||
boolean bufferStateChanged = this.bufferState != bufferState;
|
||||
if (bufferStateChanged) {
|
||||
this.bufferState = bufferState;
|
||||
}
|
||||
|
||||
// If either of the individual states have changed, update the shared control state.
|
||||
if (loaderStateChanged || bufferStateChanged) {
|
||||
updateControlState();
|
||||
}
|
||||
|
||||
return currentBufferSize < targetBufferSize && nextLoadPositionUs != -1
|
||||
&& nextLoadPositionUs <= maxLoadStartPositionUs;
|
||||
}
|
||||
|
||||
private int getLoaderBufferState(long playbackPositionUs, long nextLoadPositionUs) {
|
||||
if (nextLoadPositionUs == -1) {
|
||||
return ABOVE_HIGH_WATERMARK;
|
||||
} else {
|
||||
long timeUntilNextLoadPosition = nextLoadPositionUs - playbackPositionUs;
|
||||
return timeUntilNextLoadPosition > highWatermarkUs ? ABOVE_HIGH_WATERMARK :
|
||||
timeUntilNextLoadPosition < lowWatermarkUs ? BELOW_LOW_WATERMARK :
|
||||
BETWEEN_WATERMARKS;
|
||||
}
|
||||
}
|
||||
|
||||
private int getBufferState(int currentBufferSize) {
|
||||
float bufferLoad = (float) currentBufferSize / targetBufferSize;
|
||||
return bufferLoad > highBufferLoad ? ABOVE_HIGH_WATERMARK
|
||||
: bufferLoad < lowBufferLoad ? BELOW_LOW_WATERMARK
|
||||
: BETWEEN_WATERMARKS;
|
||||
}
|
||||
|
||||
private void updateControlState() {
|
||||
boolean loading = false;
|
||||
boolean haveNextLoadPosition = false;
|
||||
int highestState = bufferState;
|
||||
for (int i = 0; i < loaders.size(); i++) {
|
||||
LoaderState loaderState = loaderStates.get(loaders.get(i));
|
||||
loading |= loaderState.loading;
|
||||
haveNextLoadPosition |= loaderState.nextLoadPositionUs != -1;
|
||||
highestState = Math.max(highestState, loaderState.bufferState);
|
||||
}
|
||||
|
||||
fillingBuffers = !loaders.isEmpty() && (loading || haveNextLoadPosition)
|
||||
&& (highestState == BELOW_LOW_WATERMARK
|
||||
|| (highestState == BETWEEN_WATERMARKS && fillingBuffers));
|
||||
if (fillingBuffers && !streamingPrioritySet) {
|
||||
NetworkLock.instance.add(NetworkLock.STREAMING_PRIORITY);
|
||||
streamingPrioritySet = true;
|
||||
notifyLoadingChanged(true);
|
||||
} else if (!fillingBuffers && streamingPrioritySet && !loading) {
|
||||
NetworkLock.instance.remove(NetworkLock.STREAMING_PRIORITY);
|
||||
streamingPrioritySet = false;
|
||||
notifyLoadingChanged(false);
|
||||
}
|
||||
|
||||
maxLoadStartPositionUs = -1;
|
||||
if (fillingBuffers) {
|
||||
for (int i = 0; i < loaders.size(); i++) {
|
||||
Object loader = loaders.get(i);
|
||||
LoaderState loaderState = loaderStates.get(loader);
|
||||
long loaderTime = loaderState.nextLoadPositionUs;
|
||||
if (loaderTime != -1
|
||||
&& (maxLoadStartPositionUs == -1 || loaderTime < maxLoadStartPositionUs)) {
|
||||
maxLoadStartPositionUs = loaderTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyLoadingChanged(final boolean loading) {
|
||||
if (eventHandler != null && eventListener != null) {
|
||||
eventHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
eventListener.onLoadingChanged(loading);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static class LoaderState {
|
||||
|
||||
public final int bufferSizeContribution;
|
||||
|
||||
public int bufferState;
|
||||
public boolean loading;
|
||||
public long nextLoadPositionUs;
|
||||
|
||||
public LoaderState(int bufferSizeContribution) {
|
||||
this.bufferSizeContribution = bufferSizeContribution;
|
||||
bufferState = ABOVE_HIGH_WATERMARK;
|
||||
loading = false;
|
||||
nextLoadPositionUs = -1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
/**
|
||||
* A {@link TrackRenderer} that does nothing.
|
||||
* <p>
|
||||
* This renderer returns 0 from {@link #getTrackCount()} in order to request that it should be
|
||||
* ignored. {@link IllegalStateException} is thrown from all other methods documented to indicate
|
||||
* that they should not be invoked unless the renderer is prepared.
|
||||
*/
|
||||
public final class DummyTrackRenderer extends TrackRenderer {
|
||||
|
||||
@Override
|
||||
protected boolean doPrepare(long positionUs) throws ExoPlaybackException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getTrackCount() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MediaFormat getFormat(int track) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isEnded() {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isReady() {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void seekTo(long positionUs) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doSomeWork(long positionUs, long elapsedRealtimeUs) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void maybeThrowError() {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected long getDurationUs() {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected long getBufferedPositionUs() {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
/**
|
||||
* Thrown when a non-recoverable playback failure occurs.
|
||||
* <p>
|
||||
* Where possible, the cause returned by {@link #getCause()} will indicate the reason for failure.
|
||||
*/
|
||||
public final class ExoPlaybackException extends Exception {
|
||||
|
||||
/**
|
||||
* True if the cause (i.e. the {@link Throwable} returned by {@link #getCause()}) was only caught
|
||||
* by a fail-safe at the top level of the player. False otherwise.
|
||||
*/
|
||||
public final boolean caughtAtTopLevel;
|
||||
|
||||
public ExoPlaybackException(String message) {
|
||||
super(message);
|
||||
caughtAtTopLevel = false;
|
||||
}
|
||||
|
||||
public ExoPlaybackException(Throwable cause) {
|
||||
super(cause);
|
||||
caughtAtTopLevel = false;
|
||||
}
|
||||
|
||||
public ExoPlaybackException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
caughtAtTopLevel = false;
|
||||
}
|
||||
|
||||
/* package */ ExoPlaybackException(Throwable cause, boolean caughtAtTopLevel) {
|
||||
super(cause);
|
||||
this.caughtAtTopLevel = caughtAtTopLevel;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,415 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import android.os.Looper;
|
||||
|
||||
/**
|
||||
* An extensible media player exposing traditional high-level media player functionality, such as
|
||||
* the ability to prepare, play, pause and seek.
|
||||
*
|
||||
* <p>Topics covered here are:
|
||||
* <ol>
|
||||
* <li><a href="#Assumptions">Assumptions and player composition</a>
|
||||
* <li><a href="#Threading">Threading model</a>
|
||||
* <li><a href="#State">Player state</a>
|
||||
* </ol>
|
||||
*
|
||||
* <a name="Assumptions"></a>
|
||||
* <h3>Assumptions and player construction</h3>
|
||||
*
|
||||
* <p>The implementation is designed to make no assumptions about (and hence impose no restrictions
|
||||
* on) the type of the media being played, how and where it is stored, or how it is rendered.
|
||||
* Rather than implementing the loading and rendering of media directly, {@link ExoPlayer} instead
|
||||
* delegates this work to one or more {@link TrackRenderer}s, which are injected when the player
|
||||
* is prepared. Hence {@link ExoPlayer} is capable of loading and playing any media for which a
|
||||
* {@link TrackRenderer} implementation can be provided.
|
||||
*
|
||||
* <p>{@link MediaCodecAudioTrackRenderer} and {@link MediaCodecVideoTrackRenderer} can be used for
|
||||
* the common cases of rendering audio and video. These components in turn require an
|
||||
* <i>upstream</i> {@link SampleSource} to be injected through their constructors, where upstream
|
||||
* is defined to denote a component that is closer to the source of the media. This pattern of
|
||||
* upstream dependency injection is actively encouraged, since it means that the functionality of
|
||||
* the player is built up through the composition of components that can easily be exchanged for
|
||||
* alternate implementations. For example a {@link SampleSource} implementation may require a
|
||||
* further upstream data loading component to be injected through its constructor, with different
|
||||
* implementations enabling the loading of data from various sources.
|
||||
*
|
||||
* <a name="Threading"></a>
|
||||
* <h3>Threading model</h3>
|
||||
*
|
||||
* <p>The figure below shows the {@link ExoPlayer} threading model.</p>
|
||||
* <p align="center"><img src="../../../../../images/exoplayer_threading_model.png"
|
||||
* alt="MediaPlayer state diagram"
|
||||
* border="0"/></p>
|
||||
*
|
||||
* <ul>
|
||||
* <li>It is recommended that instances are created and accessed from a single application thread.
|
||||
* An application's main thread is ideal. Accessing an instance from multiple threads is
|
||||
* discouraged, however if an application does wish to do this then it may do so provided that it
|
||||
* ensures accesses are synchronized.
|
||||
* </li>
|
||||
* <li>Registered {@link Listener}s are invoked on the thread that created the {@link ExoPlayer}
|
||||
* instance.</li>
|
||||
* <li>An internal playback thread is responsible for managing playback and invoking the
|
||||
* {@link TrackRenderer}s in order to load and play the media.</li>
|
||||
* <li>{@link TrackRenderer} implementations (or any upstream components that they depend on) may
|
||||
* use additional background threads (e.g. to load data). These are implementation specific.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <a name="State"></a>
|
||||
* <h3>Player state</h3>
|
||||
*
|
||||
* <p>The components of an {@link ExoPlayer}'s state can be divided into two distinct groups. State
|
||||
* accessed by {@link #getSelectedTrack(int)} and {@link #getPlayWhenReady()} is only ever
|
||||
* changed by invoking the player's methods, and are never changed as a result of operations that
|
||||
* have been performed asynchronously by the playback thread. In contrast, the playback state
|
||||
* accessed by {@link #getPlaybackState()} is only ever changed as a result of operations
|
||||
* completing on the playback thread, as illustrated below.</p>
|
||||
* <p align="center"><img src="../../../../../images/exoplayer_state.png"
|
||||
* alt="ExoPlayer state"
|
||||
* border="0"/></p>
|
||||
*
|
||||
* <p>The possible playback state transitions are shown below. Transitions can be triggered either
|
||||
* by changes in the state of the {@link TrackRenderer}s being used, or as a result of
|
||||
* {@link #prepare(TrackRenderer[])}, {@link #stop()} or {@link #release()} being invoked.</p>
|
||||
* <p align="center"><img src="../../../../../images/exoplayer_playbackstate.png"
|
||||
* alt="ExoPlayer playback state transitions"
|
||||
* border="0"/></p>
|
||||
*/
|
||||
public interface ExoPlayer {
|
||||
|
||||
/**
|
||||
* A factory for instantiating ExoPlayer instances.
|
||||
*/
|
||||
public static final class Factory {
|
||||
|
||||
/**
|
||||
* The default minimum duration of data that must be buffered for playback to start or resume
|
||||
* following a user action such as a seek.
|
||||
*/
|
||||
public static final int DEFAULT_MIN_BUFFER_MS = 2500;
|
||||
|
||||
/**
|
||||
* The default minimum duration of data that must be buffered for playback to resume
|
||||
* after a player invoked rebuffer (i.e. a rebuffer that occurs due to buffer depletion, and
|
||||
* not due to a user action such as starting playback or seeking).
|
||||
*/
|
||||
public static final int DEFAULT_MIN_REBUFFER_MS = 5000;
|
||||
|
||||
private Factory() {}
|
||||
|
||||
/**
|
||||
* Obtains an {@link ExoPlayer} instance.
|
||||
* <p>
|
||||
* Must be invoked from a thread that has an associated {@link Looper}.
|
||||
*
|
||||
* @param rendererCount The number of {@link TrackRenderer}s that will be passed to
|
||||
* {@link #prepare(TrackRenderer[])}.
|
||||
* @param minBufferMs A minimum duration of data that must be buffered for playback to start
|
||||
* or resume following a user action such as a seek.
|
||||
* @param minRebufferMs A minimum duration of data that must be buffered for playback to resume
|
||||
* after a player invoked rebuffer (i.e. a rebuffer that occurs due to buffer depletion, and
|
||||
* not due to a user action such as starting playback or seeking).
|
||||
*/
|
||||
public static ExoPlayer newInstance(int rendererCount, int minBufferMs, int minRebufferMs) {
|
||||
return new ExoPlayerImpl(rendererCount, minBufferMs, minRebufferMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains an {@link ExoPlayer} instance.
|
||||
* <p>
|
||||
* Must be invoked from a thread that has an associated {@link Looper}.
|
||||
*
|
||||
* @param rendererCount The number of {@link TrackRenderer}s that will be passed to
|
||||
* {@link #prepare(TrackRenderer[])}.
|
||||
*/
|
||||
public static ExoPlayer newInstance(int rendererCount) {
|
||||
return new ExoPlayerImpl(rendererCount, DEFAULT_MIN_BUFFER_MS, DEFAULT_MIN_REBUFFER_MS);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be notified of changes in player state.
|
||||
*/
|
||||
public interface Listener {
|
||||
/**
|
||||
* Invoked when the value returned from either {@link ExoPlayer#getPlayWhenReady()} or
|
||||
* {@link ExoPlayer#getPlaybackState()} changes.
|
||||
*
|
||||
* @param playWhenReady Whether playback will proceed when ready.
|
||||
* @param playbackState One of the {@code STATE} constants defined in the {@link ExoPlayer}
|
||||
* interface.
|
||||
*/
|
||||
void onPlayerStateChanged(boolean playWhenReady, int playbackState);
|
||||
/**
|
||||
* Invoked when the current value of {@link ExoPlayer#getPlayWhenReady()} has been reflected
|
||||
* by the internal playback thread.
|
||||
* <p>
|
||||
* An invocation of this method will shortly follow any call to
|
||||
* {@link ExoPlayer#setPlayWhenReady(boolean)} that changes the state. If multiple calls are
|
||||
* made in rapid succession, then this method will be invoked only once, after the final state
|
||||
* has been reflected.
|
||||
*/
|
||||
void onPlayWhenReadyCommitted();
|
||||
/**
|
||||
* Invoked when an error occurs. The playback state will transition to
|
||||
* {@link ExoPlayer#STATE_IDLE} immediately after this method is invoked. The player instance
|
||||
* can still be used, and {@link ExoPlayer#release()} must still be called on the player should
|
||||
* it no longer be required.
|
||||
*
|
||||
* @param error The error.
|
||||
*/
|
||||
void onPlayerError(ExoPlaybackException error);
|
||||
}
|
||||
|
||||
/**
|
||||
* A component of an {@link ExoPlayer} that can receive messages on the playback thread.
|
||||
* <p>
|
||||
* Messages can be delivered to a component via {@link ExoPlayer#sendMessage} and
|
||||
* {@link ExoPlayer#blockingSendMessage}.
|
||||
*/
|
||||
public interface ExoPlayerComponent {
|
||||
|
||||
/**
|
||||
* Handles a message delivered to the component. Invoked on the playback thread.
|
||||
*
|
||||
* @param messageType An integer identifying the type of message.
|
||||
* @param message The message object.
|
||||
* @throws ExoPlaybackException If an error occurred whilst handling the message.
|
||||
*/
|
||||
void handleMessage(int messageType, Object message) throws ExoPlaybackException;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The player is neither prepared or being prepared.
|
||||
*/
|
||||
public static final int STATE_IDLE = 1;
|
||||
/**
|
||||
* The player is being prepared.
|
||||
*/
|
||||
public static final int STATE_PREPARING = 2;
|
||||
/**
|
||||
* The player is prepared but not able to immediately play from the current position. The cause
|
||||
* is {@link TrackRenderer} specific, but this state typically occurs when more data needs
|
||||
* to be buffered for playback to start.
|
||||
*/
|
||||
public static final int STATE_BUFFERING = 3;
|
||||
/**
|
||||
* The player is prepared and able to immediately play from the current position. The player will
|
||||
* be playing if {@link #getPlayWhenReady()} returns true, and paused otherwise.
|
||||
*/
|
||||
public static final int STATE_READY = 4;
|
||||
/**
|
||||
* The player has finished playing the media.
|
||||
*/
|
||||
public static final int STATE_ENDED = 5;
|
||||
|
||||
/**
|
||||
* A value that can be passed as the second argument to {@link #setSelectedTrack(int, int)} to
|
||||
* disable the renderer.
|
||||
*/
|
||||
public static final int TRACK_DISABLED = -1;
|
||||
/**
|
||||
* A value that can be passed as the second argument to {@link #setSelectedTrack(int, int)} to
|
||||
* select the default track.
|
||||
*/
|
||||
public static final int TRACK_DEFAULT = 0;
|
||||
|
||||
/**
|
||||
* Represents an unknown time or duration.
|
||||
*/
|
||||
public static final long UNKNOWN_TIME = -1;
|
||||
|
||||
/**
|
||||
* Gets the {@link Looper} associated with the playback thread.
|
||||
*
|
||||
* @return The {@link Looper} associated with the playback thread.
|
||||
*/
|
||||
public Looper getPlaybackLooper();
|
||||
|
||||
/**
|
||||
* Register a listener to receive events from the player. The listener's methods will be invoked
|
||||
* on the thread that was used to construct the player.
|
||||
*
|
||||
* @param listener The listener to register.
|
||||
*/
|
||||
public void addListener(Listener listener);
|
||||
|
||||
/**
|
||||
* Unregister a listener. The listener will no longer receive events from the player.
|
||||
*
|
||||
* @param listener The listener to unregister.
|
||||
*/
|
||||
public void removeListener(Listener listener);
|
||||
|
||||
/**
|
||||
* Returns the current state of the player.
|
||||
*
|
||||
* @return One of the {@code STATE} constants defined in this interface.
|
||||
*/
|
||||
public int getPlaybackState();
|
||||
|
||||
/**
|
||||
* Prepares the player for playback.
|
||||
*
|
||||
* @param renderers The {@link TrackRenderer}s to use. The number of renderers must match the
|
||||
* value that was passed to the {@link ExoPlayer.Factory#newInstance} method.
|
||||
*/
|
||||
public void prepare(TrackRenderer... renderers);
|
||||
|
||||
/**
|
||||
* Returns the number of tracks exposed by the specified renderer.
|
||||
*
|
||||
* @param rendererIndex The index of the renderer.
|
||||
* @return The number of tracks.
|
||||
*/
|
||||
public int getTrackCount(int rendererIndex);
|
||||
|
||||
/**
|
||||
* Returns the format of a track.
|
||||
*
|
||||
* @param rendererIndex The index of the renderer.
|
||||
* @param trackIndex The index of the track.
|
||||
* @return The format of the track.
|
||||
*/
|
||||
public MediaFormat getTrackFormat(int rendererIndex, int trackIndex);
|
||||
|
||||
/**
|
||||
* Selects a track for the specified renderer.
|
||||
*
|
||||
* @param rendererIndex The index of the renderer.
|
||||
* @param trackIndex The index of the track. A negative value or a value greater than or equal to
|
||||
* the renderer's track count will disable the renderer.
|
||||
*/
|
||||
public void setSelectedTrack(int rendererIndex, int trackIndex);
|
||||
|
||||
/**
|
||||
* Returns the index of the currently selected track for the specified renderer.
|
||||
*
|
||||
* @param rendererIndex The index of the renderer.
|
||||
* @return The selected track. A negative value or a value greater than or equal to the renderer's
|
||||
* track count indicates that the renderer is disabled.
|
||||
*/
|
||||
public int getSelectedTrack(int rendererIndex);
|
||||
|
||||
/**
|
||||
* Sets whether playback should proceed when {@link #getPlaybackState()} == {@link #STATE_READY}.
|
||||
* If the player is already in this state, then this method can be used to pause and resume
|
||||
* playback.
|
||||
*
|
||||
* @param playWhenReady Whether playback should proceed when ready.
|
||||
*/
|
||||
public void setPlayWhenReady(boolean playWhenReady);
|
||||
|
||||
/**
|
||||
* Whether playback will proceed when {@link #getPlaybackState()} == {@link #STATE_READY}.
|
||||
*
|
||||
* @return Whether playback will proceed when ready.
|
||||
*/
|
||||
public boolean getPlayWhenReady();
|
||||
|
||||
/**
|
||||
* Whether the current value of {@link ExoPlayer#getPlayWhenReady()} has been reflected by the
|
||||
* internal playback thread.
|
||||
*
|
||||
* @return True if the current value has been reflected. False otherwise.
|
||||
*/
|
||||
public boolean isPlayWhenReadyCommitted();
|
||||
|
||||
/**
|
||||
* Seeks to a position specified in milliseconds.
|
||||
*
|
||||
* @param positionMs The seek position.
|
||||
*/
|
||||
public void seekTo(long positionMs);
|
||||
|
||||
/**
|
||||
* Stops playback. Use {@code setPlayWhenReady(false)} rather than this method if the intention
|
||||
* is to pause playback.
|
||||
* <p>
|
||||
* Calling this method will cause the playback state to transition to
|
||||
* {@link ExoPlayer#STATE_IDLE}. The player instance can still be used, and
|
||||
* {@link ExoPlayer#release()} must still be called on the player if it's no longer required.
|
||||
* <p>
|
||||
* Calling this method does not reset the playback position. If this player instance will be used
|
||||
* to play another video from its start, then {@code seekTo(0)} should be called after stopping
|
||||
* the player and before preparing it for the next video.
|
||||
*/
|
||||
public void stop();
|
||||
|
||||
/**
|
||||
* Releases the player. This method must be called when the player is no longer required.
|
||||
* <p>
|
||||
* The player must not be used after calling this method.
|
||||
*/
|
||||
public void release();
|
||||
|
||||
/**
|
||||
* Sends a message to a specified component. The message is delivered to the component on the
|
||||
* playback thread. If the component throws a {@link ExoPlaybackException}, then it is
|
||||
* propagated out of the player as an error.
|
||||
*
|
||||
* @param target The target to which the message should be delivered.
|
||||
* @param messageType An integer that can be used to identify the type of the message.
|
||||
* @param message The message object.
|
||||
*/
|
||||
public void sendMessage(ExoPlayerComponent target, int messageType, Object message);
|
||||
|
||||
/**
|
||||
* Blocking variant of {@link #sendMessage(ExoPlayerComponent, int, Object)} that does not return
|
||||
* until after the message has been delivered.
|
||||
*
|
||||
* @param target The target to which the message should be delivered.
|
||||
* @param messageType An integer that can be used to identify the type of the message.
|
||||
* @param message The message object.
|
||||
*/
|
||||
public void blockingSendMessage(ExoPlayerComponent target, int messageType, Object message);
|
||||
|
||||
/**
|
||||
* Gets the duration of the track in milliseconds.
|
||||
*
|
||||
* @return The duration of the track in milliseconds, or {@link ExoPlayer#UNKNOWN_TIME} if the
|
||||
* duration is not known.
|
||||
*/
|
||||
public long getDuration();
|
||||
|
||||
/**
|
||||
* Gets the current playback position in milliseconds.
|
||||
*
|
||||
* @return The current playback position in milliseconds.
|
||||
*/
|
||||
public long getCurrentPosition();
|
||||
|
||||
/**
|
||||
* Gets an estimate of the absolute position in milliseconds up to which data is buffered.
|
||||
*
|
||||
* @return An estimate of the absolute position in milliseconds up to which data is buffered,
|
||||
* or {@link ExoPlayer#UNKNOWN_TIME} if no estimate is available.
|
||||
*/
|
||||
public long getBufferedPosition();
|
||||
|
||||
/**
|
||||
* Gets an estimate of the percentage into the media up to which data is buffered.
|
||||
*
|
||||
* @return An estimate of the percentage into the media up to which data is buffered. 0 if the
|
||||
* duration of the media is not known or if no estimate is available.
|
||||
*/
|
||||
public int getBufferedPercentage();
|
||||
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.Message;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
|
||||
/**
|
||||
* Concrete implementation of {@link ExoPlayer}.
|
||||
*/
|
||||
/* package */ final class ExoPlayerImpl implements ExoPlayer {
|
||||
|
||||
private static final String TAG = "ExoPlayerImpl";
|
||||
|
||||
private final Handler eventHandler;
|
||||
private final ExoPlayerImplInternal internalPlayer;
|
||||
private final CopyOnWriteArraySet<Listener> listeners;
|
||||
private final MediaFormat[][] trackFormats;
|
||||
private final int[] selectedTrackIndices;
|
||||
|
||||
private boolean playWhenReady;
|
||||
private int playbackState;
|
||||
private int pendingPlayWhenReadyAcks;
|
||||
|
||||
/**
|
||||
* Constructs an instance. Must be invoked from a thread that has an associated {@link Looper}.
|
||||
*
|
||||
* @param rendererCount The number of {@link TrackRenderer}s that will be passed to
|
||||
* {@link #prepare(TrackRenderer[])}.
|
||||
* @param minBufferMs A minimum duration of data that must be buffered for playback to start
|
||||
* or resume following a user action such as a seek.
|
||||
* @param minRebufferMs A minimum duration of data that must be buffered for playback to resume
|
||||
* after a player invoked rebuffer (i.e. a rebuffer that occurs due to buffer depletion, and
|
||||
* not due to a user action such as starting playback or seeking).
|
||||
*/
|
||||
@SuppressLint("HandlerLeak")
|
||||
public ExoPlayerImpl(int rendererCount, int minBufferMs, int minRebufferMs) {
|
||||
Log.i(TAG, "Init " + ExoPlayerLibraryInfo.VERSION);
|
||||
this.playWhenReady = false;
|
||||
this.playbackState = STATE_IDLE;
|
||||
this.listeners = new CopyOnWriteArraySet<>();
|
||||
this.trackFormats = new MediaFormat[rendererCount][];
|
||||
this.selectedTrackIndices = new int[rendererCount];
|
||||
eventHandler = new Handler() {
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
ExoPlayerImpl.this.handleEvent(msg);
|
||||
}
|
||||
};
|
||||
internalPlayer = new ExoPlayerImplInternal(eventHandler, playWhenReady, selectedTrackIndices,
|
||||
minBufferMs, minRebufferMs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Looper getPlaybackLooper() {
|
||||
return internalPlayer.getPlaybackLooper();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addListener(Listener listener) {
|
||||
listeners.add(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeListener(Listener listener) {
|
||||
listeners.remove(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPlaybackState() {
|
||||
return playbackState;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void prepare(TrackRenderer... renderers) {
|
||||
Arrays.fill(trackFormats, null);
|
||||
internalPlayer.prepare(renderers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTrackCount(int rendererIndex) {
|
||||
return trackFormats[rendererIndex] != null ? trackFormats[rendererIndex].length : 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MediaFormat getTrackFormat(int rendererIndex, int trackIndex) {
|
||||
return trackFormats[rendererIndex][trackIndex];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSelectedTrack(int rendererIndex, int trackIndex) {
|
||||
if (selectedTrackIndices[rendererIndex] != trackIndex) {
|
||||
selectedTrackIndices[rendererIndex] = trackIndex;
|
||||
internalPlayer.setRendererSelectedTrack(rendererIndex, trackIndex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSelectedTrack(int rendererIndex) {
|
||||
return selectedTrackIndices[rendererIndex];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPlayWhenReady(boolean playWhenReady) {
|
||||
if (this.playWhenReady != playWhenReady) {
|
||||
this.playWhenReady = playWhenReady;
|
||||
pendingPlayWhenReadyAcks++;
|
||||
internalPlayer.setPlayWhenReady(playWhenReady);
|
||||
for (Listener listener : listeners) {
|
||||
listener.onPlayerStateChanged(playWhenReady, playbackState);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getPlayWhenReady() {
|
||||
return playWhenReady;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPlayWhenReadyCommitted() {
|
||||
return pendingPlayWhenReadyAcks == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void seekTo(long positionMs) {
|
||||
internalPlayer.seekTo(positionMs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
internalPlayer.stop();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release() {
|
||||
internalPlayer.release();
|
||||
eventHandler.removeCallbacksAndMessages(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(ExoPlayerComponent target, int messageType, Object message) {
|
||||
internalPlayer.sendMessage(target, messageType, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void blockingSendMessage(ExoPlayerComponent target, int messageType, Object message) {
|
||||
internalPlayer.blockingSendMessage(target, messageType, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getDuration() {
|
||||
return internalPlayer.getDuration();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getCurrentPosition() {
|
||||
return internalPlayer.getCurrentPosition();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getBufferedPosition() {
|
||||
return internalPlayer.getBufferedPosition();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBufferedPercentage() {
|
||||
long bufferedPosition = getBufferedPosition();
|
||||
long duration = getDuration();
|
||||
return bufferedPosition == ExoPlayer.UNKNOWN_TIME || duration == ExoPlayer.UNKNOWN_TIME ? 0
|
||||
: (int) (duration == 0 ? 100 : (bufferedPosition * 100) / duration);
|
||||
}
|
||||
|
||||
// Not private so it can be called from an inner class without going through a thunk method.
|
||||
/* package */ void handleEvent(Message msg) {
|
||||
switch (msg.what) {
|
||||
case ExoPlayerImplInternal.MSG_PREPARED: {
|
||||
System.arraycopy(msg.obj, 0, trackFormats, 0, trackFormats.length);
|
||||
playbackState = msg.arg1;
|
||||
for (Listener listener : listeners) {
|
||||
listener.onPlayerStateChanged(playWhenReady, playbackState);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ExoPlayerImplInternal.MSG_STATE_CHANGED: {
|
||||
playbackState = msg.arg1;
|
||||
for (Listener listener : listeners) {
|
||||
listener.onPlayerStateChanged(playWhenReady, playbackState);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ExoPlayerImplInternal.MSG_SET_PLAY_WHEN_READY_ACK: {
|
||||
pendingPlayWhenReadyAcks--;
|
||||
if (pendingPlayWhenReadyAcks == 0) {
|
||||
for (Listener listener : listeners) {
|
||||
listener.onPlayWhenReadyCommitted();
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ExoPlayerImplInternal.MSG_ERROR: {
|
||||
ExoPlaybackException exception = (ExoPlaybackException) msg.obj;
|
||||
for (Listener listener : listeners) {
|
||||
listener.onPlayerError(exception);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,668 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.ExoPlayer.ExoPlayerComponent;
|
||||
import com.b44t.messenger.exoplayer.util.Assertions;
|
||||
import com.b44t.messenger.exoplayer.util.PriorityHandlerThread;
|
||||
import com.b44t.messenger.exoplayer.util.TraceUtil;
|
||||
import com.b44t.messenger.exoplayer.util.Util;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.HandlerThread;
|
||||
import android.os.Looper;
|
||||
import android.os.Message;
|
||||
import android.os.Process;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
import android.util.Pair;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Implements the internal behavior of {@link ExoPlayerImpl}.
|
||||
*/
|
||||
/* package */ final class ExoPlayerImplInternal implements Handler.Callback {
|
||||
|
||||
private static final String TAG = "ExoPlayerImplInternal";
|
||||
|
||||
// External messages
|
||||
public static final int MSG_PREPARED = 1;
|
||||
public static final int MSG_STATE_CHANGED = 2;
|
||||
public static final int MSG_SET_PLAY_WHEN_READY_ACK = 3;
|
||||
public static final int MSG_ERROR = 4;
|
||||
|
||||
// Internal messages
|
||||
private static final int MSG_PREPARE = 1;
|
||||
private static final int MSG_INCREMENTAL_PREPARE = 2;
|
||||
private static final int MSG_SET_PLAY_WHEN_READY = 3;
|
||||
private static final int MSG_STOP = 4;
|
||||
private static final int MSG_RELEASE = 5;
|
||||
private static final int MSG_SEEK_TO = 6;
|
||||
private static final int MSG_DO_SOME_WORK = 7;
|
||||
private static final int MSG_SET_RENDERER_SELECTED_TRACK = 8;
|
||||
private static final int MSG_CUSTOM = 9;
|
||||
|
||||
private static final int PREPARE_INTERVAL_MS = 10;
|
||||
private static final int RENDERING_INTERVAL_MS = 10;
|
||||
private static final int IDLE_INTERVAL_MS = 1000;
|
||||
|
||||
private final Handler handler;
|
||||
private final HandlerThread internalPlaybackThread;
|
||||
private final Handler eventHandler;
|
||||
private final StandaloneMediaClock standaloneMediaClock;
|
||||
private final AtomicInteger pendingSeekCount;
|
||||
private final List<TrackRenderer> enabledRenderers;
|
||||
private final MediaFormat[][] trackFormats;
|
||||
private final int[] selectedTrackIndices;
|
||||
private final long minBufferUs;
|
||||
private final long minRebufferUs;
|
||||
|
||||
private TrackRenderer[] renderers;
|
||||
private TrackRenderer rendererMediaClockSource;
|
||||
private MediaClock rendererMediaClock;
|
||||
|
||||
private boolean released;
|
||||
private boolean playWhenReady;
|
||||
private boolean rebuffering;
|
||||
private int state;
|
||||
private int customMessagesSent = 0;
|
||||
private int customMessagesProcessed = 0;
|
||||
private long lastSeekPositionMs;
|
||||
private long elapsedRealtimeUs;
|
||||
|
||||
private volatile long durationUs;
|
||||
private volatile long positionUs;
|
||||
private volatile long bufferedPositionUs;
|
||||
|
||||
public ExoPlayerImplInternal(Handler eventHandler, boolean playWhenReady,
|
||||
int[] selectedTrackIndices, int minBufferMs, int minRebufferMs) {
|
||||
this.eventHandler = eventHandler;
|
||||
this.playWhenReady = playWhenReady;
|
||||
this.minBufferUs = minBufferMs * 1000L;
|
||||
this.minRebufferUs = minRebufferMs * 1000L;
|
||||
this.selectedTrackIndices = Arrays.copyOf(selectedTrackIndices, selectedTrackIndices.length);
|
||||
this.state = ExoPlayer.STATE_IDLE;
|
||||
this.durationUs = TrackRenderer.UNKNOWN_TIME_US;
|
||||
this.bufferedPositionUs = TrackRenderer.UNKNOWN_TIME_US;
|
||||
|
||||
standaloneMediaClock = new StandaloneMediaClock();
|
||||
pendingSeekCount = new AtomicInteger();
|
||||
enabledRenderers = new ArrayList<>(selectedTrackIndices.length);
|
||||
trackFormats = new MediaFormat[selectedTrackIndices.length][];
|
||||
// Note: The documentation for Process.THREAD_PRIORITY_AUDIO that states "Applications can
|
||||
// not normally change to this priority" is incorrect.
|
||||
internalPlaybackThread = new PriorityHandlerThread("ExoPlayerImplInternal:Handler",
|
||||
Process.THREAD_PRIORITY_AUDIO);
|
||||
internalPlaybackThread.start();
|
||||
handler = new Handler(internalPlaybackThread.getLooper(), this);
|
||||
}
|
||||
|
||||
public Looper getPlaybackLooper() {
|
||||
return internalPlaybackThread.getLooper();
|
||||
}
|
||||
|
||||
public long getCurrentPosition() {
|
||||
return pendingSeekCount.get() > 0 ? lastSeekPositionMs : (positionUs / 1000);
|
||||
}
|
||||
|
||||
public long getBufferedPosition() {
|
||||
return bufferedPositionUs == TrackRenderer.UNKNOWN_TIME_US ? ExoPlayer.UNKNOWN_TIME
|
||||
: bufferedPositionUs / 1000;
|
||||
}
|
||||
|
||||
public long getDuration() {
|
||||
return durationUs == TrackRenderer.UNKNOWN_TIME_US ? ExoPlayer.UNKNOWN_TIME
|
||||
: durationUs / 1000;
|
||||
}
|
||||
|
||||
public void prepare(TrackRenderer... renderers) {
|
||||
handler.obtainMessage(MSG_PREPARE, renderers).sendToTarget();
|
||||
}
|
||||
|
||||
public void setPlayWhenReady(boolean playWhenReady) {
|
||||
handler.obtainMessage(MSG_SET_PLAY_WHEN_READY, playWhenReady ? 1 : 0, 0).sendToTarget();
|
||||
}
|
||||
|
||||
public void seekTo(long positionMs) {
|
||||
lastSeekPositionMs = positionMs;
|
||||
pendingSeekCount.incrementAndGet();
|
||||
handler.obtainMessage(MSG_SEEK_TO, Util.getTopInt(positionMs),
|
||||
Util.getBottomInt(positionMs)).sendToTarget();
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
handler.sendEmptyMessage(MSG_STOP);
|
||||
}
|
||||
|
||||
public void setRendererSelectedTrack(int rendererIndex, int trackIndex) {
|
||||
handler.obtainMessage(MSG_SET_RENDERER_SELECTED_TRACK, rendererIndex, trackIndex)
|
||||
.sendToTarget();
|
||||
}
|
||||
|
||||
public void sendMessage(ExoPlayerComponent target, int messageType, Object message) {
|
||||
customMessagesSent++;
|
||||
handler.obtainMessage(MSG_CUSTOM, messageType, 0, Pair.create(target, message)).sendToTarget();
|
||||
}
|
||||
|
||||
public synchronized void blockingSendMessage(ExoPlayerComponent target, int messageType,
|
||||
Object message) {
|
||||
if (released) {
|
||||
Log.w(TAG, "Sent message(" + messageType + ") after release. Message ignored.");
|
||||
return;
|
||||
}
|
||||
int messageNumber = customMessagesSent++;
|
||||
handler.obtainMessage(MSG_CUSTOM, messageType, 0, Pair.create(target, message)).sendToTarget();
|
||||
while (customMessagesProcessed <= messageNumber) {
|
||||
try {
|
||||
wait();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void release() {
|
||||
if (released) {
|
||||
return;
|
||||
}
|
||||
handler.sendEmptyMessage(MSG_RELEASE);
|
||||
while (!released) {
|
||||
try {
|
||||
wait();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
internalPlaybackThread.quit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean handleMessage(Message msg) {
|
||||
try {
|
||||
switch (msg.what) {
|
||||
case MSG_PREPARE: {
|
||||
prepareInternal((TrackRenderer[]) msg.obj);
|
||||
return true;
|
||||
}
|
||||
case MSG_INCREMENTAL_PREPARE: {
|
||||
incrementalPrepareInternal();
|
||||
return true;
|
||||
}
|
||||
case MSG_SET_PLAY_WHEN_READY: {
|
||||
setPlayWhenReadyInternal(msg.arg1 != 0);
|
||||
return true;
|
||||
}
|
||||
case MSG_DO_SOME_WORK: {
|
||||
doSomeWork();
|
||||
return true;
|
||||
}
|
||||
case MSG_SEEK_TO: {
|
||||
seekToInternal(Util.getLong(msg.arg1, msg.arg2));
|
||||
return true;
|
||||
}
|
||||
case MSG_STOP: {
|
||||
stopInternal();
|
||||
return true;
|
||||
}
|
||||
case MSG_RELEASE: {
|
||||
releaseInternal();
|
||||
return true;
|
||||
}
|
||||
case MSG_CUSTOM: {
|
||||
sendMessageInternal(msg.arg1, msg.obj);
|
||||
return true;
|
||||
}
|
||||
case MSG_SET_RENDERER_SELECTED_TRACK: {
|
||||
setRendererSelectedTrackInternal(msg.arg1, msg.arg2);
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
} catch (ExoPlaybackException e) {
|
||||
Log.e(TAG, "Internal track renderer error.", e);
|
||||
eventHandler.obtainMessage(MSG_ERROR, e).sendToTarget();
|
||||
stopInternal();
|
||||
return true;
|
||||
} catch (RuntimeException e) {
|
||||
Log.e(TAG, "Internal runtime error.", e);
|
||||
eventHandler.obtainMessage(MSG_ERROR, new ExoPlaybackException(e, true)).sendToTarget();
|
||||
stopInternal();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void setState(int state) {
|
||||
if (this.state != state) {
|
||||
this.state = state;
|
||||
eventHandler.obtainMessage(MSG_STATE_CHANGED, state, 0).sendToTarget();
|
||||
}
|
||||
}
|
||||
|
||||
private void prepareInternal(TrackRenderer[] renderers) throws ExoPlaybackException {
|
||||
resetInternal();
|
||||
this.renderers = renderers;
|
||||
Arrays.fill(trackFormats, null);
|
||||
setState(ExoPlayer.STATE_PREPARING);
|
||||
incrementalPrepareInternal();
|
||||
}
|
||||
|
||||
private void incrementalPrepareInternal() throws ExoPlaybackException {
|
||||
long operationStartTimeMs = SystemClock.elapsedRealtime();
|
||||
boolean prepared = true;
|
||||
for (int rendererIndex = 0; rendererIndex < renderers.length; rendererIndex++) {
|
||||
TrackRenderer renderer = renderers[rendererIndex];
|
||||
if (renderer.getState() == TrackRenderer.STATE_UNPREPARED) {
|
||||
int state = renderer.prepare(positionUs);
|
||||
if (state == TrackRenderer.STATE_UNPREPARED) {
|
||||
renderer.maybeThrowError();
|
||||
prepared = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!prepared) {
|
||||
// We're still waiting for some sources to be prepared.
|
||||
scheduleNextOperation(MSG_INCREMENTAL_PREPARE, operationStartTimeMs, PREPARE_INTERVAL_MS);
|
||||
return;
|
||||
}
|
||||
|
||||
long durationUs = 0;
|
||||
boolean allRenderersEnded = true;
|
||||
boolean allRenderersReadyOrEnded = true;
|
||||
for (int rendererIndex = 0; rendererIndex < renderers.length; rendererIndex++) {
|
||||
TrackRenderer renderer = renderers[rendererIndex];
|
||||
int rendererTrackCount = renderer.getTrackCount();
|
||||
MediaFormat[] rendererTrackFormats = new MediaFormat[rendererTrackCount];
|
||||
for (int trackIndex = 0; trackIndex < rendererTrackCount; trackIndex++) {
|
||||
rendererTrackFormats[trackIndex] = renderer.getFormat(trackIndex);
|
||||
}
|
||||
trackFormats[rendererIndex] = rendererTrackFormats;
|
||||
if (rendererTrackCount > 0) {
|
||||
if (durationUs == TrackRenderer.UNKNOWN_TIME_US) {
|
||||
// We've already encountered a track for which the duration is unknown, so the media
|
||||
// duration is unknown regardless of the duration of this track.
|
||||
} else {
|
||||
long trackDurationUs = renderer.getDurationUs();
|
||||
if (trackDurationUs == TrackRenderer.UNKNOWN_TIME_US) {
|
||||
durationUs = TrackRenderer.UNKNOWN_TIME_US;
|
||||
} else if (trackDurationUs == TrackRenderer.MATCH_LONGEST_US) {
|
||||
// Do nothing.
|
||||
} else {
|
||||
durationUs = Math.max(durationUs, trackDurationUs);
|
||||
}
|
||||
}
|
||||
int trackIndex = selectedTrackIndices[rendererIndex];
|
||||
if (0 <= trackIndex && trackIndex < rendererTrackFormats.length) {
|
||||
enableRenderer(renderer, trackIndex, false);
|
||||
allRenderersEnded = allRenderersEnded && renderer.isEnded();
|
||||
allRenderersReadyOrEnded = allRenderersReadyOrEnded && rendererReadyOrEnded(renderer);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.durationUs = durationUs;
|
||||
|
||||
if (allRenderersEnded
|
||||
&& (durationUs == TrackRenderer.UNKNOWN_TIME_US || durationUs <= positionUs)) {
|
||||
// We don't expect this case, but handle it anyway.
|
||||
state = ExoPlayer.STATE_ENDED;
|
||||
} else {
|
||||
state = allRenderersReadyOrEnded ? ExoPlayer.STATE_READY : ExoPlayer.STATE_BUFFERING;
|
||||
}
|
||||
|
||||
// Fire an event indicating that the player has been prepared, passing the initial state and
|
||||
// renderer track information.
|
||||
eventHandler.obtainMessage(MSG_PREPARED, state, 0, trackFormats).sendToTarget();
|
||||
|
||||
// Start the renderers if required, and schedule the first piece of work.
|
||||
if (playWhenReady && state == ExoPlayer.STATE_READY) {
|
||||
startRenderers();
|
||||
}
|
||||
handler.sendEmptyMessage(MSG_DO_SOME_WORK);
|
||||
}
|
||||
|
||||
private void enableRenderer(TrackRenderer renderer, int trackIndex, boolean joining)
|
||||
throws ExoPlaybackException {
|
||||
renderer.enable(trackIndex, positionUs, joining);
|
||||
enabledRenderers.add(renderer);
|
||||
MediaClock mediaClock = renderer.getMediaClock();
|
||||
if (mediaClock != null) {
|
||||
Assertions.checkState(rendererMediaClock == null);
|
||||
rendererMediaClock = mediaClock;
|
||||
rendererMediaClockSource = renderer;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean rendererReadyOrEnded(TrackRenderer renderer) {
|
||||
if (renderer.isEnded()) {
|
||||
return true;
|
||||
}
|
||||
if (!renderer.isReady()) {
|
||||
return false;
|
||||
}
|
||||
if (state == ExoPlayer.STATE_READY) {
|
||||
return true;
|
||||
}
|
||||
long rendererDurationUs = renderer.getDurationUs();
|
||||
long rendererBufferedPositionUs = renderer.getBufferedPositionUs();
|
||||
long minBufferDurationUs = rebuffering ? minRebufferUs : minBufferUs;
|
||||
return minBufferDurationUs <= 0
|
||||
|| rendererBufferedPositionUs == TrackRenderer.UNKNOWN_TIME_US
|
||||
|| rendererBufferedPositionUs == TrackRenderer.END_OF_TRACK_US
|
||||
|| rendererBufferedPositionUs >= positionUs + minBufferDurationUs
|
||||
|| (rendererDurationUs != TrackRenderer.UNKNOWN_TIME_US
|
||||
&& rendererDurationUs != TrackRenderer.MATCH_LONGEST_US
|
||||
&& rendererBufferedPositionUs >= rendererDurationUs);
|
||||
}
|
||||
|
||||
private void setPlayWhenReadyInternal(boolean playWhenReady) throws ExoPlaybackException {
|
||||
try {
|
||||
rebuffering = false;
|
||||
this.playWhenReady = playWhenReady;
|
||||
if (!playWhenReady) {
|
||||
stopRenderers();
|
||||
updatePositionUs();
|
||||
} else {
|
||||
if (state == ExoPlayer.STATE_READY) {
|
||||
startRenderers();
|
||||
handler.sendEmptyMessage(MSG_DO_SOME_WORK);
|
||||
} else if (state == ExoPlayer.STATE_BUFFERING) {
|
||||
handler.sendEmptyMessage(MSG_DO_SOME_WORK);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
eventHandler.obtainMessage(MSG_SET_PLAY_WHEN_READY_ACK).sendToTarget();
|
||||
}
|
||||
}
|
||||
|
||||
private void startRenderers() throws ExoPlaybackException {
|
||||
rebuffering = false;
|
||||
standaloneMediaClock.start();
|
||||
for (int i = 0; i < enabledRenderers.size(); i++) {
|
||||
enabledRenderers.get(i).start();
|
||||
}
|
||||
}
|
||||
|
||||
private void stopRenderers() throws ExoPlaybackException {
|
||||
standaloneMediaClock.stop();
|
||||
for (int i = 0; i < enabledRenderers.size(); i++) {
|
||||
ensureStopped(enabledRenderers.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
private void updatePositionUs() {
|
||||
if (rendererMediaClock != null && enabledRenderers.contains(rendererMediaClockSource)
|
||||
&& !rendererMediaClockSource.isEnded()) {
|
||||
positionUs = rendererMediaClock.getPositionUs();
|
||||
standaloneMediaClock.setPositionUs(positionUs);
|
||||
} else {
|
||||
positionUs = standaloneMediaClock.getPositionUs();
|
||||
}
|
||||
elapsedRealtimeUs = SystemClock.elapsedRealtime() * 1000;
|
||||
}
|
||||
|
||||
private void doSomeWork() throws ExoPlaybackException {
|
||||
TraceUtil.beginSection("doSomeWork");
|
||||
long operationStartTimeMs = SystemClock.elapsedRealtime();
|
||||
long bufferedPositionUs = durationUs != TrackRenderer.UNKNOWN_TIME_US ? durationUs
|
||||
: Long.MAX_VALUE;
|
||||
boolean allRenderersEnded = true;
|
||||
boolean allRenderersReadyOrEnded = true;
|
||||
updatePositionUs();
|
||||
for (int i = 0; i < enabledRenderers.size(); i++) {
|
||||
TrackRenderer renderer = enabledRenderers.get(i);
|
||||
// TODO: Each renderer should return the maximum delay before which it wishes to be
|
||||
// invoked again. The minimum of these values should then be used as the delay before the next
|
||||
// invocation of this method.
|
||||
renderer.doSomeWork(positionUs, elapsedRealtimeUs);
|
||||
allRenderersEnded = allRenderersEnded && renderer.isEnded();
|
||||
|
||||
// Determine whether the renderer is ready (or ended). If it's not, throw an error that's
|
||||
// preventing the renderer from making progress, if such an error exists.
|
||||
boolean rendererReadyOrEnded = rendererReadyOrEnded(renderer);
|
||||
if (!rendererReadyOrEnded) {
|
||||
renderer.maybeThrowError();
|
||||
}
|
||||
allRenderersReadyOrEnded = allRenderersReadyOrEnded && rendererReadyOrEnded;
|
||||
|
||||
if (bufferedPositionUs == TrackRenderer.UNKNOWN_TIME_US) {
|
||||
// We've already encountered a track for which the buffered position is unknown. Hence the
|
||||
// media buffer position unknown regardless of the buffered position of this track.
|
||||
} else {
|
||||
long rendererDurationUs = renderer.getDurationUs();
|
||||
long rendererBufferedPositionUs = renderer.getBufferedPositionUs();
|
||||
if (rendererBufferedPositionUs == TrackRenderer.UNKNOWN_TIME_US) {
|
||||
bufferedPositionUs = TrackRenderer.UNKNOWN_TIME_US;
|
||||
} else if (rendererBufferedPositionUs == TrackRenderer.END_OF_TRACK_US
|
||||
|| (rendererDurationUs != TrackRenderer.UNKNOWN_TIME_US
|
||||
&& rendererDurationUs != TrackRenderer.MATCH_LONGEST_US
|
||||
&& rendererBufferedPositionUs >= rendererDurationUs)) {
|
||||
// This track is fully buffered.
|
||||
} else {
|
||||
bufferedPositionUs = Math.min(bufferedPositionUs, rendererBufferedPositionUs);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.bufferedPositionUs = bufferedPositionUs;
|
||||
|
||||
if (allRenderersEnded
|
||||
&& (durationUs == TrackRenderer.UNKNOWN_TIME_US || durationUs <= positionUs)) {
|
||||
setState(ExoPlayer.STATE_ENDED);
|
||||
stopRenderers();
|
||||
} else if (state == ExoPlayer.STATE_BUFFERING && allRenderersReadyOrEnded) {
|
||||
setState(ExoPlayer.STATE_READY);
|
||||
if (playWhenReady) {
|
||||
startRenderers();
|
||||
}
|
||||
} else if (state == ExoPlayer.STATE_READY && !allRenderersReadyOrEnded) {
|
||||
rebuffering = playWhenReady;
|
||||
setState(ExoPlayer.STATE_BUFFERING);
|
||||
stopRenderers();
|
||||
}
|
||||
|
||||
handler.removeMessages(MSG_DO_SOME_WORK);
|
||||
if ((playWhenReady && state == ExoPlayer.STATE_READY) || state == ExoPlayer.STATE_BUFFERING) {
|
||||
scheduleNextOperation(MSG_DO_SOME_WORK, operationStartTimeMs, RENDERING_INTERVAL_MS);
|
||||
} else if (!enabledRenderers.isEmpty()) {
|
||||
scheduleNextOperation(MSG_DO_SOME_WORK, operationStartTimeMs, IDLE_INTERVAL_MS);
|
||||
}
|
||||
|
||||
TraceUtil.endSection();
|
||||
}
|
||||
|
||||
private void scheduleNextOperation(int operationType, long thisOperationStartTimeMs,
|
||||
long intervalMs) {
|
||||
long nextOperationStartTimeMs = thisOperationStartTimeMs + intervalMs;
|
||||
long nextOperationDelayMs = nextOperationStartTimeMs - SystemClock.elapsedRealtime();
|
||||
if (nextOperationDelayMs <= 0) {
|
||||
handler.sendEmptyMessage(operationType);
|
||||
} else {
|
||||
handler.sendEmptyMessageDelayed(operationType, nextOperationDelayMs);
|
||||
}
|
||||
}
|
||||
|
||||
private void seekToInternal(long positionMs) throws ExoPlaybackException {
|
||||
try {
|
||||
if (positionMs == (positionUs / 1000)) {
|
||||
// Seek is to the current position. Do nothing.
|
||||
return;
|
||||
}
|
||||
|
||||
rebuffering = false;
|
||||
positionUs = positionMs * 1000;
|
||||
standaloneMediaClock.stop();
|
||||
standaloneMediaClock.setPositionUs(positionUs);
|
||||
if (state == ExoPlayer.STATE_IDLE || state == ExoPlayer.STATE_PREPARING) {
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < enabledRenderers.size(); i++) {
|
||||
TrackRenderer renderer = enabledRenderers.get(i);
|
||||
ensureStopped(renderer);
|
||||
renderer.seekTo(positionUs);
|
||||
}
|
||||
setState(ExoPlayer.STATE_BUFFERING);
|
||||
handler.sendEmptyMessage(MSG_DO_SOME_WORK);
|
||||
} finally {
|
||||
pendingSeekCount.decrementAndGet();
|
||||
}
|
||||
}
|
||||
|
||||
private void stopInternal() {
|
||||
resetInternal();
|
||||
setState(ExoPlayer.STATE_IDLE);
|
||||
}
|
||||
|
||||
private void releaseInternal() {
|
||||
resetInternal();
|
||||
setState(ExoPlayer.STATE_IDLE);
|
||||
synchronized (this) {
|
||||
released = true;
|
||||
notifyAll();
|
||||
}
|
||||
}
|
||||
|
||||
private void resetInternal() {
|
||||
handler.removeMessages(MSG_DO_SOME_WORK);
|
||||
handler.removeMessages(MSG_INCREMENTAL_PREPARE);
|
||||
rebuffering = false;
|
||||
standaloneMediaClock.stop();
|
||||
if (renderers == null) {
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < renderers.length; i++) {
|
||||
TrackRenderer renderer = renderers[i];
|
||||
stopAndDisable(renderer);
|
||||
release(renderer);
|
||||
}
|
||||
renderers = null;
|
||||
rendererMediaClock = null;
|
||||
rendererMediaClockSource = null;
|
||||
enabledRenderers.clear();
|
||||
}
|
||||
|
||||
private void stopAndDisable(TrackRenderer renderer) {
|
||||
try {
|
||||
ensureDisabled(renderer);
|
||||
} catch (ExoPlaybackException e) {
|
||||
// There's nothing we can do.
|
||||
Log.e(TAG, "Stop failed.", e);
|
||||
} catch (RuntimeException e) {
|
||||
// Ditto.
|
||||
Log.e(TAG, "Stop failed.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void release(TrackRenderer renderer) {
|
||||
try {
|
||||
renderer.release();
|
||||
} catch (ExoPlaybackException e) {
|
||||
// There's nothing we can do.
|
||||
Log.e(TAG, "Release failed.", e);
|
||||
} catch (RuntimeException e) {
|
||||
// Ditto.
|
||||
Log.e(TAG, "Release failed.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> void sendMessageInternal(int what, Object obj)
|
||||
throws ExoPlaybackException {
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Pair<ExoPlayerComponent, Object> targetAndMessage = (Pair<ExoPlayerComponent, Object>) obj;
|
||||
targetAndMessage.first.handleMessage(what, targetAndMessage.second);
|
||||
if (state != ExoPlayer.STATE_IDLE && state != ExoPlayer.STATE_PREPARING) {
|
||||
// The message may have caused something to change that now requires us to do work.
|
||||
handler.sendEmptyMessage(MSG_DO_SOME_WORK);
|
||||
}
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
customMessagesProcessed++;
|
||||
notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setRendererSelectedTrackInternal(int rendererIndex, int trackIndex)
|
||||
throws ExoPlaybackException {
|
||||
if (selectedTrackIndices[rendererIndex] == trackIndex) {
|
||||
return;
|
||||
}
|
||||
|
||||
selectedTrackIndices[rendererIndex] = trackIndex;
|
||||
if (state == ExoPlayer.STATE_IDLE || state == ExoPlayer.STATE_PREPARING) {
|
||||
return;
|
||||
}
|
||||
|
||||
TrackRenderer renderer = renderers[rendererIndex];
|
||||
int rendererState = renderer.getState();
|
||||
if (rendererState == TrackRenderer.STATE_UNPREPARED
|
||||
|| rendererState == TrackRenderer.STATE_RELEASED
|
||||
|| renderer.getTrackCount() == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean isEnabled = rendererState == TrackRenderer.STATE_ENABLED
|
||||
|| rendererState == TrackRenderer.STATE_STARTED;
|
||||
boolean shouldEnable = 0 <= trackIndex && trackIndex < trackFormats[rendererIndex].length;
|
||||
|
||||
if (isEnabled) {
|
||||
// The renderer is currently enabled. We need to disable it, so that we can either re-enable
|
||||
// it with the newly selected track (if shouldEnable is true) or because we want to leave it
|
||||
// disabled (if shouldEnable is false).
|
||||
if (!shouldEnable && renderer == rendererMediaClockSource) {
|
||||
// We've been using rendererMediaClockSource to advance the current position, but it's being
|
||||
// disabled and won't be re-enabled. Sync standaloneMediaClock so that it can take over
|
||||
// timing responsibilities.
|
||||
standaloneMediaClock.setPositionUs(rendererMediaClock.getPositionUs());
|
||||
}
|
||||
ensureDisabled(renderer);
|
||||
enabledRenderers.remove(renderer);
|
||||
}
|
||||
|
||||
if (shouldEnable) {
|
||||
// Re-enable the renderer with the newly selected track.
|
||||
boolean playing = playWhenReady && state == ExoPlayer.STATE_READY;
|
||||
// Consider as joining if the renderer was previously disabled, but not when switching tracks.
|
||||
boolean joining = !isEnabled && playing;
|
||||
enableRenderer(renderer, trackIndex, joining);
|
||||
if (playing) {
|
||||
renderer.start();
|
||||
}
|
||||
handler.sendEmptyMessage(MSG_DO_SOME_WORK);
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureStopped(TrackRenderer renderer) throws ExoPlaybackException {
|
||||
if (renderer.getState() == TrackRenderer.STATE_STARTED) {
|
||||
renderer.stop();
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureDisabled(TrackRenderer renderer) throws ExoPlaybackException {
|
||||
ensureStopped(renderer);
|
||||
if (renderer.getState() == TrackRenderer.STATE_ENABLED) {
|
||||
renderer.disable();
|
||||
if (renderer == rendererMediaClockSource) {
|
||||
rendererMediaClock = null;
|
||||
rendererMediaClockSource = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
/**
|
||||
* Information about the ExoPlayer library.
|
||||
*/
|
||||
public final class ExoPlayerLibraryInfo {
|
||||
|
||||
/**
|
||||
* The version of the library, expressed as a string.
|
||||
*/
|
||||
public static final String VERSION = "1.5.8";
|
||||
|
||||
/**
|
||||
* The version of the library, expressed as an integer.
|
||||
* <p>
|
||||
* Three digits are used for each component of {@link #VERSION}. For example "1.2.3" has the
|
||||
* corresponding integer version 1002003 (001-002-003), and "123.45.6" has the corresponding
|
||||
* integer version 123045006 (123-045-006).
|
||||
*/
|
||||
public static final int VERSION_INT = 1005008;
|
||||
|
||||
/**
|
||||
* Whether the library was compiled with {@link com.b44t.messenger.exoplayer.util.Assertions}
|
||||
* checks enabled.
|
||||
*/
|
||||
public static final boolean ASSERTIONS_ENABLED = true;
|
||||
|
||||
/**
|
||||
* Whether the library was compiled with {@link com.b44t.messenger.exoplayer.util.TraceUtil}
|
||||
* trace enabled.
|
||||
*/
|
||||
public static final boolean TRACE_ENABLED = true;
|
||||
|
||||
private ExoPlayerLibraryInfo() {}
|
||||
|
||||
}
|
||||
@@ -1,349 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.SampleSource.SampleSourceReader;
|
||||
import com.b44t.messenger.exoplayer.drm.DrmInitData;
|
||||
import com.b44t.messenger.exoplayer.drm.DrmInitData.SchemeInitData;
|
||||
import com.b44t.messenger.exoplayer.extractor.ExtractorSampleSource;
|
||||
import com.b44t.messenger.exoplayer.extractor.mp4.PsshAtomUtil;
|
||||
import com.b44t.messenger.exoplayer.util.Assertions;
|
||||
import com.b44t.messenger.exoplayer.util.MimeTypes;
|
||||
import com.b44t.messenger.exoplayer.util.Util;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.media.MediaExtractor;
|
||||
import android.net.Uri;
|
||||
|
||||
import java.io.FileDescriptor;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Extracts samples from a stream using Android's {@link MediaExtractor}.
|
||||
* <p>
|
||||
* Warning - This class is marked as deprecated because there are known device specific issues
|
||||
* associated with its use, including playbacks not starting, playbacks stuttering and other
|
||||
* miscellaneous failures. For mp4, m4a, mp3, webm, mkv, mpeg-ts, ogg, wav and aac playbacks it is
|
||||
* strongly recommended to use {@link ExtractorSampleSource} instead. Where this is not possible
|
||||
* this class can still be used, but please be aware of the associated risks. Playing container
|
||||
* formats for which an ExoPlayer extractor does not yet exist (e.g. avi) is a valid use case of
|
||||
* this class.
|
||||
* <p>
|
||||
* Over time we hope to enhance {@link ExtractorSampleSource} to support more formats, and hence
|
||||
* make use of this class unnecessary.
|
||||
*/
|
||||
// TODO: This implementation needs to be fixed so that its methods are non-blocking (either
|
||||
// through use of a background thread, or through changes to the framework's MediaExtractor API).
|
||||
@Deprecated
|
||||
@TargetApi(16)
|
||||
public final class FrameworkSampleSource implements SampleSource, SampleSourceReader {
|
||||
|
||||
private static final int ALLOWED_FLAGS_MASK = C.SAMPLE_FLAG_SYNC | C.SAMPLE_FLAG_ENCRYPTED;
|
||||
|
||||
private static final int TRACK_STATE_DISABLED = 0;
|
||||
private static final int TRACK_STATE_ENABLED = 1;
|
||||
private static final int TRACK_STATE_FORMAT_SENT = 2;
|
||||
|
||||
// Parameters for a Uri data source.
|
||||
private final Context context;
|
||||
private final Uri uri;
|
||||
private final Map<String, String> headers;
|
||||
|
||||
// Parameters for a FileDescriptor data source.
|
||||
private final FileDescriptor fileDescriptor;
|
||||
private final long fileDescriptorOffset;
|
||||
private final long fileDescriptorLength;
|
||||
|
||||
private IOException preparationError;
|
||||
private MediaExtractor extractor;
|
||||
private MediaFormat[] trackFormats;
|
||||
private boolean prepared;
|
||||
private int remainingReleaseCount;
|
||||
private int[] trackStates;
|
||||
private boolean[] pendingDiscontinuities;
|
||||
|
||||
private long lastSeekPositionUs;
|
||||
private long pendingSeekPositionUs;
|
||||
|
||||
/**
|
||||
* Instantiates a new sample extractor reading from the specified {@code uri}.
|
||||
*
|
||||
* @param context Context for resolving {@code uri}.
|
||||
* @param uri The content URI from which to extract data.
|
||||
* @param headers Headers to send with requests for data.
|
||||
*/
|
||||
public FrameworkSampleSource(Context context, Uri uri, Map<String, String> headers) {
|
||||
Assertions.checkState(Util.SDK_INT >= 16);
|
||||
this.context = Assertions.checkNotNull(context);
|
||||
this.uri = Assertions.checkNotNull(uri);
|
||||
this.headers = headers;
|
||||
fileDescriptor = null;
|
||||
fileDescriptorOffset = 0;
|
||||
fileDescriptorLength = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new sample extractor reading from the specified seekable {@code fileDescriptor}.
|
||||
* The caller is responsible for releasing the file descriptor.
|
||||
*
|
||||
* @param fileDescriptor File descriptor from which to read.
|
||||
* @param fileDescriptorOffset The offset in bytes where the data to be extracted starts.
|
||||
* @param fileDescriptorLength The length in bytes of the data to be extracted.
|
||||
*/
|
||||
public FrameworkSampleSource(FileDescriptor fileDescriptor, long fileDescriptorOffset,
|
||||
long fileDescriptorLength) {
|
||||
Assertions.checkState(Util.SDK_INT >= 16);
|
||||
this.fileDescriptor = Assertions.checkNotNull(fileDescriptor);
|
||||
this.fileDescriptorOffset = fileDescriptorOffset;
|
||||
this.fileDescriptorLength = fileDescriptorLength;
|
||||
context = null;
|
||||
uri = null;
|
||||
headers = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SampleSourceReader register() {
|
||||
remainingReleaseCount++;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean prepare(long positionUs) {
|
||||
if (!prepared) {
|
||||
if (preparationError != null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
extractor = new MediaExtractor();
|
||||
try {
|
||||
if (context != null) {
|
||||
extractor.setDataSource(context, uri, headers);
|
||||
} else {
|
||||
extractor.setDataSource(fileDescriptor, fileDescriptorOffset, fileDescriptorLength);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
preparationError = e;
|
||||
return false;
|
||||
}
|
||||
|
||||
trackStates = new int[extractor.getTrackCount()];
|
||||
pendingDiscontinuities = new boolean[trackStates.length];
|
||||
trackFormats = new MediaFormat[trackStates.length];
|
||||
for (int i = 0; i < trackStates.length; i++) {
|
||||
trackFormats[i] = createMediaFormat(extractor.getTrackFormat(i));
|
||||
}
|
||||
prepared = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTrackCount() {
|
||||
Assertions.checkState(prepared);
|
||||
return trackStates.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MediaFormat getFormat(int track) {
|
||||
Assertions.checkState(prepared);
|
||||
return trackFormats[track];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enable(int track, long positionUs) {
|
||||
Assertions.checkState(prepared);
|
||||
Assertions.checkState(trackStates[track] == TRACK_STATE_DISABLED);
|
||||
trackStates[track] = TRACK_STATE_ENABLED;
|
||||
extractor.selectTrack(track);
|
||||
seekToUsInternal(positionUs, positionUs != 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean continueBuffering(int track, long positionUs) {
|
||||
// MediaExtractor takes care of buffering and blocks until it has samples, so we can always
|
||||
// return true here. Although note that the blocking behavior is itself as bug, as per the
|
||||
// TODO further up this file. This method will need to return something else as part of fixing
|
||||
// the TODO.
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long readDiscontinuity(int track) {
|
||||
if (pendingDiscontinuities[track]) {
|
||||
pendingDiscontinuities[track] = false;
|
||||
return lastSeekPositionUs;
|
||||
}
|
||||
return NO_DISCONTINUITY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int readData(int track, long positionUs, MediaFormatHolder formatHolder,
|
||||
SampleHolder sampleHolder) {
|
||||
Assertions.checkState(prepared);
|
||||
Assertions.checkState(trackStates[track] != TRACK_STATE_DISABLED);
|
||||
if (pendingDiscontinuities[track]) {
|
||||
return NOTHING_READ;
|
||||
}
|
||||
if (trackStates[track] != TRACK_STATE_FORMAT_SENT) {
|
||||
formatHolder.format = trackFormats[track];
|
||||
formatHolder.drmInitData = Util.SDK_INT >= 18 ? getDrmInitDataV18() : null;
|
||||
trackStates[track] = TRACK_STATE_FORMAT_SENT;
|
||||
return FORMAT_READ;
|
||||
}
|
||||
int extractorTrackIndex = extractor.getSampleTrackIndex();
|
||||
if (extractorTrackIndex == track) {
|
||||
if (sampleHolder.data != null) {
|
||||
int offset = sampleHolder.data.position();
|
||||
sampleHolder.size = extractor.readSampleData(sampleHolder.data, offset);
|
||||
sampleHolder.data.position(offset + sampleHolder.size);
|
||||
} else {
|
||||
sampleHolder.size = 0;
|
||||
}
|
||||
sampleHolder.timeUs = extractor.getSampleTime();
|
||||
sampleHolder.flags = extractor.getSampleFlags() & ALLOWED_FLAGS_MASK;
|
||||
if (sampleHolder.isEncrypted()) {
|
||||
sampleHolder.cryptoInfo.setFromExtractorV16(extractor);
|
||||
}
|
||||
pendingSeekPositionUs = C.UNKNOWN_TIME_US;
|
||||
extractor.advance();
|
||||
return SAMPLE_READ;
|
||||
} else {
|
||||
return extractorTrackIndex < 0 ? END_OF_STREAM : NOTHING_READ;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable(int track) {
|
||||
Assertions.checkState(prepared);
|
||||
Assertions.checkState(trackStates[track] != TRACK_STATE_DISABLED);
|
||||
extractor.unselectTrack(track);
|
||||
pendingDiscontinuities[track] = false;
|
||||
trackStates[track] = TRACK_STATE_DISABLED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void maybeThrowError() throws IOException {
|
||||
if (preparationError != null) {
|
||||
throw preparationError;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void seekToUs(long positionUs) {
|
||||
Assertions.checkState(prepared);
|
||||
seekToUsInternal(positionUs, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getBufferedPositionUs() {
|
||||
Assertions.checkState(prepared);
|
||||
long bufferedDurationUs = extractor.getCachedDuration();
|
||||
if (bufferedDurationUs == -1) {
|
||||
return TrackRenderer.UNKNOWN_TIME_US;
|
||||
} else {
|
||||
long sampleTime = extractor.getSampleTime();
|
||||
return sampleTime == -1 ? TrackRenderer.END_OF_TRACK_US : sampleTime + bufferedDurationUs;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release() {
|
||||
Assertions.checkState(remainingReleaseCount > 0);
|
||||
if (--remainingReleaseCount == 0 && extractor != null) {
|
||||
extractor.release();
|
||||
extractor = null;
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(18)
|
||||
private DrmInitData getDrmInitDataV18() {
|
||||
// MediaExtractor only supports psshInfo for MP4, so it's ok to hard code the mimeType here.
|
||||
Map<UUID, byte[]> psshInfo = extractor.getPsshInfo();
|
||||
if (psshInfo == null || psshInfo.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
DrmInitData.Mapped drmInitData = new DrmInitData.Mapped();
|
||||
for (UUID uuid : psshInfo.keySet()) {
|
||||
byte[] psshAtom = PsshAtomUtil.buildPsshAtom(uuid, psshInfo.get(uuid));
|
||||
drmInitData.put(uuid, new SchemeInitData(MimeTypes.VIDEO_MP4, psshAtom));
|
||||
}
|
||||
return drmInitData;
|
||||
}
|
||||
|
||||
private void seekToUsInternal(long positionUs, boolean force) {
|
||||
// Unless forced, avoid duplicate calls to the underlying extractor's seek method in the case
|
||||
// that there have been no interleaving calls to readSample.
|
||||
if (force || pendingSeekPositionUs != positionUs) {
|
||||
lastSeekPositionUs = positionUs;
|
||||
pendingSeekPositionUs = positionUs;
|
||||
extractor.seekTo(positionUs, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
|
||||
for (int i = 0; i < trackStates.length; ++i) {
|
||||
if (trackStates[i] != TRACK_STATE_DISABLED) {
|
||||
pendingDiscontinuities[i] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("InlinedApi")
|
||||
private static MediaFormat createMediaFormat(android.media.MediaFormat format) {
|
||||
String mimeType = format.getString(android.media.MediaFormat.KEY_MIME);
|
||||
String language = getOptionalStringV16(format, android.media.MediaFormat.KEY_LANGUAGE);
|
||||
int maxInputSize = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_MAX_INPUT_SIZE);
|
||||
int width = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_WIDTH);
|
||||
int height = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_HEIGHT);
|
||||
int rotationDegrees = getOptionalIntegerV16(format, "rotation-degrees");
|
||||
int channelCount = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_CHANNEL_COUNT);
|
||||
int sampleRate = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_SAMPLE_RATE);
|
||||
int encoderDelay = getOptionalIntegerV16(format, "encoder-delay");
|
||||
int encoderPadding = getOptionalIntegerV16(format, "encoder-padding");
|
||||
ArrayList<byte[]> initializationData = new ArrayList<>();
|
||||
for (int i = 0; format.containsKey("csd-" + i); i++) {
|
||||
ByteBuffer buffer = format.getByteBuffer("csd-" + i);
|
||||
byte[] data = new byte[buffer.limit()];
|
||||
buffer.get(data);
|
||||
initializationData.add(data);
|
||||
buffer.flip();
|
||||
}
|
||||
long durationUs = format.containsKey(android.media.MediaFormat.KEY_DURATION)
|
||||
? format.getLong(android.media.MediaFormat.KEY_DURATION) : C.UNKNOWN_TIME_US;
|
||||
int pcmEncoding = MimeTypes.AUDIO_RAW.equals(mimeType) ? C.ENCODING_PCM_16BIT
|
||||
: MediaFormat.NO_VALUE;
|
||||
MediaFormat mediaFormat = new MediaFormat(null, mimeType, MediaFormat.NO_VALUE, maxInputSize,
|
||||
durationUs, width, height, rotationDegrees, MediaFormat.NO_VALUE, channelCount, sampleRate,
|
||||
language, MediaFormat.OFFSET_SAMPLE_RELATIVE, initializationData, false,
|
||||
MediaFormat.NO_VALUE, MediaFormat.NO_VALUE, pcmEncoding, encoderDelay, encoderPadding);
|
||||
mediaFormat.setFrameworkFormatV16(format);
|
||||
return mediaFormat;
|
||||
}
|
||||
|
||||
@TargetApi(16)
|
||||
private static final String getOptionalStringV16(android.media.MediaFormat format, String key) {
|
||||
return format.containsKey(key) ? format.getString(key) : null;
|
||||
}
|
||||
|
||||
@TargetApi(16)
|
||||
private static final int getOptionalIntegerV16(android.media.MediaFormat format, String key) {
|
||||
return format.containsKey(key) ? format.getInteger(key) : MediaFormat.NO_VALUE;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.upstream.Allocator;
|
||||
|
||||
/**
|
||||
* Coordinates multiple loaders of time series data.
|
||||
*/
|
||||
public interface LoadControl {
|
||||
|
||||
/**
|
||||
* Registers a loader.
|
||||
*
|
||||
* @param loader The loader being registered.
|
||||
* @param bufferSizeContribution For instances whose {@link Allocator} maintains a pool of memory
|
||||
* for the purpose of satisfying allocation requests, this is a hint indicating the loader's
|
||||
* desired contribution to the size of the pool, in bytes.
|
||||
*/
|
||||
void register(Object loader, int bufferSizeContribution);
|
||||
|
||||
/**
|
||||
* Unregisters a loader.
|
||||
*
|
||||
* @param loader The loader being unregistered.
|
||||
*/
|
||||
void unregister(Object loader);
|
||||
|
||||
/**
|
||||
* Gets the {@link Allocator} that loaders should use to obtain memory allocations into which
|
||||
* data can be loaded.
|
||||
*
|
||||
* @return The {@link Allocator} to use.
|
||||
*/
|
||||
Allocator getAllocator();
|
||||
|
||||
/**
|
||||
* Hints to the control that it should consider trimming any unused memory being held in order
|
||||
* to satisfy allocation requests.
|
||||
* <p>
|
||||
* This method is typically invoked by a recently unregistered loader, once it has released all
|
||||
* of its allocations back to the {@link Allocator}.
|
||||
*/
|
||||
void trimAllocator();
|
||||
|
||||
/**
|
||||
* Invoked by a loader to update the control with its current state.
|
||||
* <p>
|
||||
* This method must be called by a registered loader whenever its state changes. This is true
|
||||
* even if the registered loader does not itself wish to start its next load (since the state of
|
||||
* the loader will still affect whether other registered loaders are allowed to proceed).
|
||||
*
|
||||
* @param loader The loader invoking the update.
|
||||
* @param playbackPositionUs The loader's playback position.
|
||||
* @param nextLoadPositionUs The loader's next load position. -1 if finished, failed, or if the
|
||||
* next load position is not yet known.
|
||||
* @param loading Whether the loader is currently loading data.
|
||||
* @return True if the loader is allowed to start its next load. False otherwise.
|
||||
*/
|
||||
boolean update(Object loader, long playbackPositionUs, long nextLoadPositionUs, boolean loading);
|
||||
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
/**
|
||||
* Tracks the progression of media time.
|
||||
*/
|
||||
public interface MediaClock {
|
||||
|
||||
/**
|
||||
* @return The current media position in microseconds.
|
||||
*/
|
||||
long getPositionUs();
|
||||
|
||||
}
|
||||
-486
@@ -1,486 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.MediaCodecUtil.DecoderQueryException;
|
||||
import com.b44t.messenger.exoplayer.audio.AudioCapabilities;
|
||||
import com.b44t.messenger.exoplayer.audio.AudioTrack;
|
||||
import com.b44t.messenger.exoplayer.drm.DrmSessionManager;
|
||||
import com.b44t.messenger.exoplayer.util.MimeTypes;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.media.AudioManager;
|
||||
import android.media.MediaCodec;
|
||||
import android.media.PlaybackParams;
|
||||
import android.media.audiofx.Virtualizer;
|
||||
import android.os.Handler;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
/**
|
||||
* Decodes and renders audio using {@link MediaCodec} and {@link android.media.AudioTrack}.
|
||||
*/
|
||||
@TargetApi(16)
|
||||
public class MediaCodecAudioTrackRenderer extends MediaCodecTrackRenderer implements MediaClock {
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be notified of {@link MediaCodecAudioTrackRenderer}
|
||||
* events.
|
||||
*/
|
||||
public interface EventListener extends MediaCodecTrackRenderer.EventListener {
|
||||
|
||||
/**
|
||||
* Invoked when an {@link AudioTrack} fails to initialize.
|
||||
*
|
||||
* @param e The corresponding exception.
|
||||
*/
|
||||
void onAudioTrackInitializationError(AudioTrack.InitializationException e);
|
||||
|
||||
/**
|
||||
* Invoked when an {@link AudioTrack} write fails.
|
||||
*
|
||||
* @param e The corresponding exception.
|
||||
*/
|
||||
void onAudioTrackWriteError(AudioTrack.WriteException e);
|
||||
|
||||
/**
|
||||
* Invoked when an {@link AudioTrack} underrun occurs.
|
||||
*
|
||||
* @param bufferSize The size of the {@link AudioTrack}'s buffer, in bytes.
|
||||
* @param bufferSizeMs The size of the {@link AudioTrack}'s buffer, in milliseconds, if it is
|
||||
* configured for PCM output. -1 if it is configured for passthrough output, as the buffered
|
||||
* media can have a variable bitrate so the duration may be unknown.
|
||||
* @param elapsedSinceLastFeedMs The time since the {@link AudioTrack} was last fed data.
|
||||
*/
|
||||
void onAudioTrackUnderrun(int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The type of a message that can be passed to an instance of this class via
|
||||
* {@link ExoPlayer#sendMessage} or {@link ExoPlayer#blockingSendMessage}. The message object
|
||||
* should be a {@link Float} with 0 being silence and 1 being unity gain.
|
||||
*/
|
||||
public static final int MSG_SET_VOLUME = 1;
|
||||
|
||||
/**
|
||||
* The type of a message that can be passed to an instance of this class via
|
||||
* {@link ExoPlayer#sendMessage} or {@link ExoPlayer#blockingSendMessage}. The message object
|
||||
* should be a {@link android.media.PlaybackParams}, which will be used to configure the
|
||||
* underlying {@link android.media.AudioTrack}. The message object should not be modified by the
|
||||
* caller after it has been passed
|
||||
*/
|
||||
public static final int MSG_SET_PLAYBACK_PARAMS = 2;
|
||||
|
||||
private final EventListener eventListener;
|
||||
private final AudioTrack audioTrack;
|
||||
|
||||
private boolean passthroughEnabled;
|
||||
private android.media.MediaFormat passthroughMediaFormat;
|
||||
private int pcmEncoding;
|
||||
private int audioSessionId;
|
||||
private long currentPositionUs;
|
||||
private boolean allowPositionDiscontinuity;
|
||||
|
||||
private boolean audioTrackHasData;
|
||||
private long lastFeedElapsedRealtimeMs;
|
||||
|
||||
/**
|
||||
* @param source The upstream source from which the renderer obtains samples.
|
||||
* @param mediaCodecSelector A decoder selector.
|
||||
*/
|
||||
public MediaCodecAudioTrackRenderer(SampleSource source, MediaCodecSelector mediaCodecSelector) {
|
||||
this(source, mediaCodecSelector, null, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param source The upstream source from which the renderer obtains samples.
|
||||
* @param mediaCodecSelector A decoder selector.
|
||||
* @param drmSessionManager For use with encrypted content. May be null if support for encrypted
|
||||
* content is not required.
|
||||
* @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
|
||||
* For example a media file may start with a short clear region so as to allow playback to
|
||||
* begin in parallel with key acquisition. This parameter specifies whether the renderer is
|
||||
* permitted to play clear regions of encrypted media files before {@code drmSessionManager}
|
||||
* has obtained the keys necessary to decrypt encrypted regions of the media.
|
||||
*/
|
||||
public MediaCodecAudioTrackRenderer(SampleSource source, MediaCodecSelector mediaCodecSelector,
|
||||
DrmSessionManager drmSessionManager, boolean playClearSamplesWithoutKeys) {
|
||||
this(source, mediaCodecSelector, drmSessionManager, playClearSamplesWithoutKeys, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param source The upstream source from which the renderer obtains samples.
|
||||
* @param mediaCodecSelector A decoder selector.
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
*/
|
||||
public MediaCodecAudioTrackRenderer(SampleSource source, MediaCodecSelector mediaCodecSelector,
|
||||
Handler eventHandler, EventListener eventListener) {
|
||||
this(source, mediaCodecSelector, null, true, eventHandler, eventListener);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param source The upstream source from which the renderer obtains samples.
|
||||
* @param mediaCodecSelector A decoder selector.
|
||||
* @param drmSessionManager For use with encrypted content. May be null if support for encrypted
|
||||
* content is not required.
|
||||
* @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
|
||||
* For example a media file may start with a short clear region so as to allow playback to
|
||||
* begin in parallel with key acquisition. This parameter specifies whether the renderer is
|
||||
* permitted to play clear regions of encrypted media files before {@code drmSessionManager}
|
||||
* has obtained the keys necessary to decrypt encrypted regions of the media.
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
*/
|
||||
public MediaCodecAudioTrackRenderer(SampleSource source, MediaCodecSelector mediaCodecSelector,
|
||||
DrmSessionManager drmSessionManager, boolean playClearSamplesWithoutKeys,
|
||||
Handler eventHandler, EventListener eventListener) {
|
||||
this(source, mediaCodecSelector, drmSessionManager, playClearSamplesWithoutKeys, eventHandler,
|
||||
eventListener, null, AudioManager.STREAM_MUSIC);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param source The upstream source from which the renderer obtains samples.
|
||||
* @param mediaCodecSelector A decoder selector.
|
||||
* @param drmSessionManager For use with encrypted content. May be null if support for encrypted
|
||||
* content is not required.
|
||||
* @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
|
||||
* For example a media file may start with a short clear region so as to allow playback to
|
||||
* begin in parallel with key acquisition. This parameter specifies whether the renderer is
|
||||
* permitted to play clear regions of encrypted media files before {@code drmSessionManager}
|
||||
* has obtained the keys necessary to decrypt encrypted regions of the media.
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
* @param audioCapabilities The audio capabilities for playback on this device. May be null if the
|
||||
* default capabilities (no encoded audio passthrough support) should be assumed.
|
||||
* @param streamType The type of audio stream for the {@link AudioTrack}.
|
||||
*/
|
||||
public MediaCodecAudioTrackRenderer(SampleSource source, MediaCodecSelector mediaCodecSelector,
|
||||
DrmSessionManager drmSessionManager, boolean playClearSamplesWithoutKeys,
|
||||
Handler eventHandler, EventListener eventListener, AudioCapabilities audioCapabilities,
|
||||
int streamType) {
|
||||
this (new SampleSource[] {source}, mediaCodecSelector, drmSessionManager,
|
||||
playClearSamplesWithoutKeys, eventHandler, eventListener, audioCapabilities, streamType);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param sources The upstream sources from which the renderer obtains samples.
|
||||
* @param mediaCodecSelector A decoder selector.
|
||||
* @param drmSessionManager For use with encrypted content. May be null if support for encrypted
|
||||
* content is not required.
|
||||
* @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
|
||||
* For example a media file may start with a short clear region so as to allow playback to
|
||||
* begin in parallel with key acquisition. This parameter specifies whether the renderer is
|
||||
* permitted to play clear regions of encrypted media files before {@code drmSessionManager}
|
||||
* has obtained the keys necessary to decrypt encrypted regions of the media.
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
* @param audioCapabilities The audio capabilities for playback on this device. May be null if the
|
||||
* default capabilities (no encoded audio passthrough support) should be assumed.
|
||||
* @param streamType The type of audio stream for the {@link AudioTrack}.
|
||||
*/
|
||||
public MediaCodecAudioTrackRenderer(SampleSource[] sources, MediaCodecSelector mediaCodecSelector,
|
||||
DrmSessionManager drmSessionManager, boolean playClearSamplesWithoutKeys,
|
||||
Handler eventHandler, EventListener eventListener, AudioCapabilities audioCapabilities,
|
||||
int streamType) {
|
||||
super(sources, mediaCodecSelector, drmSessionManager, playClearSamplesWithoutKeys, eventHandler,
|
||||
eventListener);
|
||||
this.eventListener = eventListener;
|
||||
this.audioSessionId = AudioTrack.SESSION_ID_NOT_SET;
|
||||
this.audioTrack = new AudioTrack(audioCapabilities, streamType);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean handlesTrack(MediaCodecSelector mediaCodecSelector, MediaFormat mediaFormat)
|
||||
throws DecoderQueryException {
|
||||
String mimeType = mediaFormat.mimeType;
|
||||
return MimeTypes.isAudio(mimeType) && (MimeTypes.AUDIO_UNKNOWN.equals(mimeType)
|
||||
|| (allowPassthrough(mimeType) && mediaCodecSelector.getPassthroughDecoderInfo() != null)
|
||||
|| mediaCodecSelector.getDecoderInfo(mimeType, false) != null);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DecoderInfo getDecoderInfo(MediaCodecSelector mediaCodecSelector, String mimeType,
|
||||
boolean requiresSecureDecoder) throws DecoderQueryException {
|
||||
if (allowPassthrough(mimeType)) {
|
||||
DecoderInfo passthroughDecoderInfo = mediaCodecSelector.getPassthroughDecoderInfo();
|
||||
if (passthroughDecoderInfo != null) {
|
||||
passthroughEnabled = true;
|
||||
return passthroughDecoderInfo;
|
||||
}
|
||||
}
|
||||
passthroughEnabled = false;
|
||||
return super.getDecoderInfo(mediaCodecSelector, mimeType, requiresSecureDecoder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether encoded audio passthrough should be used for playing back the input format.
|
||||
* This implementation returns true if the {@link AudioTrack}'s audio capabilities indicate that
|
||||
* passthrough is supported.
|
||||
*
|
||||
* @param mimeType The type of input media.
|
||||
* @return True if passthrough playback should be used. False otherwise.
|
||||
*/
|
||||
protected boolean allowPassthrough(String mimeType) {
|
||||
return audioTrack.isPassthroughSupported(mimeType);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configureCodec(MediaCodec codec, boolean codecIsAdaptive,
|
||||
android.media.MediaFormat format, android.media.MediaCrypto crypto) {
|
||||
String mimeType = format.getString(android.media.MediaFormat.KEY_MIME);
|
||||
if (passthroughEnabled) {
|
||||
// Override the MIME type used to configure the codec if we are using a passthrough decoder.
|
||||
format.setString(android.media.MediaFormat.KEY_MIME, MimeTypes.AUDIO_RAW);
|
||||
codec.configure(format, null, crypto, 0);
|
||||
format.setString(android.media.MediaFormat.KEY_MIME, mimeType);
|
||||
passthroughMediaFormat = format;
|
||||
} else {
|
||||
codec.configure(format, null, crypto, 0);
|
||||
passthroughMediaFormat = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MediaClock getMediaClock() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onInputFormatChanged(MediaFormatHolder holder) throws ExoPlaybackException {
|
||||
super.onInputFormatChanged(holder);
|
||||
// If the input format is anything other than PCM then we assume that the audio decoder will
|
||||
// output 16-bit PCM.
|
||||
pcmEncoding = MimeTypes.AUDIO_RAW.equals(holder.format.mimeType) ? holder.format.pcmEncoding
|
||||
: C.ENCODING_PCM_16BIT;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onOutputFormatChanged(MediaCodec codec, android.media.MediaFormat outputFormat) {
|
||||
boolean passthrough = passthroughMediaFormat != null;
|
||||
String mimeType = passthrough
|
||||
? passthroughMediaFormat.getString(android.media.MediaFormat.KEY_MIME)
|
||||
: MimeTypes.AUDIO_RAW;
|
||||
android.media.MediaFormat format = passthrough ? passthroughMediaFormat : outputFormat;
|
||||
int channelCount = format.getInteger(android.media.MediaFormat.KEY_CHANNEL_COUNT);
|
||||
int sampleRate = format.getInteger(android.media.MediaFormat.KEY_SAMPLE_RATE);
|
||||
audioTrack.configure(mimeType, channelCount, sampleRate, pcmEncoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoked when the audio session id becomes known. Once the id is known it will not change
|
||||
* (and hence this method will not be invoked again) unless the renderer is disabled and then
|
||||
* subsequently re-enabled.
|
||||
* <p>
|
||||
* The default implementation is a no-op. One reason for overriding this method would be to
|
||||
* instantiate and enable a {@link Virtualizer} in order to spatialize the audio channels. For
|
||||
* this use case, any {@link Virtualizer} instances should be released in {@link #onDisabled()}
|
||||
* (if not before).
|
||||
*
|
||||
* @param audioSessionId The audio session id.
|
||||
*/
|
||||
protected void onAudioSessionId(int audioSessionId) {
|
||||
// Do nothing.
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStarted() {
|
||||
super.onStarted();
|
||||
audioTrack.play();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStopped() {
|
||||
audioTrack.pause();
|
||||
super.onStopped();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isEnded() {
|
||||
return super.isEnded() && !audioTrack.hasPendingData();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isReady() {
|
||||
return audioTrack.hasPendingData() || super.isReady();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getPositionUs() {
|
||||
long newCurrentPositionUs = audioTrack.getCurrentPositionUs(isEnded());
|
||||
if (newCurrentPositionUs != AudioTrack.CURRENT_POSITION_NOT_SET) {
|
||||
currentPositionUs = allowPositionDiscontinuity ? newCurrentPositionUs
|
||||
: Math.max(currentPositionUs, newCurrentPositionUs);
|
||||
allowPositionDiscontinuity = false;
|
||||
}
|
||||
return currentPositionUs;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDisabled() throws ExoPlaybackException {
|
||||
audioSessionId = AudioTrack.SESSION_ID_NOT_SET;
|
||||
try {
|
||||
audioTrack.release();
|
||||
} finally {
|
||||
super.onDisabled();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDiscontinuity(long positionUs) throws ExoPlaybackException {
|
||||
super.onDiscontinuity(positionUs);
|
||||
audioTrack.reset();
|
||||
currentPositionUs = positionUs;
|
||||
allowPositionDiscontinuity = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean processOutputBuffer(long positionUs, long elapsedRealtimeUs, MediaCodec codec,
|
||||
ByteBuffer buffer, MediaCodec.BufferInfo bufferInfo, int bufferIndex, boolean shouldSkip)
|
||||
throws ExoPlaybackException {
|
||||
if (passthroughEnabled && (bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
|
||||
// Discard output buffers from the passthrough (raw) decoder containing codec specific data.
|
||||
codec.releaseOutputBuffer(bufferIndex, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (shouldSkip) {
|
||||
codec.releaseOutputBuffer(bufferIndex, false);
|
||||
codecCounters.skippedOutputBufferCount++;
|
||||
audioTrack.handleDiscontinuity();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!audioTrack.isInitialized()) {
|
||||
// Initialize the AudioTrack now.
|
||||
try {
|
||||
if (audioSessionId != AudioTrack.SESSION_ID_NOT_SET) {
|
||||
audioTrack.initialize(audioSessionId);
|
||||
} else {
|
||||
audioSessionId = audioTrack.initialize();
|
||||
onAudioSessionId(audioSessionId);
|
||||
}
|
||||
audioTrackHasData = false;
|
||||
} catch (AudioTrack.InitializationException e) {
|
||||
notifyAudioTrackInitializationError(e);
|
||||
throw new ExoPlaybackException(e);
|
||||
}
|
||||
if (getState() == TrackRenderer.STATE_STARTED) {
|
||||
audioTrack.play();
|
||||
}
|
||||
} else {
|
||||
// Check for AudioTrack underrun.
|
||||
boolean audioTrackHadData = audioTrackHasData;
|
||||
audioTrackHasData = audioTrack.hasPendingData();
|
||||
if (audioTrackHadData && !audioTrackHasData && getState() == TrackRenderer.STATE_STARTED) {
|
||||
long elapsedSinceLastFeedMs = SystemClock.elapsedRealtime() - lastFeedElapsedRealtimeMs;
|
||||
long bufferSizeUs = audioTrack.getBufferSizeUs();
|
||||
long bufferSizeMs = bufferSizeUs == C.UNKNOWN_TIME_US ? -1 : bufferSizeUs / 1000;
|
||||
notifyAudioTrackUnderrun(audioTrack.getBufferSize(), bufferSizeMs, elapsedSinceLastFeedMs);
|
||||
}
|
||||
}
|
||||
|
||||
int handleBufferResult;
|
||||
try {
|
||||
handleBufferResult = audioTrack.handleBuffer(
|
||||
buffer, bufferInfo.offset, bufferInfo.size, bufferInfo.presentationTimeUs);
|
||||
lastFeedElapsedRealtimeMs = SystemClock.elapsedRealtime();
|
||||
} catch (AudioTrack.WriteException e) {
|
||||
notifyAudioTrackWriteError(e);
|
||||
throw new ExoPlaybackException(e);
|
||||
}
|
||||
|
||||
// If we are out of sync, allow currentPositionUs to jump backwards.
|
||||
if ((handleBufferResult & AudioTrack.RESULT_POSITION_DISCONTINUITY) != 0) {
|
||||
handleAudioTrackDiscontinuity();
|
||||
allowPositionDiscontinuity = true;
|
||||
}
|
||||
|
||||
// Release the buffer if it was consumed.
|
||||
if ((handleBufferResult & AudioTrack.RESULT_BUFFER_CONSUMED) != 0) {
|
||||
codec.releaseOutputBuffer(bufferIndex, false);
|
||||
codecCounters.renderedOutputBufferCount++;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onOutputStreamEnded() {
|
||||
audioTrack.handleEndOfStream();
|
||||
}
|
||||
|
||||
protected void handleAudioTrackDiscontinuity() {
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessage(int messageType, Object message) throws ExoPlaybackException {
|
||||
switch (messageType) {
|
||||
case MSG_SET_VOLUME:
|
||||
audioTrack.setVolume((Float) message);
|
||||
break;
|
||||
case MSG_SET_PLAYBACK_PARAMS:
|
||||
audioTrack.setPlaybackParams((PlaybackParams) message);
|
||||
break;
|
||||
default:
|
||||
super.handleMessage(messageType, message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyAudioTrackInitializationError(final AudioTrack.InitializationException e) {
|
||||
if (eventHandler != null && eventListener != null) {
|
||||
eventHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
eventListener.onAudioTrackInitializationError(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyAudioTrackWriteError(final AudioTrack.WriteException e) {
|
||||
if (eventHandler != null && eventListener != null) {
|
||||
eventHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
eventListener.onAudioTrackWriteError(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyAudioTrackUnderrun(final int bufferSize, final long bufferSizeMs,
|
||||
final long elapsedSinceLastFeedMs) {
|
||||
if (eventHandler != null && eventListener != null) {
|
||||
eventHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
eventListener.onAudioTrackUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.MediaCodecUtil.DecoderQueryException;
|
||||
|
||||
import android.media.MediaCodec;
|
||||
|
||||
/**
|
||||
* Selector of {@link MediaCodec} instances.
|
||||
*/
|
||||
public interface MediaCodecSelector {
|
||||
|
||||
/**
|
||||
* Default implementation of {@link MediaCodecSelector}.
|
||||
*/
|
||||
MediaCodecSelector DEFAULT = new MediaCodecSelector() {
|
||||
|
||||
@Override
|
||||
public DecoderInfo getDecoderInfo(String mimeType, boolean requiresSecureDecoder)
|
||||
throws DecoderQueryException {
|
||||
return MediaCodecUtil.getDecoderInfo(mimeType, requiresSecureDecoder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DecoderInfo getPassthroughDecoderInfo() throws DecoderQueryException {
|
||||
return MediaCodecUtil.getPassthroughDecoderInfo();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Selects a decoder to instantiate for a given mime type.
|
||||
*
|
||||
* @param mimeType The mime type for which a decoder is required.
|
||||
* @param requiresSecureDecoder Whether a secure decoder is required.
|
||||
* @return A {@link DecoderInfo} describing the decoder, or null if no suitable decoder exists.
|
||||
* @throws DecoderQueryException Thrown if there was an error querying decoders.
|
||||
*/
|
||||
DecoderInfo getDecoderInfo(String mimeType, boolean requiresSecureDecoder)
|
||||
throws DecoderQueryException;
|
||||
|
||||
/**
|
||||
* Selects a decoder to instantiate for audio passthrough.
|
||||
*
|
||||
* @return A {@link DecoderInfo} describing the decoder, or null if no suitable decoder exists.
|
||||
* @throws DecoderQueryException Thrown if there was an error querying decoders.
|
||||
*/
|
||||
DecoderInfo getPassthroughDecoderInfo() throws DecoderQueryException;
|
||||
|
||||
}
|
||||
-1114
File diff suppressed because it is too large
Load Diff
@@ -1,501 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.util.Assertions;
|
||||
import com.b44t.messenger.exoplayer.util.MimeTypes;
|
||||
import com.b44t.messenger.exoplayer.util.Util;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.media.MediaCodecInfo;
|
||||
import android.media.MediaCodecInfo.CodecCapabilities;
|
||||
import android.media.MediaCodecInfo.CodecProfileLevel;
|
||||
import android.media.MediaCodecList;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A utility class for querying the available codecs.
|
||||
*/
|
||||
@TargetApi(16)
|
||||
public final class MediaCodecUtil {
|
||||
|
||||
/**
|
||||
* Thrown when an error occurs querying the device for its underlying media capabilities.
|
||||
* <p>
|
||||
* Such failures are not expected in normal operation and are normally temporary (e.g. if the
|
||||
* mediaserver process has crashed and is yet to restart).
|
||||
*/
|
||||
public static class DecoderQueryException extends IOException {
|
||||
|
||||
private DecoderQueryException(Throwable cause) {
|
||||
super("Failed to query underlying media codecs", cause);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final String TAG = "MediaCodecUtil";
|
||||
private static final DecoderInfo PASSTHROUGH_DECODER_INFO =
|
||||
new DecoderInfo("OMX.google.raw.decoder", null);
|
||||
|
||||
private static final Map<CodecKey, List<DecoderInfo>> decoderInfosCache = new HashMap<>();
|
||||
|
||||
// Lazily initialized.
|
||||
private static int maxH264DecodableFrameSize = -1;
|
||||
|
||||
private MediaCodecUtil() {}
|
||||
|
||||
/**
|
||||
* Optional call to warm the codec cache for a given mime type.
|
||||
* <p>
|
||||
* Calling this method may speed up subsequent calls to {@link #getDecoderInfo(String, boolean)}.
|
||||
*
|
||||
* @param mimeType The mime type.
|
||||
* @param secure Whether the decoder is required to support secure decryption. Always pass false
|
||||
* unless secure decryption really is required.
|
||||
*/
|
||||
public static void warmCodec(String mimeType, boolean secure) {
|
||||
try {
|
||||
getDecoderInfos(mimeType, secure);
|
||||
} catch (DecoderQueryException e) {
|
||||
// Codec warming is best effort, so we can swallow the exception.
|
||||
Log.e(TAG, "Codec warming failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets information about a decoder suitable for audio passthrough.
|
||||
**
|
||||
* @return A {@link DecoderInfo} describing the decoder, or null if no suitable decoder exists.
|
||||
*/
|
||||
public static DecoderInfo getPassthroughDecoderInfo() {
|
||||
// TODO: Return null if the raw decoder doesn't exist.
|
||||
return PASSTHROUGH_DECODER_INFO;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get information about the preferred decoder for a given mime type.
|
||||
*
|
||||
* @param mimeType The mime type.
|
||||
* @param secure Whether the decoder is required to support secure decryption. Always pass false
|
||||
* unless secure decryption really is required.
|
||||
* @return A {@link DecoderInfo} describing the decoder, or null if no suitable decoder exists.
|
||||
*/
|
||||
public static DecoderInfo getDecoderInfo(String mimeType, boolean secure)
|
||||
throws DecoderQueryException {
|
||||
List<DecoderInfo> decoderInfos = getDecoderInfos(mimeType, secure);
|
||||
return decoderInfos.isEmpty() ? null : decoderInfos.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all @{link DecoderInfo}s for a given mime type, in the order given by
|
||||
* {@link MediaCodecList}.
|
||||
*
|
||||
* @param mimeType The mime type.
|
||||
* @param secure Whether the decoders are required to support secure decryption. Always pass false
|
||||
* unless secure decryption really is required.
|
||||
* @return A list of all @{link DecoderInfo}s for the given mime type. May be empty if no suitable
|
||||
* decoders exist.
|
||||
*/
|
||||
public static synchronized List<DecoderInfo> getDecoderInfos(String mimeType, boolean secure)
|
||||
throws DecoderQueryException {
|
||||
CodecKey key = new CodecKey(mimeType, secure);
|
||||
List<DecoderInfo> decoderInfos = decoderInfosCache.get(key);
|
||||
if (decoderInfos != null) {
|
||||
return decoderInfos;
|
||||
}
|
||||
MediaCodecListCompat mediaCodecList = Util.SDK_INT >= 21
|
||||
? new MediaCodecListCompatV21(secure) : new MediaCodecListCompatV16();
|
||||
decoderInfos = getDecoderInfosInternal(key, mediaCodecList);
|
||||
if (secure && decoderInfos.isEmpty() && 21 <= Util.SDK_INT && Util.SDK_INT <= 23) {
|
||||
// Some devices don't list secure decoders on API level 21 [Internal: b/18678462]. Try the
|
||||
// legacy path. We also try this path on API levels 22 and 23 as a defensive measure.
|
||||
mediaCodecList = new MediaCodecListCompatV16();
|
||||
decoderInfos = getDecoderInfosInternal(key, mediaCodecList);
|
||||
if (!decoderInfos.isEmpty()) {
|
||||
Log.w(TAG, "MediaCodecList API didn't list secure decoder for: " + mimeType
|
||||
+ ". Assuming: " + decoderInfos.get(0).name);
|
||||
}
|
||||
}
|
||||
decoderInfos = Collections.unmodifiableList(decoderInfos);
|
||||
decoderInfosCache.put(key, decoderInfos);
|
||||
return decoderInfos;
|
||||
}
|
||||
|
||||
private static List<DecoderInfo> getDecoderInfosInternal(
|
||||
CodecKey key, MediaCodecListCompat mediaCodecList) throws DecoderQueryException {
|
||||
try {
|
||||
List<DecoderInfo> decoderInfos = new ArrayList<>();
|
||||
String mimeType = key.mimeType;
|
||||
int numberOfCodecs = mediaCodecList.getCodecCount();
|
||||
boolean secureDecodersExplicit = mediaCodecList.secureDecodersExplicit();
|
||||
// Note: MediaCodecList is sorted by the framework such that the best decoders come first.
|
||||
for (int i = 0; i < numberOfCodecs; i++) {
|
||||
MediaCodecInfo codecInfo = mediaCodecList.getCodecInfoAt(i);
|
||||
String codecName = codecInfo.getName();
|
||||
if (isCodecUsableDecoder(codecInfo, codecName, secureDecodersExplicit)) {
|
||||
for (String supportedType : codecInfo.getSupportedTypes()) {
|
||||
if (supportedType.equalsIgnoreCase(mimeType)) {
|
||||
try {
|
||||
CodecCapabilities capabilities = codecInfo.getCapabilitiesForType(supportedType);
|
||||
boolean secure = mediaCodecList.isSecurePlaybackSupported(mimeType, capabilities);
|
||||
if ((secureDecodersExplicit && key.secure == secure)
|
||||
|| (!secureDecodersExplicit && !key.secure)) {
|
||||
decoderInfos.add(new DecoderInfo(codecName, capabilities));
|
||||
} else if (!secureDecodersExplicit && secure) {
|
||||
decoderInfos.add(new DecoderInfo(codecName + ".secure", capabilities));
|
||||
// It only makes sense to have one synthesized secure decoder, return immediately.
|
||||
return decoderInfos;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (Util.SDK_INT <= 23 && !decoderInfos.isEmpty()) {
|
||||
// Suppress error querying secondary codec capabilities up to API level 23.
|
||||
Log.e(TAG, "Skipping codec " + codecName + " (failed to query capabilities)");
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return decoderInfos;
|
||||
} catch (Exception e) {
|
||||
// If the underlying mediaserver is in a bad state, we may catch an IllegalStateException
|
||||
// or an IllegalArgumentException here.
|
||||
throw new DecoderQueryException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the specified codec is usable for decoding on the current device.
|
||||
*/
|
||||
private static boolean isCodecUsableDecoder(MediaCodecInfo info, String name,
|
||||
boolean secureDecodersExplicit) {
|
||||
if (info.isEncoder() || (!secureDecodersExplicit && name.endsWith(".secure"))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Work around broken audio decoders.
|
||||
if (Util.SDK_INT < 21
|
||||
&& ("CIPAACDecoder".equals(name))
|
||||
|| "CIPMP3Decoder".equals(name)
|
||||
|| "CIPVorbisDecoder".equals(name)
|
||||
|| "AACDecoder".equals(name)
|
||||
|| "MP3Decoder".equals(name)) {
|
||||
return false;
|
||||
}
|
||||
// Work around https://github.com/google/ExoPlayer/issues/398
|
||||
if (Util.SDK_INT < 18 && "OMX.SEC.MP3.Decoder".equals(name)) {
|
||||
return false;
|
||||
}
|
||||
// Work around https://github.com/google/ExoPlayer/issues/1528
|
||||
if (Util.SDK_INT < 18 && "OMX.MTK.AUDIO.DECODER.AAC".equals(name)
|
||||
&& "a70".equals(Util.DEVICE)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Work around an issue where creating a particular MP3 decoder on some devices on platform API
|
||||
// version 16 crashes mediaserver.
|
||||
if (Util.SDK_INT == 16
|
||||
&& "OMX.qcom.audio.decoder.mp3".equals(name)
|
||||
&& ("dlxu".equals(Util.DEVICE) // HTC Butterfly
|
||||
|| "protou".equals(Util.DEVICE) // HTC Desire X
|
||||
|| "C6602".equals(Util.DEVICE) // Sony Xperia Z
|
||||
|| "C6603".equals(Util.DEVICE)
|
||||
|| "C6606".equals(Util.DEVICE)
|
||||
|| "C6616".equals(Util.DEVICE)
|
||||
|| "L36h".equals(Util.DEVICE)
|
||||
|| "SO-02E".equals(Util.DEVICE))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Work around an issue where large timestamps are not propagated correctly.
|
||||
if (Util.SDK_INT == 16
|
||||
&& "OMX.qcom.audio.decoder.aac".equals(name)
|
||||
&& ("C1504".equals(Util.DEVICE) // Sony Xperia E
|
||||
|| "C1505".equals(Util.DEVICE)
|
||||
|| "C1604".equals(Util.DEVICE) // Sony Xperia E dual
|
||||
|| "C1605".equals(Util.DEVICE))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Work around an issue where the VP8 decoder on Samsung Galaxy S3/S4 Mini does not render
|
||||
// video.
|
||||
if (Util.SDK_INT <= 19 && Util.DEVICE != null
|
||||
&& (Util.DEVICE.startsWith("d2") || Util.DEVICE.startsWith("serrano"))
|
||||
&& "samsung".equals(Util.MANUFACTURER) && name.equals("OMX.SEC.vp8.dec")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether the device advertises it can decode video of a given type at a specified width
|
||||
* and height.
|
||||
* <p>
|
||||
* Must not be called if the device SDK version is less than 21.
|
||||
*
|
||||
* @param mimeType The mime type.
|
||||
* @param secure Whether the decoder is required to support secure decryption. Always pass false
|
||||
* unless secure decryption really is required.
|
||||
* @param width Width in pixels.
|
||||
* @param height Height in pixels.
|
||||
* @return Whether the decoder advertises support of the given size.
|
||||
*/
|
||||
@TargetApi(21)
|
||||
public static boolean isSizeSupportedV21(String mimeType, boolean secure, int width,
|
||||
int height) throws DecoderQueryException {
|
||||
Assertions.checkState(Util.SDK_INT >= 21);
|
||||
MediaCodecInfo.VideoCapabilities videoCapabilities = getVideoCapabilitiesV21(mimeType, secure);
|
||||
return videoCapabilities != null && videoCapabilities.isSizeSupported(width, height);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether the device advertises it can decode video of a given type at a specified
|
||||
* width, height, and frame rate.
|
||||
* <p>
|
||||
* Must not be called if the device SDK version is less than 21.
|
||||
*
|
||||
* @param mimeType The mime type.
|
||||
* @param secure Whether the decoder is required to support secure decryption. Always pass false
|
||||
* unless secure decryption really is required.
|
||||
* @param width Width in pixels.
|
||||
* @param height Height in pixels.
|
||||
* @param frameRate Frame rate in frames per second.
|
||||
* @return Whether the decoder advertises support of the given size and frame rate.
|
||||
*/
|
||||
@TargetApi(21)
|
||||
public static boolean isSizeAndRateSupportedV21(String mimeType, boolean secure,
|
||||
int width, int height, double frameRate) throws DecoderQueryException {
|
||||
Assertions.checkState(Util.SDK_INT >= 21);
|
||||
MediaCodecInfo.VideoCapabilities videoCapabilities = getVideoCapabilitiesV21(mimeType, secure);
|
||||
return videoCapabilities != null
|
||||
&& videoCapabilities.areSizeAndRateSupported(width, height, frameRate);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param profile An AVC profile constant from {@link CodecProfileLevel}.
|
||||
* @param level An AVC profile level from {@link CodecProfileLevel}.
|
||||
* @return Whether the specified profile is supported at the specified level.
|
||||
* @deprecated Prefer {@link #getDecoderInfos(String, boolean)} for new code.
|
||||
*/
|
||||
@Deprecated
|
||||
public static boolean isH264ProfileSupported(int profile, int level)
|
||||
throws DecoderQueryException {
|
||||
DecoderInfo decoderInfo = getDecoderInfo(MimeTypes.VIDEO_H264, false);
|
||||
if (decoderInfo == null) {
|
||||
return false;
|
||||
}
|
||||
for (CodecProfileLevel profileLevel : decoderInfo.capabilities.profileLevels) {
|
||||
if (profileLevel.profile == profile && profileLevel.level >= level) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the maximum frame size for an H264 stream that can be decoded on the device.
|
||||
*/
|
||||
public static int maxH264DecodableFrameSize() throws DecoderQueryException {
|
||||
if (maxH264DecodableFrameSize == -1) {
|
||||
int result = 0;
|
||||
DecoderInfo decoderInfo = getDecoderInfo(MimeTypes.VIDEO_H264, false);
|
||||
if (decoderInfo != null) {
|
||||
for (CodecProfileLevel profileLevel : decoderInfo.capabilities.profileLevels) {
|
||||
result = Math.max(avcLevelToMaxFrameSize(profileLevel.level), result);
|
||||
}
|
||||
// We assume support for at least 360p.
|
||||
result = Math.max(result, 480 * 360);
|
||||
}
|
||||
maxH264DecodableFrameSize = result;
|
||||
}
|
||||
return maxH264DecodableFrameSize;
|
||||
}
|
||||
|
||||
@TargetApi(21)
|
||||
private static MediaCodecInfo.VideoCapabilities getVideoCapabilitiesV21(String mimeType,
|
||||
boolean secure) throws DecoderQueryException {
|
||||
DecoderInfo decoderInfo = getDecoderInfo(mimeType, secure);
|
||||
return decoderInfo == null ? null : decoderInfo.capabilities.getVideoCapabilities();
|
||||
}
|
||||
|
||||
/**
|
||||
* Conversion values taken from ISO 14496-10 Table A-1.
|
||||
*
|
||||
* @param avcLevel one of CodecProfileLevel.AVCLevel* constants.
|
||||
* @return maximum frame size that can be decoded by a decoder with the specified avc level
|
||||
* (or {@code -1} if the level is not recognized)
|
||||
*/
|
||||
private static int avcLevelToMaxFrameSize(int avcLevel) {
|
||||
switch (avcLevel) {
|
||||
case CodecProfileLevel.AVCLevel1: return 99 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel1b: return 99 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel12: return 396 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel13: return 396 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel2: return 396 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel21: return 792 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel22: return 1620 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel3: return 1620 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel31: return 3600 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel32: return 5120 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel4: return 8192 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel41: return 8192 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel42: return 8704 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel5: return 22080 * 16 * 16;
|
||||
case CodecProfileLevel.AVCLevel51: return 36864 * 16 * 16;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private interface MediaCodecListCompat {
|
||||
|
||||
/**
|
||||
* The number of codecs in the list.
|
||||
*/
|
||||
int getCodecCount();
|
||||
|
||||
/**
|
||||
* The info at the specified index in the list.
|
||||
*
|
||||
* @param index The index.
|
||||
*/
|
||||
MediaCodecInfo getCodecInfoAt(int index);
|
||||
|
||||
/**
|
||||
* @return Returns whether secure decoders are explicitly listed, if present.
|
||||
*/
|
||||
boolean secureDecodersExplicit();
|
||||
|
||||
/**
|
||||
* Whether secure playback is supported for the given {@link CodecCapabilities}, which should
|
||||
* have been obtained from a {@link MediaCodecInfo} obtained from this list.
|
||||
*/
|
||||
boolean isSecurePlaybackSupported(String mimeType, CodecCapabilities capabilities);
|
||||
|
||||
}
|
||||
|
||||
@TargetApi(21)
|
||||
private static final class MediaCodecListCompatV21 implements MediaCodecListCompat {
|
||||
|
||||
private final int codecKind;
|
||||
|
||||
private MediaCodecInfo[] mediaCodecInfos;
|
||||
|
||||
public MediaCodecListCompatV21(boolean includeSecure) {
|
||||
codecKind = includeSecure ? MediaCodecList.ALL_CODECS : MediaCodecList.REGULAR_CODECS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCodecCount() {
|
||||
ensureMediaCodecInfosInitialized();
|
||||
return mediaCodecInfos.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MediaCodecInfo getCodecInfoAt(int index) {
|
||||
ensureMediaCodecInfosInitialized();
|
||||
return mediaCodecInfos[index];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean secureDecodersExplicit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSecurePlaybackSupported(String mimeType, CodecCapabilities capabilities) {
|
||||
return capabilities.isFeatureSupported(CodecCapabilities.FEATURE_SecurePlayback);
|
||||
}
|
||||
|
||||
private void ensureMediaCodecInfosInitialized() {
|
||||
if (mediaCodecInfos == null) {
|
||||
mediaCodecInfos = new MediaCodecList(codecKind).getCodecInfos();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private static final class MediaCodecListCompatV16 implements MediaCodecListCompat {
|
||||
|
||||
@Override
|
||||
public int getCodecCount() {
|
||||
return MediaCodecList.getCodecCount();
|
||||
}
|
||||
|
||||
@Override
|
||||
public MediaCodecInfo getCodecInfoAt(int index) {
|
||||
return MediaCodecList.getCodecInfoAt(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean secureDecodersExplicit() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSecurePlaybackSupported(String mimeType, CodecCapabilities capabilities) {
|
||||
// Secure decoders weren't explicitly listed prior to API level 21. We assume that a secure
|
||||
// H264 decoder exists.
|
||||
return MimeTypes.VIDEO_H264.equals(mimeType);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final class CodecKey {
|
||||
|
||||
public final String mimeType;
|
||||
public final boolean secure;
|
||||
|
||||
public CodecKey(String mimeType, boolean secure) {
|
||||
this.mimeType = mimeType;
|
||||
this.secure = secure;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((mimeType == null) ? 0 : mimeType.hashCode());
|
||||
result = prime * result + (secure ? 1231 : 1237);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null || obj.getClass() != CodecKey.class) {
|
||||
return false;
|
||||
}
|
||||
CodecKey other = (CodecKey) obj;
|
||||
return TextUtils.equals(mimeType, other.mimeType) && secure == other.secure;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-611
@@ -1,611 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.MediaCodecUtil.DecoderQueryException;
|
||||
import com.b44t.messenger.exoplayer.drm.DrmSessionManager;
|
||||
import com.b44t.messenger.exoplayer.util.MimeTypes;
|
||||
import com.b44t.messenger.exoplayer.util.TraceUtil;
|
||||
import com.b44t.messenger.exoplayer.util.Util;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.media.MediaCodec;
|
||||
import android.media.MediaCrypto;
|
||||
import android.os.Handler;
|
||||
import android.os.SystemClock;
|
||||
import android.view.Surface;
|
||||
import android.view.TextureView;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
/**
|
||||
* Decodes and renders video using {@link MediaCodec}.
|
||||
*/
|
||||
@TargetApi(16)
|
||||
public class MediaCodecVideoTrackRenderer extends MediaCodecTrackRenderer {
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be notified of {@link MediaCodecVideoTrackRenderer}
|
||||
* events.
|
||||
*/
|
||||
public interface EventListener extends MediaCodecTrackRenderer.EventListener {
|
||||
|
||||
/**
|
||||
* Invoked to report the number of frames dropped by the renderer. Dropped frames are reported
|
||||
* whenever the renderer is stopped having dropped frames, and optionally, whenever the count
|
||||
* reaches a specified threshold whilst the renderer is started.
|
||||
*
|
||||
* @param count The number of dropped frames.
|
||||
* @param elapsed The duration in milliseconds over which the frames were dropped. This
|
||||
* duration is timed from when the renderer was started or from when dropped frames were
|
||||
* last reported (whichever was more recent), and not from when the first of the reported
|
||||
* drops occurred.
|
||||
*/
|
||||
void onDroppedFrames(int count, long elapsed);
|
||||
|
||||
/**
|
||||
* Invoked each time there's a change in the size of the video being rendered.
|
||||
*
|
||||
* @param width The video width in pixels.
|
||||
* @param height The video height in pixels.
|
||||
* @param unappliedRotationDegrees For videos that require a rotation, this is the clockwise
|
||||
* rotation in degrees that the application should apply for the video for it to be rendered
|
||||
* in the correct orientation. This value will always be zero on API levels 21 and above,
|
||||
* since the renderer will apply all necessary rotations internally. On earlier API levels
|
||||
* this is not possible. Applications that use {@link TextureView} can apply the rotation by
|
||||
* calling {@link TextureView#setTransform}. Applications that do not expect to encounter
|
||||
* rotated videos can safely ignore this parameter.
|
||||
* @param pixelWidthHeightRatio The width to height ratio of each pixel. For the normal case
|
||||
* of square pixels this will be equal to 1.0. Different values are indicative of anamorphic
|
||||
* content.
|
||||
*/
|
||||
void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees,
|
||||
float pixelWidthHeightRatio);
|
||||
|
||||
/**
|
||||
* Invoked when a frame is rendered to a surface for the first time following that surface
|
||||
* having been set as the target for the renderer.
|
||||
*
|
||||
* @param surface The surface to which a first frame has been rendered.
|
||||
*/
|
||||
void onDrawnToSurface(Surface surface);
|
||||
|
||||
}
|
||||
|
||||
// TODO: Use MediaFormat constants if these get exposed through the API. See
|
||||
// [Internal: b/14127601].
|
||||
private static final String KEY_CROP_LEFT = "crop-left";
|
||||
private static final String KEY_CROP_RIGHT = "crop-right";
|
||||
private static final String KEY_CROP_BOTTOM = "crop-bottom";
|
||||
private static final String KEY_CROP_TOP = "crop-top";
|
||||
|
||||
/**
|
||||
* The type of a message that can be passed to an instance of this class via
|
||||
* {@link ExoPlayer#sendMessage} or {@link ExoPlayer#blockingSendMessage}. The message object
|
||||
* should be the target {@link Surface}, or null.
|
||||
*/
|
||||
public static final int MSG_SET_SURFACE = 1;
|
||||
|
||||
private final VideoFrameReleaseTimeHelper frameReleaseTimeHelper;
|
||||
private final EventListener eventListener;
|
||||
private final long allowedJoiningTimeUs;
|
||||
private final int videoScalingMode;
|
||||
private final int maxDroppedFrameCountToNotify;
|
||||
|
||||
private Surface surface;
|
||||
private boolean reportedDrawnToSurface;
|
||||
private boolean renderedFirstFrame;
|
||||
private long joiningDeadlineUs;
|
||||
private long droppedFrameAccumulationStartTimeMs;
|
||||
private int droppedFrameCount;
|
||||
private int consecutiveDroppedFrameCount;
|
||||
|
||||
private int pendingRotationDegrees;
|
||||
private float pendingPixelWidthHeightRatio;
|
||||
private int currentWidth;
|
||||
private int currentHeight;
|
||||
private int currentUnappliedRotationDegrees;
|
||||
private float currentPixelWidthHeightRatio;
|
||||
private int lastReportedWidth;
|
||||
private int lastReportedHeight;
|
||||
private int lastReportedUnappliedRotationDegrees;
|
||||
private float lastReportedPixelWidthHeightRatio;
|
||||
|
||||
/**
|
||||
* @param context A context.
|
||||
* @param source The upstream source from which the renderer obtains samples.
|
||||
* @param mediaCodecSelector A decoder selector.
|
||||
* @param videoScalingMode The scaling mode to pass to
|
||||
* {@link MediaCodec#setVideoScalingMode(int)}.
|
||||
*/
|
||||
public MediaCodecVideoTrackRenderer(Context context, SampleSource source,
|
||||
MediaCodecSelector mediaCodecSelector, int videoScalingMode) {
|
||||
this(context, source, mediaCodecSelector, videoScalingMode, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param context A context.
|
||||
* @param source The upstream source from which the renderer obtains samples.
|
||||
* @param mediaCodecSelector A decoder selector.
|
||||
* @param videoScalingMode The scaling mode to pass to
|
||||
* {@link MediaCodec#setVideoScalingMode(int)}.
|
||||
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
|
||||
* can attempt to seamlessly join an ongoing playback.
|
||||
*/
|
||||
public MediaCodecVideoTrackRenderer(Context context, SampleSource source,
|
||||
MediaCodecSelector mediaCodecSelector, int videoScalingMode, long allowedJoiningTimeMs) {
|
||||
this(context, source, mediaCodecSelector, videoScalingMode, allowedJoiningTimeMs, null, null,
|
||||
-1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param context A context.
|
||||
* @param source The upstream source from which the renderer obtains samples.
|
||||
* @param mediaCodecSelector A decoder selector.
|
||||
* @param videoScalingMode The scaling mode to pass to
|
||||
* {@link MediaCodec#setVideoScalingMode(int)}.
|
||||
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
|
||||
* can attempt to seamlessly join an ongoing playback.
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
* @param maxDroppedFrameCountToNotify The maximum number of frames that can be dropped between
|
||||
* invocations of {@link EventListener#onDroppedFrames(int, long)}.
|
||||
*/
|
||||
public MediaCodecVideoTrackRenderer(Context context, SampleSource source,
|
||||
MediaCodecSelector mediaCodecSelector, int videoScalingMode, long allowedJoiningTimeMs,
|
||||
Handler eventHandler, EventListener eventListener, int maxDroppedFrameCountToNotify) {
|
||||
this(context, source, mediaCodecSelector, videoScalingMode, allowedJoiningTimeMs, null, false,
|
||||
eventHandler, eventListener, maxDroppedFrameCountToNotify);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param context A context.
|
||||
* @param source The upstream source from which the renderer obtains samples.
|
||||
* @param mediaCodecSelector A decoder selector.
|
||||
* @param videoScalingMode The scaling mode to pass to
|
||||
* {@link MediaCodec#setVideoScalingMode(int)}.
|
||||
* @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
|
||||
* can attempt to seamlessly join an ongoing playback.
|
||||
* @param drmSessionManager For use with encrypted content. May be null if support for encrypted
|
||||
* content is not required.
|
||||
* @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
|
||||
* For example a media file may start with a short clear region so as to allow playback to
|
||||
* begin in parallel with key acquisision. This parameter specifies whether the renderer is
|
||||
* permitted to play clear regions of encrypted media files before {@code drmSessionManager}
|
||||
* has obtained the keys necessary to decrypt encrypted regions of the media.
|
||||
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
|
||||
* null if delivery of events is not required.
|
||||
* @param eventListener A listener of events. May be null if delivery of events is not required.
|
||||
* @param maxDroppedFrameCountToNotify The maximum number of frames that can be dropped between
|
||||
* invocations of {@link EventListener#onDroppedFrames(int, long)}.
|
||||
*/
|
||||
public MediaCodecVideoTrackRenderer(Context context, SampleSource source,
|
||||
MediaCodecSelector mediaCodecSelector, int videoScalingMode, long allowedJoiningTimeMs,
|
||||
DrmSessionManager drmSessionManager, boolean playClearSamplesWithoutKeys,
|
||||
Handler eventHandler, EventListener eventListener, int maxDroppedFrameCountToNotify) {
|
||||
super(source, mediaCodecSelector, drmSessionManager, playClearSamplesWithoutKeys, eventHandler,
|
||||
eventListener);
|
||||
this.frameReleaseTimeHelper = new VideoFrameReleaseTimeHelper(context);
|
||||
this.videoScalingMode = videoScalingMode;
|
||||
this.allowedJoiningTimeUs = allowedJoiningTimeMs * 1000;
|
||||
this.eventListener = eventListener;
|
||||
this.maxDroppedFrameCountToNotify = maxDroppedFrameCountToNotify;
|
||||
joiningDeadlineUs = -1;
|
||||
currentWidth = -1;
|
||||
currentHeight = -1;
|
||||
currentPixelWidthHeightRatio = -1;
|
||||
pendingPixelWidthHeightRatio = -1;
|
||||
lastReportedWidth = -1;
|
||||
lastReportedHeight = -1;
|
||||
lastReportedPixelWidthHeightRatio = -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean handlesTrack(MediaCodecSelector mediaCodecSelector, MediaFormat mediaFormat)
|
||||
throws DecoderQueryException {
|
||||
String mimeType = mediaFormat.mimeType;
|
||||
return MimeTypes.isVideo(mimeType) && (MimeTypes.VIDEO_UNKNOWN.equals(mimeType)
|
||||
|| mediaCodecSelector.getDecoderInfo(mimeType, false) != null);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onEnabled(int track, long positionUs, boolean joining)
|
||||
throws ExoPlaybackException {
|
||||
super.onEnabled(track, positionUs, joining);
|
||||
if (joining && allowedJoiningTimeUs > 0) {
|
||||
joiningDeadlineUs = SystemClock.elapsedRealtime() * 1000L + allowedJoiningTimeUs;
|
||||
}
|
||||
frameReleaseTimeHelper.enable();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDiscontinuity(long positionUs) throws ExoPlaybackException {
|
||||
super.onDiscontinuity(positionUs);
|
||||
renderedFirstFrame = false;
|
||||
consecutiveDroppedFrameCount = 0;
|
||||
joiningDeadlineUs = -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isReady() {
|
||||
if (super.isReady() && (renderedFirstFrame || !codecInitialized()
|
||||
|| getSourceState() == SOURCE_STATE_READY_READ_MAY_FAIL)) {
|
||||
// Ready. If we were joining then we've now joined, so clear the joining deadline.
|
||||
joiningDeadlineUs = -1;
|
||||
return true;
|
||||
} else if (joiningDeadlineUs == -1) {
|
||||
// Not joining.
|
||||
return false;
|
||||
} else if (SystemClock.elapsedRealtime() * 1000 < joiningDeadlineUs) {
|
||||
// Joining and still within the joining deadline.
|
||||
return true;
|
||||
} else {
|
||||
// The joining deadline has been exceeded. Give up and clear the deadline.
|
||||
joiningDeadlineUs = -1;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStarted() {
|
||||
super.onStarted();
|
||||
droppedFrameCount = 0;
|
||||
droppedFrameAccumulationStartTimeMs = SystemClock.elapsedRealtime();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStopped() {
|
||||
joiningDeadlineUs = -1;
|
||||
maybeNotifyDroppedFrameCount();
|
||||
super.onStopped();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDisabled() throws ExoPlaybackException {
|
||||
currentWidth = -1;
|
||||
currentHeight = -1;
|
||||
currentPixelWidthHeightRatio = -1;
|
||||
pendingPixelWidthHeightRatio = -1;
|
||||
lastReportedWidth = -1;
|
||||
lastReportedHeight = -1;
|
||||
lastReportedPixelWidthHeightRatio = -1;
|
||||
frameReleaseTimeHelper.disable();
|
||||
super.onDisabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleMessage(int messageType, Object message) throws ExoPlaybackException {
|
||||
if (messageType == MSG_SET_SURFACE) {
|
||||
setSurface((Surface) message);
|
||||
} else {
|
||||
super.handleMessage(messageType, message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param surface The surface to set.
|
||||
* @throws ExoPlaybackException
|
||||
*/
|
||||
private void setSurface(Surface surface) throws ExoPlaybackException {
|
||||
if (this.surface == surface) {
|
||||
return;
|
||||
}
|
||||
this.surface = surface;
|
||||
this.reportedDrawnToSurface = false;
|
||||
int state = getState();
|
||||
if (state == TrackRenderer.STATE_ENABLED || state == TrackRenderer.STATE_STARTED) {
|
||||
releaseCodec();
|
||||
maybeInitCodec();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldInitCodec() {
|
||||
return super.shouldInitCodec() && surface != null && surface.isValid();
|
||||
}
|
||||
|
||||
// Override configureCodec to provide the surface.
|
||||
@Override
|
||||
protected void configureCodec(MediaCodec codec, boolean codecIsAdaptive,
|
||||
android.media.MediaFormat format, MediaCrypto crypto) {
|
||||
maybeSetMaxInputSize(format, codecIsAdaptive);
|
||||
codec.configure(format, surface, crypto, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onInputFormatChanged(MediaFormatHolder holder) throws ExoPlaybackException {
|
||||
super.onInputFormatChanged(holder);
|
||||
pendingPixelWidthHeightRatio = holder.format.pixelWidthHeightRatio == MediaFormat.NO_VALUE ? 1
|
||||
: holder.format.pixelWidthHeightRatio;
|
||||
pendingRotationDegrees = holder.format.rotationDegrees == MediaFormat.NO_VALUE ? 0
|
||||
: holder.format.rotationDegrees;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return True if the first frame has been rendered (playback has not necessarily begun).
|
||||
*/
|
||||
protected final boolean haveRenderedFirstFrame() {
|
||||
return renderedFirstFrame;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onOutputFormatChanged(MediaCodec codec, android.media.MediaFormat outputFormat) {
|
||||
boolean hasCrop = outputFormat.containsKey(KEY_CROP_RIGHT)
|
||||
&& outputFormat.containsKey(KEY_CROP_LEFT) && outputFormat.containsKey(KEY_CROP_BOTTOM)
|
||||
&& outputFormat.containsKey(KEY_CROP_TOP);
|
||||
currentWidth = hasCrop
|
||||
? outputFormat.getInteger(KEY_CROP_RIGHT) - outputFormat.getInteger(KEY_CROP_LEFT) + 1
|
||||
: outputFormat.getInteger(android.media.MediaFormat.KEY_WIDTH);
|
||||
currentHeight = hasCrop
|
||||
? outputFormat.getInteger(KEY_CROP_BOTTOM) - outputFormat.getInteger(KEY_CROP_TOP) + 1
|
||||
: outputFormat.getInteger(android.media.MediaFormat.KEY_HEIGHT);
|
||||
currentPixelWidthHeightRatio = pendingPixelWidthHeightRatio;
|
||||
if (Util.SDK_INT >= 21) {
|
||||
// On API level 21 and above the decoder applies the rotation when rendering to the surface.
|
||||
// Hence currentUnappliedRotation should always be 0. For 90 and 270 degree rotations, we need
|
||||
// to flip the width, height and pixel aspect ratio to reflect the rotation that was applied.
|
||||
if (pendingRotationDegrees == 90 || pendingRotationDegrees == 270) {
|
||||
int rotatedHeight = currentWidth;
|
||||
currentWidth = currentHeight;
|
||||
currentHeight = rotatedHeight;
|
||||
currentPixelWidthHeightRatio = 1 / currentPixelWidthHeightRatio;
|
||||
}
|
||||
} else {
|
||||
// On API level 20 and below the decoder does not apply the rotation.
|
||||
currentUnappliedRotationDegrees = pendingRotationDegrees;
|
||||
}
|
||||
// Must be applied each time the output format changes.
|
||||
codec.setVideoScalingMode(videoScalingMode);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean canReconfigureCodec(MediaCodec codec, boolean codecIsAdaptive,
|
||||
MediaFormat oldFormat, MediaFormat newFormat) {
|
||||
return newFormat.mimeType.equals(oldFormat.mimeType)
|
||||
&& (codecIsAdaptive
|
||||
|| (oldFormat.width == newFormat.width && oldFormat.height == newFormat.height));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean processOutputBuffer(long positionUs, long elapsedRealtimeUs, MediaCodec codec,
|
||||
ByteBuffer buffer, MediaCodec.BufferInfo bufferInfo, int bufferIndex, boolean shouldSkip) {
|
||||
if (shouldSkip) {
|
||||
skipOutputBuffer(codec, bufferIndex);
|
||||
consecutiveDroppedFrameCount = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!renderedFirstFrame) {
|
||||
if (Util.SDK_INT >= 21) {
|
||||
renderOutputBufferV21(codec, bufferIndex, System.nanoTime());
|
||||
} else {
|
||||
renderOutputBuffer(codec, bufferIndex);
|
||||
}
|
||||
consecutiveDroppedFrameCount = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (getState() != TrackRenderer.STATE_STARTED) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Compute how many microseconds it is until the buffer's presentation time.
|
||||
long elapsedSinceStartOfLoopUs = (SystemClock.elapsedRealtime() * 1000) - elapsedRealtimeUs;
|
||||
long earlyUs = bufferInfo.presentationTimeUs - positionUs - elapsedSinceStartOfLoopUs;
|
||||
|
||||
// Compute the buffer's desired release time in nanoseconds.
|
||||
long systemTimeNs = System.nanoTime();
|
||||
long unadjustedFrameReleaseTimeNs = systemTimeNs + (earlyUs * 1000);
|
||||
|
||||
// Apply a timestamp adjustment, if there is one.
|
||||
long adjustedReleaseTimeNs = frameReleaseTimeHelper.adjustReleaseTime(
|
||||
bufferInfo.presentationTimeUs, unadjustedFrameReleaseTimeNs);
|
||||
earlyUs = (adjustedReleaseTimeNs - systemTimeNs) / 1000;
|
||||
|
||||
if (earlyUs < -30000) {
|
||||
// We're more than 30ms late rendering the frame.
|
||||
dropOutputBuffer(codec, bufferIndex);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Util.SDK_INT >= 21) {
|
||||
// Let the underlying framework time the release.
|
||||
if (earlyUs < 50000) {
|
||||
renderOutputBufferV21(codec, bufferIndex, adjustedReleaseTimeNs);
|
||||
consecutiveDroppedFrameCount = 0;
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
// We need to time the release ourselves.
|
||||
if (earlyUs < 30000) {
|
||||
if (earlyUs > 11000) {
|
||||
// We're a little too early to render the frame. Sleep until the frame can be rendered.
|
||||
// Note: The 11ms threshold was chosen fairly arbitrarily.
|
||||
try {
|
||||
// Subtracting 10000 rather than 11000 ensures the sleep time will be at least 1ms.
|
||||
Thread.sleep((earlyUs - 10000) / 1000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
renderOutputBuffer(codec, bufferIndex);
|
||||
consecutiveDroppedFrameCount = 0;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// We're either not playing, or it's not time to render the frame yet.
|
||||
return false;
|
||||
}
|
||||
|
||||
protected void skipOutputBuffer(MediaCodec codec, int bufferIndex) {
|
||||
TraceUtil.beginSection("skipVideoBuffer");
|
||||
codec.releaseOutputBuffer(bufferIndex, false);
|
||||
TraceUtil.endSection();
|
||||
codecCounters.skippedOutputBufferCount++;
|
||||
}
|
||||
|
||||
protected void dropOutputBuffer(MediaCodec codec, int bufferIndex) {
|
||||
TraceUtil.beginSection("dropVideoBuffer");
|
||||
codec.releaseOutputBuffer(bufferIndex, false);
|
||||
TraceUtil.endSection();
|
||||
codecCounters.droppedOutputBufferCount++;
|
||||
droppedFrameCount++;
|
||||
consecutiveDroppedFrameCount++;
|
||||
codecCounters.maxConsecutiveDroppedOutputBufferCount = Math.max(consecutiveDroppedFrameCount,
|
||||
codecCounters.maxConsecutiveDroppedOutputBufferCount);
|
||||
if (droppedFrameCount == maxDroppedFrameCountToNotify) {
|
||||
maybeNotifyDroppedFrameCount();
|
||||
}
|
||||
}
|
||||
|
||||
protected void renderOutputBuffer(MediaCodec codec, int bufferIndex) {
|
||||
maybeNotifyVideoSizeChanged();
|
||||
TraceUtil.beginSection("releaseOutputBuffer");
|
||||
codec.releaseOutputBuffer(bufferIndex, true);
|
||||
TraceUtil.endSection();
|
||||
codecCounters.renderedOutputBufferCount++;
|
||||
renderedFirstFrame = true;
|
||||
maybeNotifyDrawnToSurface();
|
||||
}
|
||||
|
||||
@TargetApi(21)
|
||||
protected void renderOutputBufferV21(MediaCodec codec, int bufferIndex, long releaseTimeNs) {
|
||||
maybeNotifyVideoSizeChanged();
|
||||
TraceUtil.beginSection("releaseOutputBuffer");
|
||||
codec.releaseOutputBuffer(bufferIndex, releaseTimeNs);
|
||||
TraceUtil.endSection();
|
||||
codecCounters.renderedOutputBufferCount++;
|
||||
renderedFirstFrame = true;
|
||||
maybeNotifyDrawnToSurface();
|
||||
}
|
||||
|
||||
@SuppressLint("InlinedApi")
|
||||
private void maybeSetMaxInputSize(android.media.MediaFormat format, boolean codecIsAdaptive) {
|
||||
if (format.containsKey(android.media.MediaFormat.KEY_MAX_INPUT_SIZE)) {
|
||||
// Already set. The source of the format may know better, so do nothing.
|
||||
return;
|
||||
}
|
||||
int maxHeight = format.getInteger(android.media.MediaFormat.KEY_HEIGHT);
|
||||
if (codecIsAdaptive && format.containsKey(android.media.MediaFormat.KEY_MAX_HEIGHT)) {
|
||||
maxHeight = Math.max(maxHeight, format.getInteger(android.media.MediaFormat.KEY_MAX_HEIGHT));
|
||||
}
|
||||
int maxWidth = format.getInteger(android.media.MediaFormat.KEY_WIDTH);
|
||||
if (codecIsAdaptive && format.containsKey(android.media.MediaFormat.KEY_MAX_WIDTH)) {
|
||||
maxWidth = Math.max(maxHeight, format.getInteger(android.media.MediaFormat.KEY_MAX_WIDTH));
|
||||
}
|
||||
int maxPixels;
|
||||
int minCompressionRatio;
|
||||
switch (format.getString(android.media.MediaFormat.KEY_MIME)) {
|
||||
case MimeTypes.VIDEO_H263:
|
||||
case MimeTypes.VIDEO_MP4V:
|
||||
maxPixels = maxWidth * maxHeight;
|
||||
minCompressionRatio = 2;
|
||||
break;
|
||||
case MimeTypes.VIDEO_H264:
|
||||
if ("BRAVIA 4K 2015".equals(Util.MODEL)) {
|
||||
// The Sony BRAVIA 4k TV has input buffers that are too small for the calculated 4k video
|
||||
// maximum input size, so use the default value.
|
||||
return;
|
||||
}
|
||||
// Round up width/height to an integer number of macroblocks.
|
||||
maxPixels = ((maxWidth + 15) / 16) * ((maxHeight + 15) / 16) * 16 * 16;
|
||||
minCompressionRatio = 2;
|
||||
break;
|
||||
case MimeTypes.VIDEO_VP8:
|
||||
// VPX does not specify a ratio so use the values from the platform's SoftVPX.cpp.
|
||||
maxPixels = maxWidth * maxHeight;
|
||||
minCompressionRatio = 2;
|
||||
break;
|
||||
case MimeTypes.VIDEO_H265:
|
||||
case MimeTypes.VIDEO_VP9:
|
||||
maxPixels = maxWidth * maxHeight;
|
||||
minCompressionRatio = 4;
|
||||
break;
|
||||
default:
|
||||
// Leave the default max input size.
|
||||
return;
|
||||
}
|
||||
// Estimate the maximum input size assuming three channel 4:2:0 subsampled input frames.
|
||||
int maxInputSize = (maxPixels * 3) / (2 * minCompressionRatio);
|
||||
format.setInteger(android.media.MediaFormat.KEY_MAX_INPUT_SIZE, maxInputSize);
|
||||
}
|
||||
|
||||
private void maybeNotifyVideoSizeChanged() {
|
||||
if (eventHandler == null || eventListener == null
|
||||
|| (lastReportedWidth == currentWidth && lastReportedHeight == currentHeight
|
||||
&& lastReportedUnappliedRotationDegrees == currentUnappliedRotationDegrees
|
||||
&& lastReportedPixelWidthHeightRatio == currentPixelWidthHeightRatio)) {
|
||||
return;
|
||||
}
|
||||
// Make final copies to ensure the runnable reports the correct values.
|
||||
final int currentWidth = this.currentWidth;
|
||||
final int currentHeight = this.currentHeight;
|
||||
final int currentUnappliedRotationDegrees = this.currentUnappliedRotationDegrees;
|
||||
final float currentPixelWidthHeightRatio = this.currentPixelWidthHeightRatio;
|
||||
eventHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
eventListener.onVideoSizeChanged(currentWidth, currentHeight,
|
||||
currentUnappliedRotationDegrees, currentPixelWidthHeightRatio);
|
||||
}
|
||||
});
|
||||
// Update the last reported values.
|
||||
lastReportedWidth = currentWidth;
|
||||
lastReportedHeight = currentHeight;
|
||||
lastReportedUnappliedRotationDegrees = currentUnappliedRotationDegrees;
|
||||
lastReportedPixelWidthHeightRatio = currentPixelWidthHeightRatio;
|
||||
}
|
||||
|
||||
private void maybeNotifyDrawnToSurface() {
|
||||
if (eventHandler == null || eventListener == null || reportedDrawnToSurface) {
|
||||
return;
|
||||
}
|
||||
// Make a final copy to ensure the runnable reports the correct surface.
|
||||
final Surface surface = this.surface;
|
||||
eventHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
eventListener.onDrawnToSurface(surface);
|
||||
}
|
||||
});
|
||||
// Record that we have reported that the surface has been drawn to.
|
||||
reportedDrawnToSurface = true;
|
||||
}
|
||||
|
||||
private void maybeNotifyDroppedFrameCount() {
|
||||
if (eventHandler == null || eventListener == null || droppedFrameCount == 0) {
|
||||
return;
|
||||
}
|
||||
long now = SystemClock.elapsedRealtime();
|
||||
// Make final copies to ensure the runnable reports the correct values.
|
||||
final int countToNotify = droppedFrameCount;
|
||||
final long elapsedToNotify = now - droppedFrameAccumulationStartTimeMs;
|
||||
eventHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
eventListener.onDroppedFrames(countToNotify, elapsedToNotify);
|
||||
}
|
||||
});
|
||||
// Reset the dropped frame tracking.
|
||||
droppedFrameCount = 0;
|
||||
droppedFrameAccumulationStartTimeMs = now;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,502 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.util.Assertions;
|
||||
import com.b44t.messenger.exoplayer.util.MimeTypes;
|
||||
import com.b44t.messenger.exoplayer.util.Util;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.annotation.TargetApi;
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Defines the format of an elementary media stream.
|
||||
*/
|
||||
public final class MediaFormat implements Parcelable {
|
||||
|
||||
public static final int NO_VALUE = -1;
|
||||
|
||||
/**
|
||||
* A value for {@link #subsampleOffsetUs} to indicate that subsample timestamps are relative to
|
||||
* the timestamps of their parent samples.
|
||||
*/
|
||||
public static final long OFFSET_SAMPLE_RELATIVE = Long.MAX_VALUE;
|
||||
|
||||
/**
|
||||
* The identifier for the track represented by the format, or null if unknown or not applicable.
|
||||
*/
|
||||
public final String trackId;
|
||||
/**
|
||||
* The mime type of the format.
|
||||
*/
|
||||
public final String mimeType;
|
||||
/**
|
||||
* The average bandwidth in bits per second, or {@link #NO_VALUE} if unknown or not applicable.
|
||||
*/
|
||||
public final int bitrate;
|
||||
/**
|
||||
* The maximum size of a buffer of data (typically one sample) in the format, or {@link #NO_VALUE}
|
||||
* if unknown or not applicable.
|
||||
*/
|
||||
public final int maxInputSize;
|
||||
/**
|
||||
* The duration in microseconds, or {@link C#UNKNOWN_TIME_US} if the duration is unknown, or
|
||||
* {@link C#MATCH_LONGEST_US} if the duration should match the duration of the longest track whose
|
||||
* duration is known.
|
||||
*/
|
||||
public final long durationUs;
|
||||
/**
|
||||
* Initialization data that must be provided to the decoder. Will not be null, but may be empty
|
||||
* if initialization data is not required.
|
||||
*/
|
||||
public final List<byte[]> initializationData;
|
||||
/**
|
||||
* Whether the format represents an adaptive track, meaning that the format of the actual media
|
||||
* data may change (e.g. to adapt to network conditions).
|
||||
*/
|
||||
public final boolean adaptive;
|
||||
|
||||
// Video specific.
|
||||
|
||||
/**
|
||||
* The width of the video in pixels, or {@link #NO_VALUE} if unknown or not applicable.
|
||||
*/
|
||||
public final int width;
|
||||
|
||||
/**
|
||||
* The height of the video in pixels, or {@link #NO_VALUE} if unknown or not applicable.
|
||||
*/
|
||||
public final int height;
|
||||
/**
|
||||
* For formats that belong to an adaptive video track (either describing the track, or describing
|
||||
* a specific format within it), this is the maximum width of the video in pixels that will be
|
||||
* encountered in the stream. Set to {@link #NO_VALUE} if unknown or not applicable.
|
||||
*/
|
||||
public final int maxWidth;
|
||||
/**
|
||||
* For formats that belong to an adaptive video track (either describing the track, or describing
|
||||
* a specific format within it), this is the maximum height of the video in pixels that will be
|
||||
* encountered in the stream. Set to {@link #NO_VALUE} if unknown or not applicable.
|
||||
*/
|
||||
public final int maxHeight;
|
||||
/**
|
||||
* The clockwise rotation that should be applied to the video for it to be rendered in the correct
|
||||
* orientation, or {@link #NO_VALUE} if unknown or not applicable. Only 0, 90, 180 and 270 are
|
||||
* supported.
|
||||
*/
|
||||
public final int rotationDegrees;
|
||||
/**
|
||||
* The width to height ratio of pixels in the video, or {@link #NO_VALUE} if unknown or not
|
||||
* applicable.
|
||||
*/
|
||||
public final float pixelWidthHeightRatio;
|
||||
|
||||
// Audio specific.
|
||||
|
||||
/**
|
||||
* The number of audio channels, or {@link #NO_VALUE} if unknown or not applicable.
|
||||
*/
|
||||
public final int channelCount;
|
||||
/**
|
||||
* The audio sampling rate in Hz, or {@link #NO_VALUE} if unknown or not applicable.
|
||||
*/
|
||||
public final int sampleRate;
|
||||
/**
|
||||
* The encoding for PCM audio streams. If {@link #mimeType} is {@link MimeTypes#AUDIO_RAW} then
|
||||
* one of {@link C#ENCODING_PCM_8BIT}, {@link C#ENCODING_PCM_16BIT}, {@link C#ENCODING_PCM_24BIT}
|
||||
* and {@link C#ENCODING_PCM_32BIT}. Set to {@link #NO_VALUE} for other media types.
|
||||
*/
|
||||
public final int pcmEncoding;
|
||||
/**
|
||||
* The number of samples to trim from the start of the decoded audio stream.
|
||||
*/
|
||||
public final int encoderDelay;
|
||||
/**
|
||||
* The number of samples to trim from the end of the decoded audio stream.
|
||||
*/
|
||||
public final int encoderPadding;
|
||||
|
||||
// Text specific.
|
||||
|
||||
/**
|
||||
* The language of the track, or null if unknown or not applicable.
|
||||
*/
|
||||
public final String language;
|
||||
|
||||
/**
|
||||
* For samples that contain subsamples, this is an offset that should be added to subsample
|
||||
* timestamps. A value of {@link #OFFSET_SAMPLE_RELATIVE} indicates that subsample timestamps are
|
||||
* relative to the timestamps of their parent samples.
|
||||
*/
|
||||
public final long subsampleOffsetUs;
|
||||
|
||||
// Lazy-initialized hashcode and framework media format.
|
||||
|
||||
private int hashCode;
|
||||
private android.media.MediaFormat frameworkMediaFormat;
|
||||
|
||||
public static MediaFormat createVideoFormat(String trackId, String mimeType, int bitrate,
|
||||
int maxInputSize, long durationUs, int width, int height, List<byte[]> initializationData) {
|
||||
return createVideoFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, width, height,
|
||||
initializationData, NO_VALUE, NO_VALUE);
|
||||
}
|
||||
|
||||
public static MediaFormat createVideoFormat(String trackId, String mimeType, int bitrate,
|
||||
int maxInputSize, long durationUs, int width, int height, List<byte[]> initializationData,
|
||||
int rotationDegrees, float pixelWidthHeightRatio) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, width, height,
|
||||
rotationDegrees, pixelWidthHeightRatio, NO_VALUE, NO_VALUE, null, OFFSET_SAMPLE_RELATIVE,
|
||||
initializationData, false, NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE);
|
||||
}
|
||||
|
||||
public static MediaFormat createAudioFormat(String trackId, String mimeType, int bitrate,
|
||||
int maxInputSize, long durationUs, int channelCount, int sampleRate,
|
||||
List<byte[]> initializationData, String language) {
|
||||
return createAudioFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, channelCount,
|
||||
sampleRate, initializationData, language, NO_VALUE);
|
||||
}
|
||||
|
||||
public static MediaFormat createAudioFormat(String trackId, String mimeType, int bitrate,
|
||||
int maxInputSize, long durationUs, int channelCount, int sampleRate,
|
||||
List<byte[]> initializationData, String language, int pcmEncoding) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, NO_VALUE, NO_VALUE,
|
||||
NO_VALUE, NO_VALUE, channelCount, sampleRate, language, OFFSET_SAMPLE_RELATIVE,
|
||||
initializationData, false, NO_VALUE, NO_VALUE, pcmEncoding, NO_VALUE, NO_VALUE);
|
||||
}
|
||||
|
||||
public static MediaFormat createTextFormat(String trackId, String mimeType, int bitrate,
|
||||
long durationUs, String language) {
|
||||
return createTextFormat(trackId, mimeType, bitrate, durationUs, language,
|
||||
OFFSET_SAMPLE_RELATIVE);
|
||||
}
|
||||
|
||||
public static MediaFormat createTextFormat(String trackId, String mimeType, int bitrate,
|
||||
long durationUs, String language, long subsampleOffsetUs) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, NO_VALUE, durationUs, NO_VALUE, NO_VALUE,
|
||||
NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE, language, subsampleOffsetUs, null, false, NO_VALUE,
|
||||
NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE);
|
||||
}
|
||||
|
||||
public static MediaFormat createImageFormat(String trackId, String mimeType, int bitrate,
|
||||
long durationUs, List<byte[]> initializationData, String language) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, NO_VALUE, durationUs, NO_VALUE, NO_VALUE,
|
||||
NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE, language, OFFSET_SAMPLE_RELATIVE,
|
||||
initializationData, false, NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE);
|
||||
}
|
||||
|
||||
public static MediaFormat createFormatForMimeType(String trackId, String mimeType, int bitrate,
|
||||
long durationUs) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, NO_VALUE, durationUs, NO_VALUE, NO_VALUE,
|
||||
NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE, null, OFFSET_SAMPLE_RELATIVE, null, false, NO_VALUE,
|
||||
NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE);
|
||||
}
|
||||
|
||||
public static MediaFormat createId3Format() {
|
||||
return createFormatForMimeType(null, MimeTypes.APPLICATION_ID3, MediaFormat.NO_VALUE,
|
||||
C.UNKNOWN_TIME_US);
|
||||
}
|
||||
|
||||
/* package */ MediaFormat(Parcel in) {
|
||||
trackId = in.readString();
|
||||
mimeType = in.readString();
|
||||
bitrate = in.readInt();
|
||||
maxInputSize = in.readInt();
|
||||
durationUs = in.readLong();
|
||||
width = in.readInt();
|
||||
height = in.readInt();
|
||||
rotationDegrees = in.readInt();
|
||||
pixelWidthHeightRatio = in.readFloat();
|
||||
channelCount = in.readInt();
|
||||
sampleRate = in.readInt();
|
||||
language = in.readString();
|
||||
subsampleOffsetUs = in.readLong();
|
||||
initializationData = new ArrayList<>();
|
||||
in.readList(initializationData, null);
|
||||
adaptive = in.readInt() == 1;
|
||||
maxWidth = in.readInt();
|
||||
maxHeight = in.readInt();
|
||||
pcmEncoding = in.readInt();
|
||||
encoderDelay = in.readInt();
|
||||
encoderPadding = in.readInt();
|
||||
}
|
||||
|
||||
/* package */ MediaFormat(String trackId, String mimeType, int bitrate, int maxInputSize,
|
||||
long durationUs, int width, int height, int rotationDegrees, float pixelWidthHeightRatio,
|
||||
int channelCount, int sampleRate, String language, long subsampleOffsetUs,
|
||||
List<byte[]> initializationData, boolean adaptive, int maxWidth, int maxHeight,
|
||||
int pcmEncoding, int encoderDelay, int encoderPadding) {
|
||||
this.trackId = trackId;
|
||||
this.mimeType = Assertions.checkNotEmpty(mimeType);
|
||||
this.bitrate = bitrate;
|
||||
this.maxInputSize = maxInputSize;
|
||||
this.durationUs = durationUs;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.rotationDegrees = rotationDegrees;
|
||||
this.pixelWidthHeightRatio = pixelWidthHeightRatio;
|
||||
this.channelCount = channelCount;
|
||||
this.sampleRate = sampleRate;
|
||||
this.language = language;
|
||||
this.subsampleOffsetUs = subsampleOffsetUs;
|
||||
this.initializationData = initializationData == null ? Collections.<byte[]>emptyList()
|
||||
: initializationData;
|
||||
this.adaptive = adaptive;
|
||||
this.maxWidth = maxWidth;
|
||||
this.maxHeight = maxHeight;
|
||||
this.pcmEncoding = pcmEncoding;
|
||||
this.encoderDelay = encoderDelay;
|
||||
this.encoderPadding = encoderPadding;
|
||||
}
|
||||
|
||||
public MediaFormat copyWithMaxInputSize(int maxInputSize) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, width, height,
|
||||
rotationDegrees, pixelWidthHeightRatio, channelCount, sampleRate, language,
|
||||
subsampleOffsetUs, initializationData, adaptive, maxWidth, maxHeight, pcmEncoding,
|
||||
encoderDelay, encoderPadding);
|
||||
}
|
||||
|
||||
public MediaFormat copyWithMaxVideoDimensions(int maxWidth, int maxHeight) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, width, height,
|
||||
rotationDegrees, pixelWidthHeightRatio, channelCount, sampleRate, language,
|
||||
subsampleOffsetUs, initializationData, adaptive, maxWidth, maxHeight, pcmEncoding,
|
||||
encoderDelay, encoderPadding);
|
||||
}
|
||||
|
||||
public MediaFormat copyWithSubsampleOffsetUs(long subsampleOffsetUs) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, width, height,
|
||||
rotationDegrees, pixelWidthHeightRatio, channelCount, sampleRate, language,
|
||||
subsampleOffsetUs, initializationData, adaptive, maxWidth, maxHeight, pcmEncoding,
|
||||
encoderDelay, encoderPadding);
|
||||
}
|
||||
|
||||
public MediaFormat copyWithDurationUs(long durationUs) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, width, height,
|
||||
rotationDegrees, pixelWidthHeightRatio, channelCount, sampleRate, language,
|
||||
subsampleOffsetUs, initializationData, adaptive, maxWidth, maxHeight, pcmEncoding,
|
||||
encoderDelay, encoderPadding);
|
||||
}
|
||||
|
||||
public MediaFormat copyWithLanguage(String language) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, width, height,
|
||||
rotationDegrees, pixelWidthHeightRatio, channelCount, sampleRate, language,
|
||||
subsampleOffsetUs, initializationData, adaptive, maxWidth, maxHeight, pcmEncoding,
|
||||
encoderDelay, encoderPadding);
|
||||
}
|
||||
|
||||
public MediaFormat copyWithFixedTrackInfo(String trackId, int bitrate, int width, int height,
|
||||
String language) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, width, height,
|
||||
rotationDegrees, pixelWidthHeightRatio, channelCount, sampleRate, language,
|
||||
subsampleOffsetUs, initializationData, adaptive, NO_VALUE, NO_VALUE, pcmEncoding,
|
||||
encoderDelay, encoderPadding);
|
||||
}
|
||||
|
||||
public MediaFormat copyAsAdaptive(String trackId) {
|
||||
return new MediaFormat(trackId, mimeType, NO_VALUE, NO_VALUE, durationUs, NO_VALUE, NO_VALUE,
|
||||
NO_VALUE, NO_VALUE, NO_VALUE, NO_VALUE, null, OFFSET_SAMPLE_RELATIVE, null, true, maxWidth,
|
||||
maxHeight, NO_VALUE, NO_VALUE, NO_VALUE);
|
||||
}
|
||||
|
||||
public MediaFormat copyWithGaplessInfo(int encoderDelay, int encoderPadding) {
|
||||
return new MediaFormat(trackId, mimeType, bitrate, maxInputSize, durationUs, width, height,
|
||||
rotationDegrees, pixelWidthHeightRatio, channelCount, sampleRate, language,
|
||||
subsampleOffsetUs, initializationData, adaptive, maxWidth, maxHeight, pcmEncoding,
|
||||
encoderDelay, encoderPadding);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A {@link MediaFormat} representation of this format.
|
||||
*/
|
||||
@SuppressLint("InlinedApi")
|
||||
@TargetApi(16)
|
||||
public final android.media.MediaFormat getFrameworkMediaFormatV16() {
|
||||
if (frameworkMediaFormat == null) {
|
||||
android.media.MediaFormat format = new android.media.MediaFormat();
|
||||
format.setString(android.media.MediaFormat.KEY_MIME, mimeType);
|
||||
maybeSetStringV16(format, android.media.MediaFormat.KEY_LANGUAGE, language);
|
||||
maybeSetIntegerV16(format, android.media.MediaFormat.KEY_MAX_INPUT_SIZE, maxInputSize);
|
||||
maybeSetIntegerV16(format, android.media.MediaFormat.KEY_WIDTH, width);
|
||||
maybeSetIntegerV16(format, android.media.MediaFormat.KEY_HEIGHT, height);
|
||||
maybeSetIntegerV16(format, "rotation-degrees", rotationDegrees);
|
||||
maybeSetIntegerV16(format, android.media.MediaFormat.KEY_MAX_WIDTH, maxWidth);
|
||||
maybeSetIntegerV16(format, android.media.MediaFormat.KEY_MAX_HEIGHT, maxHeight);
|
||||
maybeSetIntegerV16(format, android.media.MediaFormat.KEY_CHANNEL_COUNT, channelCount);
|
||||
maybeSetIntegerV16(format, android.media.MediaFormat.KEY_SAMPLE_RATE, sampleRate);
|
||||
maybeSetIntegerV16(format, "encoder-delay", encoderDelay);
|
||||
maybeSetIntegerV16(format, "encoder-padding", encoderPadding);
|
||||
for (int i = 0; i < initializationData.size(); i++) {
|
||||
format.setByteBuffer("csd-" + i, ByteBuffer.wrap(initializationData.get(i)));
|
||||
}
|
||||
if (durationUs != C.UNKNOWN_TIME_US) {
|
||||
format.setLong(android.media.MediaFormat.KEY_DURATION, durationUs);
|
||||
}
|
||||
frameworkMediaFormat = format;
|
||||
}
|
||||
return frameworkMediaFormat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the framework format returned by {@link #getFrameworkMediaFormatV16()}.
|
||||
*
|
||||
* @deprecated This method only exists for FrameworkSampleSource, which is itself deprecated.
|
||||
* @param format The framework format.
|
||||
*/
|
||||
@Deprecated
|
||||
@TargetApi(16)
|
||||
/* package */ final void setFrameworkFormatV16(android.media.MediaFormat format) {
|
||||
frameworkMediaFormat = format;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MediaFormat(" + trackId + ", " + mimeType + ", " + bitrate + ", " + maxInputSize
|
||||
+ ", " + width + ", " + height + ", " + rotationDegrees + ", " + pixelWidthHeightRatio
|
||||
+ ", " + channelCount + ", " + sampleRate + ", " + language + ", " + durationUs + ", "
|
||||
+ adaptive + ", " + maxWidth + ", " + maxHeight + ", " + pcmEncoding + ", " + encoderDelay
|
||||
+ ", " + encoderPadding + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
if (hashCode == 0) {
|
||||
int result = 17;
|
||||
result = 31 * result + (trackId == null ? 0 : trackId.hashCode());
|
||||
result = 31 * result + (mimeType == null ? 0 : mimeType.hashCode());
|
||||
result = 31 * result + bitrate;
|
||||
result = 31 * result + maxInputSize;
|
||||
result = 31 * result + width;
|
||||
result = 31 * result + height;
|
||||
result = 31 * result + rotationDegrees;
|
||||
result = 31 * result + Float.floatToRawIntBits(pixelWidthHeightRatio);
|
||||
result = 31 * result + (int) durationUs;
|
||||
result = 31 * result + (adaptive ? 1231 : 1237);
|
||||
result = 31 * result + maxWidth;
|
||||
result = 31 * result + maxHeight;
|
||||
result = 31 * result + channelCount;
|
||||
result = 31 * result + sampleRate;
|
||||
result = 31 * result + pcmEncoding;
|
||||
result = 31 * result + encoderDelay;
|
||||
result = 31 * result + encoderPadding;
|
||||
result = 31 * result + (language == null ? 0 : language.hashCode());
|
||||
result = 31 * result + (int) subsampleOffsetUs;
|
||||
for (int i = 0; i < initializationData.size(); i++) {
|
||||
result = 31 * result + Arrays.hashCode(initializationData.get(i));
|
||||
}
|
||||
hashCode = result;
|
||||
}
|
||||
return hashCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null || getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
MediaFormat other = (MediaFormat) obj;
|
||||
if (adaptive != other.adaptive || bitrate != other.bitrate || maxInputSize != other.maxInputSize
|
||||
|| durationUs != other.durationUs || width != other.width || height != other.height
|
||||
|| rotationDegrees != other.rotationDegrees
|
||||
|| pixelWidthHeightRatio != other.pixelWidthHeightRatio
|
||||
|| maxWidth != other.maxWidth || maxHeight != other.maxHeight
|
||||
|| channelCount != other.channelCount || sampleRate != other.sampleRate
|
||||
|| pcmEncoding != other.pcmEncoding || encoderDelay != other.encoderDelay
|
||||
|| encoderPadding != other.encoderPadding || subsampleOffsetUs != other.subsampleOffsetUs
|
||||
|| !Util.areEqual(trackId, other.trackId) || !Util.areEqual(language, other.language)
|
||||
|| !Util.areEqual(mimeType, other.mimeType)
|
||||
|| initializationData.size() != other.initializationData.size()) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < initializationData.size(); i++) {
|
||||
if (!Arrays.equals(initializationData.get(i), other.initializationData.get(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@TargetApi(16)
|
||||
private static final void maybeSetStringV16(android.media.MediaFormat format, String key,
|
||||
String value) {
|
||||
if (value != null) {
|
||||
format.setString(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(16)
|
||||
private static final void maybeSetIntegerV16(android.media.MediaFormat format, String key,
|
||||
int value) {
|
||||
if (value != NO_VALUE) {
|
||||
format.setInteger(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
// Parcelable implementation.
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(Parcel dest, int flags) {
|
||||
dest.writeString(trackId);
|
||||
dest.writeString(mimeType);
|
||||
dest.writeInt(bitrate);
|
||||
dest.writeInt(maxInputSize);
|
||||
dest.writeLong(durationUs);
|
||||
dest.writeInt(width);
|
||||
dest.writeInt(height);
|
||||
dest.writeInt(rotationDegrees);
|
||||
dest.writeFloat(pixelWidthHeightRatio);
|
||||
dest.writeInt(channelCount);
|
||||
dest.writeInt(sampleRate);
|
||||
dest.writeString(language);
|
||||
dest.writeLong(subsampleOffsetUs);
|
||||
dest.writeList(initializationData);
|
||||
dest.writeInt(adaptive ? 1 : 0);
|
||||
dest.writeInt(maxWidth);
|
||||
dest.writeInt(maxHeight);
|
||||
dest.writeInt(pcmEncoding);
|
||||
dest.writeInt(encoderDelay);
|
||||
dest.writeInt(encoderPadding);
|
||||
}
|
||||
|
||||
public static final Creator<MediaFormat> CREATOR = new Creator<MediaFormat>() {
|
||||
|
||||
@Override
|
||||
public MediaFormat createFromParcel(Parcel in) {
|
||||
return new MediaFormat(in);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MediaFormat[] newArray(int size) {
|
||||
return new MediaFormat[size];
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.drm.DrmInitData;
|
||||
|
||||
/**
|
||||
* Holds a {@link MediaFormat} and corresponding drm scheme initialization data.
|
||||
*/
|
||||
public final class MediaFormatHolder {
|
||||
|
||||
/**
|
||||
* The format of the media.
|
||||
*/
|
||||
public MediaFormat format;
|
||||
/**
|
||||
* Initialization data for drm schemes supported by the media. Null if the media is not encrypted.
|
||||
*/
|
||||
public DrmInitData drmInitData;
|
||||
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Thrown when an error occurs parsing media data.
|
||||
*/
|
||||
public class ParserException extends IOException {
|
||||
|
||||
public ParserException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ParserException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ParserException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public ParserException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
/**
|
||||
* Holds sample data and corresponding metadata.
|
||||
*/
|
||||
public final class SampleHolder {
|
||||
|
||||
/**
|
||||
* Disallows buffer replacement.
|
||||
*/
|
||||
public static final int BUFFER_REPLACEMENT_MODE_DISABLED = 0;
|
||||
|
||||
/**
|
||||
* Allows buffer replacement using {@link ByteBuffer#allocate(int)}.
|
||||
*/
|
||||
public static final int BUFFER_REPLACEMENT_MODE_NORMAL = 1;
|
||||
|
||||
/**
|
||||
* Allows buffer replacement using {@link ByteBuffer#allocateDirect(int)}.
|
||||
*/
|
||||
public static final int BUFFER_REPLACEMENT_MODE_DIRECT = 2;
|
||||
|
||||
public final CryptoInfo cryptoInfo;
|
||||
|
||||
/**
|
||||
* A buffer holding the sample data.
|
||||
*/
|
||||
public ByteBuffer data;
|
||||
|
||||
/**
|
||||
* The size of the sample in bytes.
|
||||
*/
|
||||
public int size;
|
||||
|
||||
/**
|
||||
* Flags that accompany the sample. A combination of {@link C#SAMPLE_FLAG_SYNC},
|
||||
* {@link C#SAMPLE_FLAG_ENCRYPTED} and {@link C#SAMPLE_FLAG_DECODE_ONLY}.
|
||||
*/
|
||||
public int flags;
|
||||
|
||||
/**
|
||||
* The time at which the sample should be presented.
|
||||
*/
|
||||
public long timeUs;
|
||||
|
||||
private final int bufferReplacementMode;
|
||||
|
||||
/**
|
||||
* @param bufferReplacementMode Determines the behavior of {@link #ensureSpaceForWrite(int)}. One
|
||||
* of {@link #BUFFER_REPLACEMENT_MODE_DISABLED}, {@link #BUFFER_REPLACEMENT_MODE_NORMAL} and
|
||||
* {@link #BUFFER_REPLACEMENT_MODE_DIRECT}.
|
||||
*/
|
||||
public SampleHolder(int bufferReplacementMode) {
|
||||
this.cryptoInfo = new CryptoInfo();
|
||||
this.bufferReplacementMode = bufferReplacementMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that {@link #data} is large enough to accommodate a write of a given length at its
|
||||
* current position.
|
||||
* <p>
|
||||
* If the capacity of {@link #data} is sufficient this method does nothing. If the capacity is
|
||||
* insufficient then an attempt is made to replace {@link #data} with a new {@link ByteBuffer}
|
||||
* whose capacity is sufficient. Data up to the current position is copied to the new buffer.
|
||||
*
|
||||
* @param length The length of the write that must be accommodated, in bytes.
|
||||
* @throws IllegalStateException If there is insufficient capacity to accommodate the write and
|
||||
* the buffer replacement mode of the holder is {@link #BUFFER_REPLACEMENT_MODE_DISABLED}.
|
||||
*/
|
||||
public void ensureSpaceForWrite(int length) throws IllegalStateException {
|
||||
if (data == null) {
|
||||
data = createReplacementBuffer(length);
|
||||
return;
|
||||
}
|
||||
// Check whether the current buffer is sufficient.
|
||||
int capacity = data.capacity();
|
||||
int position = data.position();
|
||||
int requiredCapacity = position + length;
|
||||
if (capacity >= requiredCapacity) {
|
||||
return;
|
||||
}
|
||||
// Instantiate a new buffer if possible.
|
||||
ByteBuffer newData = createReplacementBuffer(requiredCapacity);
|
||||
// Copy data up to the current position from the old buffer to the new one.
|
||||
if (position > 0) {
|
||||
data.position(0);
|
||||
data.limit(position);
|
||||
newData.put(data);
|
||||
}
|
||||
// Set the new buffer.
|
||||
data = newData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether {@link #flags} has {@link C#SAMPLE_FLAG_ENCRYPTED} set.
|
||||
*/
|
||||
public boolean isEncrypted() {
|
||||
return (flags & C.SAMPLE_FLAG_ENCRYPTED) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether {@link #flags} has {@link C#SAMPLE_FLAG_DECODE_ONLY} set.
|
||||
*/
|
||||
public boolean isDecodeOnly() {
|
||||
return (flags & C.SAMPLE_FLAG_DECODE_ONLY) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether {@link #flags} has {@link C#SAMPLE_FLAG_SYNC} set.
|
||||
*/
|
||||
public boolean isSyncFrame() {
|
||||
return (flags & C.SAMPLE_FLAG_SYNC) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears {@link #data}. Does nothing if {@link #data} is null.
|
||||
*/
|
||||
public void clearData() {
|
||||
if (data != null) {
|
||||
data.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private ByteBuffer createReplacementBuffer(int requiredCapacity) {
|
||||
if (bufferReplacementMode == BUFFER_REPLACEMENT_MODE_NORMAL) {
|
||||
return ByteBuffer.allocate(requiredCapacity);
|
||||
} else if (bufferReplacementMode == BUFFER_REPLACEMENT_MODE_DIRECT) {
|
||||
return ByteBuffer.allocateDirect(requiredCapacity);
|
||||
} else {
|
||||
int currentCapacity = data == null ? 0 : data.capacity();
|
||||
throw new IllegalStateException("Buffer too small (" + currentCapacity + " < "
|
||||
+ requiredCapacity + ")");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* A source of media samples.
|
||||
* <p>
|
||||
* A {@link SampleSource} may expose one or multiple tracks. The number of tracks and each track's
|
||||
* media format can be queried using {@link SampleSourceReader#getTrackCount()} and
|
||||
* {@link SampleSourceReader#getFormat(int)} respectively.
|
||||
*/
|
||||
public interface SampleSource {
|
||||
|
||||
/**
|
||||
* The end of stream has been reached.
|
||||
*/
|
||||
public static final int END_OF_STREAM = -1;
|
||||
/**
|
||||
* Neither a sample nor a format was read in full. This may be because insufficient data is
|
||||
* buffered upstream. If multiple tracks are enabled, this return value may indicate that the
|
||||
* next piece of data to be returned from the {@link SampleSource} corresponds to a different
|
||||
* track than the one for which data was requested.
|
||||
*/
|
||||
public static final int NOTHING_READ = -2;
|
||||
/**
|
||||
* A sample was read.
|
||||
*/
|
||||
public static final int SAMPLE_READ = -3;
|
||||
/**
|
||||
* A format was read.
|
||||
*/
|
||||
public static final int FORMAT_READ = -4;
|
||||
/**
|
||||
* Returned from {@link SampleSourceReader#readDiscontinuity(int)} to indicate no discontinuity.
|
||||
*/
|
||||
public static final long NO_DISCONTINUITY = Long.MIN_VALUE;
|
||||
|
||||
/**
|
||||
* A consumer of samples should call this method to register themselves and gain access to the
|
||||
* source through the returned {@link SampleSourceReader}.
|
||||
* <p>
|
||||
* {@link SampleSourceReader#release()} should be called on the returned object when access is no
|
||||
* longer required.
|
||||
*
|
||||
* @return A {@link SampleSourceReader} that provides access to the source.
|
||||
*/
|
||||
public SampleSourceReader register();
|
||||
|
||||
/**
|
||||
* An interface providing read access to a {@link SampleSource}.
|
||||
*/
|
||||
public interface SampleSourceReader {
|
||||
|
||||
/**
|
||||
* If the source is currently having difficulty preparing or loading samples, then this method
|
||||
* throws the underlying error. Otherwise does nothing.
|
||||
*
|
||||
* @throws IOException The underlying error.
|
||||
*/
|
||||
public void maybeThrowError() throws IOException;
|
||||
|
||||
/**
|
||||
* Prepares the source.
|
||||
* <p>
|
||||
* Preparation may require reading from the data source (e.g. to determine the available tracks
|
||||
* and formats). If insufficient data is available then the call will return {@code false}
|
||||
* rather than block. The method can be called repeatedly until the return value indicates
|
||||
* success.
|
||||
*
|
||||
* @param positionUs The player's current playback position.
|
||||
* @return True if the source was prepared, false otherwise.
|
||||
*/
|
||||
public boolean prepare(long positionUs);
|
||||
|
||||
/**
|
||||
* Returns the number of tracks exposed by the source.
|
||||
* <p>
|
||||
* This method should only be called after the source has been prepared.
|
||||
*
|
||||
* @return The number of tracks.
|
||||
*/
|
||||
public int getTrackCount();
|
||||
|
||||
/**
|
||||
* Returns the format of the specified track.
|
||||
* <p>
|
||||
* Note that whilst the format of a track will remain constant, the format of the actual media
|
||||
* stream may change dynamically. An example of this is where the track is adaptive
|
||||
* (i.e. @link {@link MediaFormat#adaptive} is true). Hence the track formats returned through
|
||||
* this method should not be used to configure decoders. Decoder configuration should be
|
||||
* performed using the formats obtained when reading the media stream through calls to
|
||||
* {@link #readData(int, long, MediaFormatHolder, SampleHolder)}.
|
||||
* <p>
|
||||
* This method should only be called after the source has been prepared.
|
||||
*
|
||||
* @param track The track index.
|
||||
* @return The format of the specified track.
|
||||
*/
|
||||
public MediaFormat getFormat(int track);
|
||||
|
||||
/**
|
||||
* Enable the specified track. This allows the track's format and samples to be read from
|
||||
* {@link #readData(int, long, MediaFormatHolder, SampleHolder)}.
|
||||
* <p>
|
||||
* This method should only be called after the source has been prepared, and when the specified
|
||||
* track is disabled.
|
||||
*
|
||||
* @param track The track to enable.
|
||||
* @param positionUs The player's current playback position.
|
||||
*/
|
||||
public void enable(int track, long positionUs);
|
||||
|
||||
/**
|
||||
* Indicates to the source that it should still be buffering data for the specified track.
|
||||
* <p>
|
||||
* This method should only be called when the specified track is enabled.
|
||||
*
|
||||
* @param track The track to continue buffering.
|
||||
* @param positionUs The current playback position.
|
||||
* @return True if the track has available samples, or if the end of the stream has been
|
||||
* reached. False if more data needs to be buffered for samples to become available.
|
||||
*/
|
||||
public boolean continueBuffering(int track, long positionUs);
|
||||
|
||||
/**
|
||||
* Attempts to read a pending discontinuity from the source.
|
||||
* <p>
|
||||
* This method should only be called when the specified track is enabled.
|
||||
*
|
||||
* @param track The track from which to read.
|
||||
* @return If a discontinuity was read then the playback position after the discontinuity. Else
|
||||
* {@link #NO_DISCONTINUITY}.
|
||||
*/
|
||||
public long readDiscontinuity(int track);
|
||||
|
||||
/**
|
||||
* Attempts to read a sample or a new format from the source.
|
||||
* <p>
|
||||
* This method should only be called when the specified track is enabled.
|
||||
* <p>
|
||||
* Note that where multiple tracks are enabled, {@link #NOTHING_READ} may be returned if the
|
||||
* next piece of data to be read from the {@link SampleSource} corresponds to a different track
|
||||
* than the one for which data was requested.
|
||||
* <p>
|
||||
* This method will always return {@link #NOTHING_READ} in the case that there's a pending
|
||||
* discontinuity to be read from {@link #readDiscontinuity(int)} for the specified track.
|
||||
*
|
||||
* @param track The track from which to read.
|
||||
* @param positionUs The current playback position.
|
||||
* @param formatHolder A {@link MediaFormatHolder} object to populate in the case of a new
|
||||
* format.
|
||||
* @param sampleHolder A {@link SampleHolder} object to populate in the case of a new sample.
|
||||
* If the caller requires the sample data then it must ensure that {@link SampleHolder#data}
|
||||
* references a valid output buffer.
|
||||
* @return The result, which can be {@link #SAMPLE_READ}, {@link #FORMAT_READ},
|
||||
* {@link #NOTHING_READ} or {@link #END_OF_STREAM}.
|
||||
*/
|
||||
public int readData(int track, long positionUs, MediaFormatHolder formatHolder,
|
||||
SampleHolder sampleHolder);
|
||||
|
||||
/**
|
||||
* Seeks to the specified time in microseconds.
|
||||
* <p>
|
||||
* This method should only be called when at least one track is enabled.
|
||||
*
|
||||
* @param positionUs The seek position in microseconds.
|
||||
*/
|
||||
public void seekToUs(long positionUs);
|
||||
|
||||
/**
|
||||
* Returns an estimate of the position up to which data is buffered.
|
||||
* <p>
|
||||
* This method should only be called when at least one track is enabled.
|
||||
*
|
||||
* @return An estimate of the absolute position in microseconds up to which data is buffered,
|
||||
* or {@link TrackRenderer#END_OF_TRACK_US} if data is buffered to the end of the stream,
|
||||
* or {@link TrackRenderer#UNKNOWN_TIME_US} if no estimate is available.
|
||||
*/
|
||||
public long getBufferedPositionUs();
|
||||
|
||||
/**
|
||||
* Disable the specified track.
|
||||
* <p>
|
||||
* This method should only be called when the specified track is enabled.
|
||||
*
|
||||
* @param track The track to disable.
|
||||
*/
|
||||
public void disable(int track);
|
||||
|
||||
/**
|
||||
* Releases the {@link SampleSourceReader}.
|
||||
* <p>
|
||||
* This method should be called when access to the {@link SampleSource} is no longer required.
|
||||
*/
|
||||
public void release();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-267
@@ -1,267 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.MediaCodecUtil.DecoderQueryException;
|
||||
import com.b44t.messenger.exoplayer.SampleSource.SampleSourceReader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Base class for {@link TrackRenderer} implementations that render samples obtained from a
|
||||
* {@link SampleSource}.
|
||||
*/
|
||||
public abstract class SampleSourceTrackRenderer extends TrackRenderer {
|
||||
|
||||
private final SampleSourceReader[] sources;
|
||||
|
||||
private int[] handledSourceIndices;
|
||||
private int[] handledSourceTrackIndices;
|
||||
|
||||
private SampleSourceReader enabledSource;
|
||||
private int enabledSourceTrackIndex;
|
||||
|
||||
private long durationUs;
|
||||
|
||||
/**
|
||||
* @param sources One or more upstream sources from which the renderer can obtain samples.
|
||||
*/
|
||||
public SampleSourceTrackRenderer(SampleSource... sources) {
|
||||
this.sources = new SampleSourceReader[sources.length];
|
||||
for (int i = 0; i < sources.length; i++) {
|
||||
this.sources[i] = sources[i].register();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final boolean doPrepare(long positionUs) throws ExoPlaybackException {
|
||||
boolean allSourcesPrepared = true;
|
||||
for (int i = 0; i < sources.length; i++) {
|
||||
allSourcesPrepared &= sources[i].prepare(positionUs);
|
||||
}
|
||||
if (!allSourcesPrepared) {
|
||||
return false;
|
||||
}
|
||||
// The sources are all prepared.
|
||||
int totalSourceTrackCount = 0;
|
||||
for (int i = 0; i < sources.length; i++) {
|
||||
totalSourceTrackCount += sources[i].getTrackCount();
|
||||
}
|
||||
long durationUs = 0;
|
||||
int handledTrackCount = 0;
|
||||
int[] handledSourceIndices = new int[totalSourceTrackCount];
|
||||
int[] handledTrackIndices = new int[totalSourceTrackCount];
|
||||
int sourceCount = sources.length;
|
||||
for (int sourceIndex = 0; sourceIndex < sourceCount; sourceIndex++) {
|
||||
SampleSourceReader source = sources[sourceIndex];
|
||||
int sourceTrackCount = source.getTrackCount();
|
||||
for (int trackIndex = 0; trackIndex < sourceTrackCount; trackIndex++) {
|
||||
MediaFormat format = source.getFormat(trackIndex);
|
||||
boolean handlesTrack;
|
||||
try {
|
||||
handlesTrack = handlesTrack(format);
|
||||
} catch (DecoderQueryException e) {
|
||||
throw new ExoPlaybackException(e);
|
||||
}
|
||||
if (handlesTrack) {
|
||||
handledSourceIndices[handledTrackCount] = sourceIndex;
|
||||
handledTrackIndices[handledTrackCount] = trackIndex;
|
||||
handledTrackCount++;
|
||||
if (durationUs == TrackRenderer.UNKNOWN_TIME_US) {
|
||||
// We've already encountered a track for which the duration is unknown, so the media
|
||||
// duration is unknown regardless of the duration of this track.
|
||||
} else {
|
||||
long trackDurationUs = format.durationUs;
|
||||
if (trackDurationUs == TrackRenderer.UNKNOWN_TIME_US) {
|
||||
durationUs = TrackRenderer.UNKNOWN_TIME_US;
|
||||
} else if (trackDurationUs == TrackRenderer.MATCH_LONGEST_US) {
|
||||
// Do nothing.
|
||||
} else {
|
||||
durationUs = Math.max(durationUs, trackDurationUs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
this.durationUs = durationUs;
|
||||
this.handledSourceIndices = Arrays.copyOf(handledSourceIndices, handledTrackCount);
|
||||
this.handledSourceTrackIndices = Arrays.copyOf(handledTrackIndices, handledTrackCount);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onEnabled(int track, long positionUs, boolean joining)
|
||||
throws ExoPlaybackException {
|
||||
positionUs = shiftInputPosition(positionUs);
|
||||
enabledSource = sources[handledSourceIndices[track]];
|
||||
enabledSourceTrackIndex = handledSourceTrackIndices[track];
|
||||
enabledSource.enable(enabledSourceTrackIndex, positionUs);
|
||||
onDiscontinuity(positionUs);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final void seekTo(long positionUs) throws ExoPlaybackException {
|
||||
positionUs = shiftInputPosition(positionUs);
|
||||
enabledSource.seekToUs(positionUs);
|
||||
checkForDiscontinuity(positionUs);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final void doSomeWork(long positionUs, long elapsedRealtimeUs)
|
||||
throws ExoPlaybackException {
|
||||
positionUs = shiftInputPosition(positionUs);
|
||||
boolean sourceIsReady = enabledSource.continueBuffering(enabledSourceTrackIndex, positionUs);
|
||||
positionUs = checkForDiscontinuity(positionUs);
|
||||
doSomeWork(positionUs, elapsedRealtimeUs, sourceIsReady);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected long getBufferedPositionUs() {
|
||||
return enabledSource.getBufferedPositionUs();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected long getDurationUs() {
|
||||
return durationUs;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void maybeThrowError() throws ExoPlaybackException {
|
||||
if (enabledSource != null) {
|
||||
maybeThrowError(enabledSource);
|
||||
} else {
|
||||
int sourceCount = sources.length;
|
||||
for (int i = 0; i < sourceCount; i++) {
|
||||
maybeThrowError(sources[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDisabled() throws ExoPlaybackException {
|
||||
enabledSource.disable(enabledSourceTrackIndex);
|
||||
enabledSource = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onReleased() throws ExoPlaybackException {
|
||||
int sourceCount = sources.length;
|
||||
for (int i = 0; i < sourceCount; i++) {
|
||||
sources[i].release();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final int getTrackCount() {
|
||||
return handledSourceTrackIndices.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final MediaFormat getFormat(int track) {
|
||||
SampleSourceReader source = sources[handledSourceIndices[track]];
|
||||
return source.getFormat(handledSourceTrackIndices[track]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shifts positions passed to {@link #onEnabled(int, long, boolean)}, {@link #seekTo(long)} and
|
||||
* {@link #doSomeWork(long, long)}.
|
||||
* <p>
|
||||
* The default implementation does not modify the position. Except in very specific cases,
|
||||
* subclasses should not override this method.
|
||||
*
|
||||
* @param positionUs The position in microseconds.
|
||||
* @return The adjusted position in microseconds.
|
||||
*/
|
||||
protected long shiftInputPosition(long positionUs) {
|
||||
return positionUs;
|
||||
}
|
||||
|
||||
// Methods to be called by subclasses.
|
||||
|
||||
/**
|
||||
* Reads from the enabled upstream source.
|
||||
*
|
||||
* @param positionUs The current playback position.
|
||||
* @param formatHolder A {@link MediaFormatHolder} object to populate in the case of a new format.
|
||||
* @param sampleHolder A {@link SampleHolder} object to populate in the case of a new sample.
|
||||
* If the caller requires the sample data then it must ensure that {@link SampleHolder#data}
|
||||
* references a valid output buffer.
|
||||
* @return The result, which can be {@link SampleSource#SAMPLE_READ},
|
||||
* {@link SampleSource#FORMAT_READ}, {@link SampleSource#NOTHING_READ} or
|
||||
* {@link SampleSource#END_OF_STREAM}.
|
||||
*/
|
||||
protected final int readSource(long positionUs, MediaFormatHolder formatHolder,
|
||||
SampleHolder sampleHolder) {
|
||||
return enabledSource.readData(enabledSourceTrackIndex, positionUs, formatHolder, sampleHolder);
|
||||
}
|
||||
|
||||
// Abstract methods.
|
||||
|
||||
/**
|
||||
* Returns whether this renderer is capable of handling the provided track.
|
||||
*
|
||||
* @param mediaFormat The format of the track.
|
||||
* @return True if the renderer can handle the track, false otherwise.
|
||||
* @throws DecoderQueryException Thrown if there was an error querying decoders.
|
||||
*/
|
||||
protected abstract boolean handlesTrack(MediaFormat mediaFormat) throws DecoderQueryException;
|
||||
|
||||
/**
|
||||
* Invoked when a discontinuity is encountered. Also invoked when the renderer is enabled, for
|
||||
* convenience.
|
||||
*
|
||||
* @param positionUs The playback position after the discontinuity, or the position at which
|
||||
* the renderer is being enabled.
|
||||
* @throws ExoPlaybackException If an error occurs handling the discontinuity.
|
||||
*/
|
||||
protected abstract void onDiscontinuity(long positionUs) throws ExoPlaybackException;
|
||||
|
||||
/**
|
||||
* Called by {@link #doSomeWork(long, long)}.
|
||||
*
|
||||
* @param positionUs The current media time in microseconds, measured at the start of the
|
||||
* current iteration of the rendering loop.
|
||||
* @param elapsedRealtimeUs {@link android.os.SystemClock#elapsedRealtime()} in microseconds,
|
||||
* measured at the start of the current iteration of the rendering loop.
|
||||
* @param sourceIsReady The result of the most recent call to
|
||||
* {@link SampleSourceReader#continueBuffering(int, long)}.
|
||||
* @throws ExoPlaybackException If an error occurs.
|
||||
* @throws ExoPlaybackException
|
||||
*/
|
||||
protected abstract void doSomeWork(long positionUs, long elapsedRealtimeUs, boolean sourceIsReady)
|
||||
throws ExoPlaybackException;
|
||||
|
||||
// Private methods.
|
||||
|
||||
private long checkForDiscontinuity(long positionUs) throws ExoPlaybackException {
|
||||
long discontinuityPositionUs = enabledSource.readDiscontinuity(enabledSourceTrackIndex);
|
||||
if (discontinuityPositionUs != SampleSource.NO_DISCONTINUITY) {
|
||||
onDiscontinuity(discontinuityPositionUs);
|
||||
return discontinuityPositionUs;
|
||||
}
|
||||
return positionUs;
|
||||
}
|
||||
|
||||
private void maybeThrowError(SampleSourceReader source) throws ExoPlaybackException {
|
||||
try {
|
||||
source.maybeThrowError();
|
||||
} catch (IOException e) {
|
||||
throw new ExoPlaybackException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,301 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.b44t.messenger.exoplayer;
|
||||
|
||||
import com.b44t.messenger.exoplayer.SampleSource.SampleSourceReader;
|
||||
import com.b44t.messenger.exoplayer.upstream.DataSource;
|
||||
import com.b44t.messenger.exoplayer.upstream.DataSpec;
|
||||
import com.b44t.messenger.exoplayer.upstream.Loader;
|
||||
import com.b44t.messenger.exoplayer.upstream.Loader.Loadable;
|
||||
import com.b44t.messenger.exoplayer.util.Assertions;
|
||||
|
||||
import android.net.Uri;
|
||||
import android.os.Handler;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* A {@link SampleSource} that loads the data at a given {@link Uri} as a single sample.
|
||||
*/
|
||||
public final class SingleSampleSource implements SampleSource, SampleSourceReader, Loader.Callback,
|
||||
Loadable {
|
||||
|
||||
/**
|
||||
* Interface definition for a callback to be notified of {@link SingleSampleSource} events.
|
||||
*/
|
||||
public interface EventListener {
|
||||
|
||||
/**
|
||||
* Invoked when an error occurs loading media data.
|
||||
*
|
||||
* @param sourceId The id of the reporting {@link SampleSource}.
|
||||
* @param e The cause of the failure.
|
||||
*/
|
||||
void onLoadError(int sourceId, IOException e);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The default minimum number of times to retry loading data prior to failing.
|
||||
*/
|
||||
public static final int DEFAULT_MIN_LOADABLE_RETRY_COUNT = 3;
|
||||
|
||||
/**
|
||||
* The initial size of the allocation used to hold the sample data.
|
||||
*/
|
||||
private static final int INITIAL_SAMPLE_SIZE = 1;
|
||||
|
||||
private static final int STATE_SEND_FORMAT = 0;
|
||||
private static final int STATE_SEND_SAMPLE = 1;
|
||||
private static final int STATE_END_OF_STREAM = 2;
|
||||
|
||||
private final Uri uri;
|
||||
private final DataSource dataSource;
|
||||
private final MediaFormat format;
|
||||
private final int minLoadableRetryCount;
|
||||
private final Handler eventHandler;
|
||||
private final EventListener eventListener;
|
||||
private final int eventSourceId;
|
||||
|
||||
private int state;
|
||||
private byte[] sampleData;
|
||||
private int sampleSize;
|
||||
|
||||
private long pendingDiscontinuityPositionUs;
|
||||
private boolean loadingFinished;
|
||||
private Loader loader;
|
||||
private IOException currentLoadableException;
|
||||
private int currentLoadableExceptionCount;
|
||||
private long currentLoadableExceptionTimestamp;
|
||||
|
||||
public SingleSampleSource(Uri uri, DataSource dataSource, MediaFormat format) {
|
||||
this(uri, dataSource, format, DEFAULT_MIN_LOADABLE_RETRY_COUNT);
|
||||
}
|
||||
|
||||
public SingleSampleSource(Uri uri, DataSource dataSource, MediaFormat format,
|
||||
int minLoadableRetryCount) {
|
||||
this(uri, dataSource, format, minLoadableRetryCount, null, null, 0);
|
||||
}
|
||||
|
||||
public SingleSampleSource(Uri uri, DataSource dataSource, MediaFormat format,
|
||||
int minLoadableRetryCount, Handler eventHandler, EventListener eventListener,
|
||||
int eventSourceId) {
|
||||
this.uri = uri;
|
||||
this.dataSource = dataSource;
|
||||
this.format = format;
|
||||
this.minLoadableRetryCount = minLoadableRetryCount;
|
||||
this.eventHandler = eventHandler;
|
||||
this.eventListener = eventListener;
|
||||
this.eventSourceId = eventSourceId;
|
||||
sampleData = new byte[INITIAL_SAMPLE_SIZE];
|
||||
}
|
||||
|
||||
@Override
|
||||
public SampleSourceReader register() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean prepare(long positionUs) {
|
||||
if (loader == null) {
|
||||
loader = new Loader("Loader:" + format.mimeType);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTrackCount() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MediaFormat getFormat(int track) {
|
||||
return format;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enable(int track, long positionUs) {
|
||||
state = STATE_SEND_FORMAT;
|
||||
pendingDiscontinuityPositionUs = NO_DISCONTINUITY;
|
||||
clearCurrentLoadableException();
|
||||
maybeStartLoading();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean continueBuffering(int track, long positionUs) {
|
||||
maybeStartLoading();
|
||||
return loadingFinished;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void maybeThrowError() throws IOException {
|
||||
if (currentLoadableException != null && currentLoadableExceptionCount > minLoadableRetryCount) {
|
||||
throw currentLoadableException;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long readDiscontinuity(int track) {
|
||||
long discontinuityPositionUs = pendingDiscontinuityPositionUs;
|
||||
pendingDiscontinuityPositionUs = NO_DISCONTINUITY;
|
||||
return discontinuityPositionUs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int readData(int track, long positionUs, MediaFormatHolder formatHolder,
|
||||
SampleHolder sampleHolder) {
|
||||
if (state == STATE_END_OF_STREAM) {
|
||||
return END_OF_STREAM;
|
||||
} else if (state == STATE_SEND_FORMAT) {
|
||||
formatHolder.format = format;
|
||||
state = STATE_SEND_SAMPLE;
|
||||
return FORMAT_READ;
|
||||
}
|
||||
|
||||
Assertions.checkState(state == STATE_SEND_SAMPLE);
|
||||
if (!loadingFinished) {
|
||||
return NOTHING_READ;
|
||||
} else {
|
||||
sampleHolder.timeUs = 0;
|
||||
sampleHolder.size = sampleSize;
|
||||
sampleHolder.flags = C.SAMPLE_FLAG_SYNC;
|
||||
sampleHolder.ensureSpaceForWrite(sampleHolder.size);
|
||||
sampleHolder.data.put(sampleData, 0, sampleSize);
|
||||
state = STATE_END_OF_STREAM;
|
||||
return SAMPLE_READ;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void seekToUs(long positionUs) {
|
||||
if (state == STATE_END_OF_STREAM) {
|
||||
pendingDiscontinuityPositionUs = positionUs;
|
||||
state = STATE_SEND_SAMPLE;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getBufferedPositionUs() {
|
||||
return loadingFinished ? TrackRenderer.END_OF_TRACK_US : 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable(int track) {
|
||||
state = STATE_END_OF_STREAM;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release() {
|
||||
if (loader != null) {
|
||||
loader.release();
|
||||
loader = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Private methods.
|
||||
|
||||
private void maybeStartLoading() {
|
||||
if (loadingFinished || state == STATE_END_OF_STREAM || loader.isLoading()) {
|
||||
return;
|
||||
}
|
||||
if (currentLoadableException != null) {
|
||||
long elapsedMillis = SystemClock.elapsedRealtime() - currentLoadableExceptionTimestamp;
|
||||
if (elapsedMillis < getRetryDelayMillis(currentLoadableExceptionCount)) {
|
||||
return;
|
||||
}
|
||||
currentLoadableException = null;
|
||||
}
|
||||
loader.startLoading(this, this);
|
||||
}
|
||||
|
||||
private void clearCurrentLoadableException() {
|
||||
currentLoadableException = null;
|
||||
currentLoadableExceptionCount = 0;
|
||||
}
|
||||
|
||||
private long getRetryDelayMillis(long errorCount) {
|
||||
return Math.min((errorCount - 1) * 1000, 5000);
|
||||
}
|
||||
|
||||
// Loader.Callback implementation.
|
||||
|
||||
@Override
|
||||
public void onLoadCompleted(Loadable loadable) {
|
||||
loadingFinished = true;
|
||||
clearCurrentLoadableException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoadCanceled(Loadable loadable) {
|
||||
// Never happens.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoadError(Loadable loadable, IOException e) {
|
||||
currentLoadableException = e;
|
||||
currentLoadableExceptionCount++;
|
||||
currentLoadableExceptionTimestamp = SystemClock.elapsedRealtime();
|
||||
notifyLoadError(e);
|
||||
maybeStartLoading();
|
||||
}
|
||||
|
||||
// Loadable implementation.
|
||||
|
||||
@Override
|
||||
public void cancelLoad() {
|
||||
// Never happens.
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLoadCanceled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() throws IOException, InterruptedException {
|
||||
// We always load from the beginning, so reset the sampleSize to 0.
|
||||
sampleSize = 0;
|
||||
try {
|
||||
// Create and open the input.
|
||||
dataSource.open(new DataSpec(uri));
|
||||
// Load the sample data.
|
||||
int result = 0;
|
||||
while (result != C.RESULT_END_OF_INPUT) {
|
||||
sampleSize += result;
|
||||
if (sampleSize == sampleData.length) {
|
||||
sampleData = Arrays.copyOf(sampleData, sampleData.length * 2);
|
||||
}
|
||||
result = dataSource.read(sampleData, sampleSize, sampleData.length - sampleSize);
|
||||
}
|
||||
} finally {
|
||||
dataSource.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyLoadError(final IOException e) {
|
||||
if (eventHandler != null && eventListener != null) {
|
||||
eventHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
eventListener.onLoadError(eventSourceId, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user