Skip to content
This repository has been archived by the owner on Feb 6, 2023. It is now read-only.

Commit

Permalink
fix: 并发解析 svga 文件时极大概率出现解析失败
Browse files Browse the repository at this point in the history
  • Loading branch information
caiyuwei committed Jun 9, 2020
1 parent 7378862 commit 94a8616
Showing 1 changed file with 33 additions and 29 deletions.
62 changes: 33 additions & 29 deletions library/src/main/java/com/opensource/svgaplayer/SVGAParser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import java.util.zip.ZipInputStream
*/

private var fileLock: Int = 0
private var isUnzipping = false

class SVGAParser(context: Context?) {
private var mContextRef = WeakReference<Context?>(context)
Expand Down Expand Up @@ -135,14 +136,19 @@ class SVGAParser(context: Context?) {
try {
readAsBytes(inputStream)?.let { bytes ->
if (bytes.size > 4 && bytes[0].toInt() == 80 && bytes[1].toInt() == 75 && bytes[2].toInt() == 3 && bytes[3].toInt() == 4) {
if (!buildCacheDir(cacheKey).exists()) {
ByteArrayInputStream(bytes).use {
unzip(it, cacheKey)
if (!buildCacheDir(cacheKey).exists() || isUnzipping) {
synchronized(fileLock) {
if (!buildCacheDir(cacheKey).exists()) {
isUnzipping = true
ByteArrayInputStream(bytes).use {
unzip(it, cacheKey)
isUnzipping = false
}
}
}
}
this.decodeFromCacheKey(cacheKey, callback)
}
else {
} else {
inflate(bytes)?.let {
val videoItem = SVGAVideoEntity(MovieEntity.ADAPTER.decode(it), File(cacheKey))
videoItem.prepare {
Expand Down Expand Up @@ -306,36 +312,34 @@ class SVGAParser(context: Context?) {
}

private fun unzip(inputStream: InputStream, cacheKey: String) {
synchronized(fileLock) {
val cacheDir = this.buildCacheDir(cacheKey)
cacheDir.mkdirs()
try {
BufferedInputStream(inputStream).use {
ZipInputStream(it).use { zipInputStream ->
while (true) {
val zipItem = zipInputStream.nextEntry ?: break
if (zipItem.name.contains("/")) {
continue
}
val file = File(cacheDir, zipItem.name)
FileOutputStream(file).use { fileOutputStream ->
val buff = ByteArray(2048)
while (true) {
val readBytes = zipInputStream.read(buff)
if (readBytes <= 0) {
break
}
fileOutputStream.write(buff, 0, readBytes)
val cacheDir = this.buildCacheDir(cacheKey)
cacheDir.mkdirs()
try {
BufferedInputStream(inputStream).use {
ZipInputStream(it).use { zipInputStream ->
while (true) {
val zipItem = zipInputStream.nextEntry ?: break
if (zipItem.name.contains("/")) {
continue
}
val file = File(cacheDir, zipItem.name)
FileOutputStream(file).use { fileOutputStream ->
val buff = ByteArray(2048)
while (true) {
val readBytes = zipInputStream.read(buff)
if (readBytes <= 0) {
break
}
fileOutputStream.write(buff, 0, readBytes)
}
zipInputStream.closeEntry()
}
zipInputStream.closeEntry()
}
}
} catch (e: Exception) {
cacheDir.delete()
throw e
}
} catch (e: Exception) {
cacheDir.delete()
throw e
}
}
}

0 comments on commit 94a8616

Please sign in to comment.