commit 922ec80bcc458f99d1382adb608b072eca5cf502 Author: tongtongstudio Date: Mon Nov 30 17:36:17 2026 +0800 初始化 TTVideoPlayer 工程:模块化播放框架、同同影音 App 与文档 Media3 内核播放框架(player-api/core/media3/source/render/lifecycle/telemetry)、 WebDAV/SMB/Jellyfin 来源、DLNA/Google Cast 投屏、RTMP 原生库与完整 App。 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b9b50d4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +**/build/ +.gradle/ +.kotlin/ +.idea/ +local.properties +*.iml +**/.cxx/ +# 构建产物与发布包 +dist/ +*.apk +*.zip diff --git a/README.md b/README.md new file mode 100644 index 0000000..1afcab1 --- /dev/null +++ b/README.md @@ -0,0 +1,85 @@ +# TTVideoPlayer + +面向 Android 6.0(API 23)及以上设备的模块化播放框架。默认内核为 AndroidX Media3 ExoPlayer,业务接口不依赖 Media3。低端机优先硬解与 SurfaceView,后续可通过适配器引入其他内核。 + +现已提供完整应用 **同同影音**(`app` module):首页、来源、历史/收藏、设置、目录浏览和播放页。使用方法与实现边界见 [App 使用与设计](docs/app.md)。安装包:`dist/TTVideoPlayer-1.0.0-debug.apk`。`app-demo` 保留为框架接入示例,两个宿主共用 applicationId,安装时相互升级覆盖。 + +## 模块 + +| module | 职责 | 依赖 | +| --- | --- | --- | +| player-api | 纯 Kotlin/JVM 播放契约、状态、事件、轨道、能力模型 | coroutines-core | +| player-core | 共享输入校验和解码策略能力校验 | player-api | +| player-android-api | Surface 输出契约,不绑定具体 View | player-api | +| player-media3 | 可运行的 Media3 内核、解码器筛选、首帧与错误事件 | core、android-api | +| player-media3-source | HTTP(S)、HLS、DASH、SmoothStreaming、FLV、RTMP、RTSP 路由与网络配置 | core、Media3 协议模块 | +| player-rtmp-native | 固定上游源码重建的 RTMP 播放 JNI,四 ABI、16 KB ELF 对齐 | NDK、CMake | +| player-render-android | SurfaceView/TextureView 的输出绑定与所有权 | android-api | +| player-lifecycle | 前后台暂停恢复及销毁释放 | player-api、Lifecycle | +| player-telemetry | 结构化日志与埋点回调,不包含媒体地址 | player-api | +| app-demo | 输入 URL、播放暂停、硬软解策略及渲染切换示例 | 上述功能模块 | +| app | 完整应用、加密历史、来源浏览、队列、字幕 UI、DLNA 前台服务 | 播放/来源/投屏模块 | +| library-api | 来源、媒体条目、播放解析与观看会话契约 | player-api | +| library-http | 可取消 HTTP 请求、限量响应与安全 XML 解析 | library-api、OkHttp | +| library-webdav | Basic/匿名 WebDAV、目录与字幕匹配 | library-http | +| library-smb | SMB2/3 浏览与随机读取句柄 | library-api、SMBJ | +| library-jellyfin | 登录、媒体库分页、播放协商与进度同步 | library-http | +| library-storage | Android Keystore 加密账户、稳定标识书签 | library-api | +| library-media3 | SMB DataSource 插件、续播/观看会话协调 | 来源 API、Media3 | +| player-cast-api | 投屏决策、接收端媒体模型与 Range 规则 | player-api | +| player-cast-dlna | SSDP 发现、AVTransport SOAP 控制 | cast-api、library-http | +| player-cast-relay | 局域网 token 文件代理、HEAD/Range | cast-api、Media3 数据源 | +| player-cast-google | Media3 CastPlayer、媒体服务、投屏验证页 | Media3 Cast/Session/UI | + +API/core/telemetry 目前是 JVM module,不是已完成的 Kotlin Multiplatform 库。共享模型不暴露 Android 类型,未来转为 KMP 时还需要迁移构建脚本和 URI 校验等平台实现。 + +## 构建运行 + +需要 JDK 17、Android SDK 36、NDK 28.2.13676358、CMake 3.22.1、网络可用的 Google Maven/Maven Central。Gradle Wrapper 为 8.13,AGP 8.13.2,Kotlin 2.3.0,Media3 1.11.1。版本为本项目固定版本,不自动跟随 latest。RTMP native 依赖与本地修改见 [构建记录](player-rtmp-native/LOCAL-CHANGES.md)。 + +在 `local.properties` 设置自己的 `sdk.dir`(文件不入库),或配置 `ANDROID_HOME`。 + +```powershell +.\gradlew.bat :app:assembleDebug :app:lintDebug :app:testDebugUnitTest +.\gradlew.bat :app-demo:assembleDebug :player-core:test :app-demo:lintDebug +.\gradlew.bat :player-media3:testDebugUnitTest :player-lifecycle:testDebugUnitTest +.\gradlew.bat :player-media3-source:testDebugUnitTest +``` + +Android Studio 直接打开本目录,运行 `app`。完整应用通过系统文件选择器(SAF)打开本地视频,无需全盘存储权限。应用与 Demo 为兼容局域网 NAS 的 HTTP 服务开放明文 HTTP;library 不改变宿主网络安全策略。公网连接应使用 HTTPS。网络链接支持选择媒体协议、HTTP 请求头与 RTSP TCP。 + +官方 Maven 网络不可达时,可以在命令末尾添加 `-PdependencyMirror=https://maven.aliyun.com/repository/public`。镜像为可选项;依赖源码和版本仍由各 module 的构建文件固定。 + +## 接入 + +```kotlin +// 主线程创建,建议传入 applicationContext。 +val engine = Media3Engine(applicationContext) +val output = SurfaceViewBinding(surfaceView, engine) +val lifecycle = PlaybackLifecycleBinding(this, engine) +val telemetry = PlaybackTelemetry(engine, lifecycleScope, sessionId, sink) + +// 应先订阅 state/events,再 prepare;prepare 成功不代表已经显示首帧。 +lifecycleScope.launch { + engine.prepare(PlaybackRequest(uri = url, autoplay = true)) +} +// 用户按钮通过 lifecycle.playByUser()/pauseByUser() 保持恢复意图一致。 +// View 销毁时 output.close();采集结束时 telemetry.close()。 +// 默认生命周期绑定在 Activity/Fragment owner ON_DESTROY 释放 engine。 +``` + +Fragment 渲染应绑定 viewLifecycleOwner,且在 onDestroyView 关闭输出;若播放器由 ViewModel 或服务持有,传入 `releaseOnDestroy=false`,最终所有者必须调用 `release()`。完整 App 的本机视频进入后台暂停;DLNA 使用前台媒体服务,Google Cast 使用 MediaSessionService。 + +## 文档 + +- [App 使用与设计](docs/app.md) +- [框架选型与边界](docs/framework-selection.md) +- [接口契约与架构](docs/architecture.md) +- [设备验证与已知限制](docs/validation.md) +- [在线协议接入](docs/online-protocols.md) +- [WebDAV、SMB 与 Jellyfin](docs/media-libraries.md) +- [DLNA 与 Google Cast](docs/casting.md) + +0.3.0 Demo 增加「来源管理」入口,支持添加/编辑/删除来源、目录浏览、外挂字幕选择、音轨选择、拖动和续播。先加载视频,再选择 DLNA 或 Google Cast 投屏。SMB 请在来源管理中配置共享地址,不要在手动播放框直接填写 smb://。 + +当前仅实现 Media3 内核。FSPlayer/libmpv 的选型与适配要求见文档,没有空实现冒充可用内核,也没有自动跨内核回退。 diff --git a/app-demo/build.gradle.kts b/app-demo/build.gradle.kts new file mode 100644 index 0000000..be4d2a1 --- /dev/null +++ b/app-demo/build.gradle.kts @@ -0,0 +1,46 @@ +plugins { + id("com.android.application") + kotlin("android") +} + +android { + namespace = "com.ttstd.player.appdemo" + compileSdk = 37 + + defaultConfig { + minSdk = 23 + targetSdk = 37 + applicationId = "com.ttstd.player.demo" + versionCode = 3 + versionName = "0.3.0" + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} + +kotlin { jvmToolchain(17) } + +dependencies { + implementation(project(":library-api")) + implementation(project(":library-webdav")) + implementation(project(":library-smb")) + implementation(project(":library-jellyfin")) + implementation(project(":library-storage")) + implementation(project(":library-media3")) + implementation(project(":player-media3-source")) + implementation(project(":player-cast-api")) + implementation(project(":player-cast-dlna")) + implementation(project(":player-cast-relay")) + implementation(project(":player-cast-google")) + implementation("androidx.appcompat:appcompat:1.7.1") + implementation(project(":player-core")) + implementation(project(":player-media3")) + implementation(project(":player-render-android")) + implementation(project(":player-lifecycle")) + implementation(project(":player-telemetry")) + implementation("androidx.activity:activity-ktx:1.10.1") + implementation("androidx.core:core-ktx:1.16.0") +} diff --git a/app-demo/src/main/AndroidManifest.xml b/app-demo/src/main/AndroidManifest.xml new file mode 100644 index 0000000..46869f3 --- /dev/null +++ b/app-demo/src/main/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/app-demo/src/main/kotlin/com/ttstd/player/demo/DemoCasting.kt b/app-demo/src/main/kotlin/com/ttstd/player/demo/DemoCasting.kt new file mode 100644 index 0000000..8e5c245 --- /dev/null +++ b/app-demo/src/main/kotlin/com/ttstd/player/demo/DemoCasting.kt @@ -0,0 +1,158 @@ +package com.ttstd.player.demo + +import android.app.AlertDialog +import android.content.Context +import android.widget.* +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.lifecycleScope +import com.ttstd.player.api.* +import com.ttstd.player.cast.* +import com.ttstd.player.cast.dlna.* +import com.ttstd.player.cast.google.* +import com.ttstd.player.cast.relay.CastRelay +import com.ttstd.player.library.LibraryPlayback +import com.ttstd.player.library.media3.LibraryPlaybackTracker +import com.ttstd.player.library.storage.PlaybackBookmarks +import kotlinx.coroutines.* +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** 投屏期间接管媒体服务进度;只持有 Application Context,不保留界面。 */ +private class SourceCastObserver(context: Context, private val playback: LibraryPlayback) : CastProgressObserver { + private val bookmarks = PlaybackBookmarks(context.applicationContext) + override suspend fun started(positionMs: Long) { playback.session?.started(positionMs) } + override suspend fun progress(state: RemotePlaybackState) { + bookmarks.save(playback.stableId, state.positionMs + playback.positionOffsetMs, playback.originalDurationMs ?: state.durationMs?.plus(playback.positionOffsetMs)) + playback.session?.progress(state.positionMs, !state.playing) + } + override suspend fun stopped(positionMs: Long) { + bookmarks.save(playback.stableId, positionMs + playback.positionOffsetMs, playback.originalDurationMs) + playback.session?.stopped(positionMs) + } +} + +/** Demo 的投屏编排:DLNA 控制和 Google Cast 服务都复用来源解析结果。 + * DLNA relay 随本验证页面销毁而关闭;Google Cast relay 交给服务持有。 + */ +class DemoCasting( + private val activity: AppCompatActivity, + private val engine: PlayerEngine, + private val tracker: LibraryPlaybackTracker, + private val current: () -> LibraryPlayback?, + private val launchGoogle: (android.content.Intent) -> Unit, + private val resumeLocal: suspend (Long, Boolean) -> Unit, + private val message: (String) -> Unit, +) : AutoCloseable { + private val relay = CastRelay(activity.applicationContext) + private val dlna = DlnaController(activity.applicationContext) + private val mutex = Mutex() + private var device: DlnaDevice? = null + private var observer: CastProgressObserver? = null + private var polling: Job? = null + private var state = RemotePlaybackState() + private var googleActive = false + val isRemote: Boolean get() = device != null || googleActive + + private fun media(playback: LibraryPlayback): CastMedia { + val request = playback.receiverRequest ?: playback.request + val decision = CastPolicy.assess(request) + if (decision.route == CastRoute.UNSUPPORTED) throw IllegalArgumentException(decision.reason) + val uri = if (decision.route == CastRoute.DIRECT) request.uri else relay.publish(request, decision.mimeType, playback.contentLength) + return CastMedia(uri, playback.title, decision.mimeType, engine.state.value.positionMs) + } + suspend fun google() { + val playback = current() ?: return message("请先加载视频") + if (device != null) stop(false) + try { + val media = media(playback) + tracker.detach(); engine.pause() + val sharedRelay = relay + GoogleCastResources.hold(SourceCastObserver(activity.applicationContext, playback), sharedRelay::close) + googleActive = true + launchGoogle(GoogleCastActivity.intent(activity, media)) + } catch (e: Exception) { message(e.message ?: "无法启动投屏") } + } + suspend fun googleReturned(positionMs: Long?, playing: Boolean) { + if (!googleActive) return + googleActive = false + relay.close() + resumeLocal(positionMs ?: engine.state.value.positionMs, playing) + } + suspend fun discoverDlna() { + if (current() == null) return message("请先加载视频") + message("正在搜索 DLNA 设备…") + try { + val devices = dlna.discover() + if (devices.isEmpty()) return message("没有发现 DLNA 设备,请确认电视和手机在同一局域网且已开启投屏") + AlertDialog.Builder(activity).setTitle("选择 DLNA 设备").setItems(devices.map { it.name }.toTypedArray()) { _, index -> + activity.lifecycleScope.launch { connect(devices[index]) } + }.setNegativeButton("取消", null).show() + } catch (_: Exception) { message("DLNA 搜索失败,请检查局域网权限和网络") } + } + private suspend fun connect(target: DlnaDevice) { + val playback = current() ?: return + if (device != null) stop(false) + try { + val media = media(playback) + mutex.withLock { dlna.load(target, media) } + device = target + state = RemotePlaybackState(media.startPositionMs, engine.state.value.durationMs, true) + tracker.detach(); engine.pause() + observer = SourceCastObserver(activity.applicationContext, playback) + runCatching { observer?.started(state.positionMs) } + polling = activity.lifecycleScope.launch { + var count = 0 + while (isActive) { + try { + state = mutex.withLock { dlna.state(target) } + if (count++ % 3 == 0) observer?.progress(state) + message("DLNA · ${target.name} · ${state.positionMs / 1000}s") + } catch (cancelled: CancellationException) { throw cancelled } + catch (_: Exception) { message("DLNA 状态读取失败,可重试控制或结束投屏") } + delay(3000) + } + } + showDlnaControls() + } catch (cancelled: CancellationException) { relay.close(); throw cancelled } + catch (e: Exception) { + runCatching { mutex.withLock { dlna.stop(target) } } + relay.close(); message(e.message ?: "DLNA 连接失败") + } + } + fun showDlnaControls() { + val target = device ?: return + val controls = arrayOf("播放", "暂停", "后退 30 秒", "前进 30 秒", "结束并返回本机") + AlertDialog.Builder(activity).setTitle("DLNA · ${target.name}").setItems(controls) { _, index -> + activity.lifecycleScope.launch { + try { + when (index) { + 0 -> mutex.withLock { dlna.play(target) } + 1 -> mutex.withLock { dlna.pause(target) } + 2 -> mutex.withLock { dlna.seek(target, (state.positionMs - 30_000).coerceAtLeast(0)) } + 3 -> mutex.withLock { dlna.seek(target, state.positionMs + 30_000) } + else -> stop(true) + } + } catch (_: Exception) { message("电视未接受该控制操作") } + } + }.setNegativeButton("关闭", null).show() + } + suspend fun stop(resume: Boolean) { + val old = device ?: return + polling?.cancelAndJoin(); polling = null + val finalState = runCatching { mutex.withLock { dlna.state(old) } }.getOrDefault(state) + runCatching { mutex.withLock { dlna.stop(old) } } + runCatching { observer?.stopped(finalState.positionMs) } + observer = null; device = null; relay.close() + if (resume) resumeLocal(finalState.positionMs, finalState.playing) + } + override fun close() { + polling?.cancel() + if (!googleActive) relay.close() + val oldDevice = device + val oldObserver = observer + if (oldDevice != null) CoroutineScope(Dispatchers.IO).launch { + withTimeoutOrNull(5000) { runCatching { dlna.stop(oldDevice) }; runCatching { oldObserver?.stopped(state.positionMs) } } + } + device = null; observer = null + } +} diff --git a/app-demo/src/main/kotlin/com/ttstd/player/demo/LibraryActivity.kt b/app-demo/src/main/kotlin/com/ttstd/player/demo/LibraryActivity.kt new file mode 100644 index 0000000..6c85425 --- /dev/null +++ b/app-demo/src/main/kotlin/com/ttstd/player/demo/LibraryActivity.kt @@ -0,0 +1,179 @@ +package com.ttstd.player.demo + +import android.app.AlertDialog +import android.content.Intent +import android.os.Bundle +import android.text.InputType +import android.widget.* +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.lifecycle.lifecycleScope +import com.ttstd.player.library.* +import com.ttstd.player.library.webdav.WebDavLibrary +import com.ttstd.player.library.smb.SmbLibrary +import com.ttstd.player.library.jellyfin.JellyfinLibrary +import com.ttstd.player.library.storage.* +import kotlinx.coroutines.* +import java.net.URI +import java.util.UUID + +/** 来源管理和目录浏览验证页。所有网络/加密 IO 均离开主线程。 */ +class LibraryActivity : AppCompatActivity() { + private lateinit var status: TextView + private lateinit var list: ListView + private lateinit var more: Button + private lateinit var accounts: LibraryAccounts + private var provider: MediaLibrary? = null + private val folders = mutableListOf>() + private val entries = mutableListOf() + private var nextOffset: Int? = null + private var loadJob: Job? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + accounts = LibraryAccounts(this) + val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } + ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets -> + val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime()) + view.setPadding(16 + bars.left, bars.top, 16 + bars.right, bars.bottom); insets + } + status = TextView(this) + root.addView(status) + root.addView(Button(this).apply { text = "添加来源:WebDAV / SMB / Jellyfin"; setOnClickListener { editAccount() } }) + root.addView(Button(this).apply { text = "上一级 / 返回来源"; setOnClickListener { up() } }) + list = ListView(this) + root.addView(list, LinearLayout.LayoutParams(-1, 0, 1f)) + more = Button(this).apply { text = "加载更多"; setOnClickListener { load(nextOffset ?: 0) } } + root.addView(more) + setContentView(root) + showAccounts() + onBackPressedDispatcher.addCallback(this, object : androidx.activity.OnBackPressedCallback(true) { + override fun handleOnBackPressed() { if (provider == null) finish() else up() } + }) + } + private fun showAccounts() { + loadJob?.cancel(); provider = null; folders.clear(); more.isEnabled = false + loadJob = lifecycleScope.launch { + try { + val saved = withContext(Dispatchers.IO) { accounts.all() } + status.text = "媒体来源(长按可编辑或删除)" + list.adapter = ArrayAdapter(this@LibraryActivity, android.R.layout.simple_list_item_1, saved.map { "${it.name} · ${it.kind}" }) + list.setOnItemClickListener { _, _, position, _ -> open(saved[position]) } + list.setOnItemLongClickListener { _, _, position, _ -> + val account = saved[position] + AlertDialog.Builder(this@LibraryActivity).setTitle(account.name).setItems(arrayOf("编辑", "删除")) { _, choice -> + if (choice == 0) editAccount(account) else AlertDialog.Builder(this@LibraryActivity).setMessage("删除这个来源配置?") + .setPositiveButton("删除") { _, _ -> lifecycleScope.launch { withContext(Dispatchers.IO) { accounts.delete(account.id) }; showAccounts() } } + .setNegativeButton("取消", null).show() + }.show() + true + } + } catch (_: Exception) { status.text = "无法读取来源配置;设备密钥变化时需要重新配置账户" } + } + } + private fun open(account: LibraryAccount) { + provider = when (account.kind) { LibraryKind.WEBDAV -> WebDavLibrary(account); LibraryKind.SMB -> SmbLibrary(account); LibraryKind.JELLYFIN -> JellyfinLibrary(account) } + folders.clear(); folders += "" to account.name + list.onItemLongClickListener = null + load() + } + private fun up() { + if (folders.size <= 1) showAccounts() else { folders.removeAt(folders.lastIndex); load() } + } + private fun load(offset: Int = 0) { + loadJob?.cancel() + val library = provider ?: return + val folder = folders.lastOrNull()?.first.orEmpty() + loadJob = lifecycleScope.launch { + status.text = "正在加载…"; more.isEnabled = false + try { + val page = library.list(folder, offset) + if (offset == 0) entries.clear() + entries += page.entries + nextOffset = page.nextOffset + status.text = "${folders.lastOrNull()?.second} · ${entries.size} 项" + list.adapter = ArrayAdapter(this@LibraryActivity, android.R.layout.simple_list_item_1, + entries.map { (if (it.isFolder) "[目录] " else "") + it.name }) + list.setOnItemClickListener { _, _, position, _ -> + val entry = entries[position] + if (entry.isFolder) { folders += entry.id to entry.name; load() } + else if (library.account.kind == LibraryKind.JELLYFIN || LibraryFiles.isVideo(entry.name)) play(entry) + else Toast.makeText(this@LibraryActivity, "请选择视频;同名外挂字幕会自动匹配", Toast.LENGTH_SHORT).show() + } + more.isEnabled = nextOffset != null + } catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { status.text = safeError(e) } + } + } + private fun play(entry: LibraryEntry) { + val library = provider ?: return + loadJob?.cancel() + loadJob = lifecycleScope.launch { + status.text = "正在获取播放地址…" + try { + var playback = library.resolve(entry, LibraryPlaybackOptions(startPositionMs = entry.resumeMs)) + val bookmark = withContext(Dispatchers.IO) { PlaybackBookmarks(this@LibraryActivity).position(playback.stableId) } + val start = if (bookmark > 0) bookmark else entry.resumeMs + playback = if (library.account.kind == LibraryKind.JELLYFIN && start != entry.resumeMs) + library.resolve(entry, LibraryPlaybackOptions(startPositionMs = start)) + else playback.copy(request = playback.request.copy(startPositionMs = if (playback.positionOffsetMs == 0L) start else 0)) + val selected = playback + if (playback.subtitles.isEmpty()) deliver(playback) else { + val choices = arrayOf("不使用外挂字幕") + playback.subtitles.map { android.net.Uri.parse(it.uri).lastPathSegment ?: "字幕" } + AlertDialog.Builder(this@LibraryActivity).setTitle("选择外挂字幕").setItems(choices) { _, index -> + deliver(selected.copy(request = selected.request.copy(subtitles = if (index == 0) emptyList() else listOf(selected.subtitles[index - 1])))) + }.setNegativeButton("取消", null).show() + status.text = "请选择字幕" + } + } catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { status.text = safeError(e) } + } + } + private fun deliver(playback: LibraryPlayback) { + val ticket = LibraryPlaybackInbox.put(playback) + startActivity(Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP).putExtra("libraryTicket", ticket)) + finish() + } + private fun editAccount(existing: LibraryAccount? = null) { + val form = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(24, 8, 24, 8) } + val kinds = LibraryKind.entries + val kind = Spinner(this).apply { adapter = ArrayAdapter(this@LibraryActivity, android.R.layout.simple_spinner_dropdown_item, kinds.map { it.name }); setSelection(kinds.indexOf(existing?.kind ?: LibraryKind.WEBDAV)) } + form.addView(kind) + fun field(hint: String, value: String = "", secret: Boolean = false): EditText = EditText(this).apply { + this.hint = hint; isSaveEnabled = false; setSingleLine(true) + inputType = InputType.TYPE_CLASS_TEXT or if (secret) InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS + setText(value); form.addView(this) + } + val name = field("来源名称", existing?.name.orEmpty()) + val endpoint = field("https://host/dav/ 或 smb://host/share/ 或 Jellyfin 服务根地址", existing?.endpoint.orEmpty()) + val user = field("用户名(匿名 WebDAV/SMB 可留空)", existing?.username.orEmpty()) + val password = field("密码", existing?.password.orEmpty(), true) + val domain = field("SMB 域(可留空)", existing?.domain.orEmpty()) + val error = TextView(this); form.addView(error) + val dialog = AlertDialog.Builder(this).setTitle(if (existing == null) "添加来源" else "编辑来源") + .setView(ScrollView(this).apply { addView(form) }).setPositiveButton("保存", null).setNegativeButton("取消", null).create() + dialog.setOnShowListener { + dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + val selected = kinds[kind.selectedItemPosition] + val uri = runCatching { URI(endpoint.text.toString().trim()) }.getOrNull() + if (name.text.isBlank() || uri?.host == null || uri.userInfo != null || uri.rawQuery != null || + (selected == LibraryKind.SMB && (uri.scheme != "smb" || uri.path.trim('/').isBlank())) || + (selected != LibraryKind.SMB && uri.scheme !in setOf("http", "https"))) { + error.text = "请填写名称和正确的来源根地址;用户名/密码请填写在独立字段"; return@setOnClickListener + } + val account = LibraryAccount(existing?.id ?: UUID.randomUUID().toString(), name.text.toString(), selected, + uri.toASCIIString(), user.text.toString(), password.text.toString(), domain.text.toString()) + lifecycleScope.launch { + try { withContext(Dispatchers.IO) { accounts.save(account) }; dialog.dismiss(); showAccounts() } + catch (_: Exception) { error.text = "来源保存失败,请检查设备密钥存储" } + } + } + } + dialog.show() + } + private fun safeError(error: Exception): String = when (error) { + is LibraryException -> error.message ?: "来源请求失败" + else -> "来源操作失败,请检查地址、账户和服务器配置" + } +} diff --git a/app-demo/src/main/kotlin/com/ttstd/player/demo/MainActivity.kt b/app-demo/src/main/kotlin/com/ttstd/player/demo/MainActivity.kt new file mode 100644 index 0000000..c9f1902 --- /dev/null +++ b/app-demo/src/main/kotlin/com/ttstd/player/demo/MainActivity.kt @@ -0,0 +1,266 @@ +package com.ttstd.player.demo + +import android.os.Bundle +import android.app.AlertDialog +import android.content.Intent +import android.util.Log +import android.view.* +import android.widget.* +import androidx.appcompat.app.AppCompatActivity +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.lifecycle.lifecycleScope +import com.ttstd.player.api.* +import com.ttstd.player.core.HttpHeaders +import com.ttstd.player.core.SourceRouting +import com.ttstd.player.library.LibraryPlayback +import com.ttstd.player.library.media3.LibraryPlaybackTracker +import com.ttstd.player.library.storage.PlaybackBookmarks +import com.ttstd.player.media3.source.Media3TransportRegistry +import com.ttstd.player.media3.source.Media3FileCache +import com.ttstd.player.lifecycle.PlaybackLifecycleBinding +import com.ttstd.player.media3.Media3Engine +import com.ttstd.player.render.* +import com.ttstd.player.telemetry.* +import kotlinx.coroutines.launch +import java.util.UUID + +/** 最小集成示例:输入地址、切换渲染宿主和解码策略。正式业务自行实现控制 UI。 */ +class MainActivity : AppCompatActivity() { + private lateinit var engine: Media3Engine + private lateinit var lifecycleBinding: PlaybackLifecycleBinding + private lateinit var telemetry: PlaybackTelemetry + private var outputBinding: AutoCloseable? = null + private lateinit var videoHost: FrameLayout + private var useTexture = false + private var videoRatio = 16f / 9f + private var sourceType = MediaSourceType.AUTO + private var network = NetworkOptions() + private var headers: Map = emptyMap() + private lateinit var tracker: LibraryPlaybackTracker + private lateinit var casting: DemoCasting + private lateinit var playbackStatus: TextView + private var currentPlayback: LibraryPlayback? = null + private val googleLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + lifecycleScope.launch { + val data = result.data + casting.googleReturned(data?.getLongExtra("position", 0), data?.getBooleanExtra("playing", true) ?: true) + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + engine = Media3Engine(applicationContext) + tracker = LibraryPlaybackTracker(applicationContext, engine, lifecycleScope) + lifecycleBinding = PlaybackLifecycleBinding(this, engine) + telemetry = PlaybackTelemetry(engine, lifecycleScope, UUID.randomUUID().toString(), TelemetrySink { name, attrs -> + Log.d("TTVideoPlayer", "$name $attrs") + }) + val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(16, 0, 16, 0) } + // API 35+ edge-to-edge:给控制区域应用系统栏 inset,避免按钮被遮挡。 + ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets -> + val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime()) + view.setPadding(16 + bars.left, bars.top, 16 + bars.right, bars.bottom) + insets + } + val address = EditText(this).apply { + hint = "https://… / http://… / rtsp://… / rtmp://…" + isSaveEnabled = false // 地址可能包含 RTSP 凭证,不写入实例状态。 + setSingleLine(true) + setText(savedInstanceState?.getString("uri") ?: "https://storage.googleapis.com/exoplayer-test-media-0/BigBuckBunny_320x180.mp4") + } + // 控件放在可滚动区域,小屏与横屏仍可访问连接设置。 + val controls = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } + val scroll = ScrollView(this).apply { addView(controls) } + root.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f)) + controls.addView(address) + fun button(label: String, action: suspend () -> Unit) { + controls.addView(Button(this).apply { text = label; setOnClickListener { lifecycleScope.launch { action() } } }) + } + val status = TextView(this) + playbackStatus = status + casting = DemoCasting(this, engine, tracker, { currentPlayback }, { googleLauncher.launch(it) }, + { position, playing -> resumeLocal(position, playing) }, { status.text = it }) + button("来源管理:WebDAV / SMB / Jellyfin") { startActivity(Intent(this, LibraryActivity::class.java)) } + button("加载并播放") { + val uri = address.text.toString().trim() + val position = PlaybackBookmarks(this).position("manual:$uri") + play(LibraryPlayback(PlaybackRequest(uri, headers = headers, autoplay = true, sourceType = sourceType, + network = network, startPositionMs = position), "manual:$uri", "手动地址")) + } + button("连接设置:协议 / 请求头 / RTSP TCP") { showConnectionSettings() } + button("播放 / 暂停") { + if (casting.isRemote) casting.showDlnaControls() + else if (engine.state.value.playWhenReady) lifecycleBinding.pauseByUser() else lifecycleBinding.playByUser() + } + button("DLNA 投屏:搜索电视") { casting.discoverDlna() } + button("DLNA 播放控制 / 返回本机") { casting.showDlnaControls() } + button("Google Cast 投屏") { casting.google() } + button("选择音轨 / 字幕") { + val tracks = engine.state.value.tracks + val labels = arrayOf("关闭字幕") + tracks.map { "${it.type} · ${it.label ?: it.language ?: it.id}${if (it.selected) " ✓" else ""}" } + AlertDialog.Builder(this).setTitle("音轨和字幕").setItems(labels) { _, index -> + lifecycleScope.launch { + val result = if (index == 0) engine.selectTrack(TrackSelection(TrackType.TEXT, disabled = true)) + else tracks[index - 1].let { engine.selectTrack(TrackSelection(it.type, it.id)) } + if (result != CommandResult.Accepted) status.text = result.toString() + } + }.show() + } + val seek = SeekBar(this).apply { max = 1000 } + controls.addView(seek) + var seeking = false + seek.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { + override fun onStartTrackingTouch(seekBar: SeekBar) { seeking = true } + override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) = Unit + override fun onStopTrackingTouch(seekBar: SeekBar) { + seeking = false + if (casting.isRemote) return + val current = currentPlayback + val duration = current?.originalDurationMs ?: engine.state.value.durationMs?.plus(current?.positionOffsetMs ?: 0) ?: return + val position = duration * seekBar.progress / 1000 + val refresher = current?.refresh + lifecycleScope.launch { + if (current != null && current.positionOffsetMs > 0 && refresher != null) { + try { val refreshed = refresher.invoke(position); play(refreshed) } + catch (_: Exception) { status.text = "服务端拖动播放失败" } + } else { + val result = engine.seekTo(position) + if (result != CommandResult.Accepted) status.text = result.toString() + } + } + } + }) + val modes = DecodeMode.entries + val selector = Spinner(this).apply { adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, modes.map { it.name }) } + controls.addView(selector) + button("应用视频解码策略") { + val result = engine.setDecodePolicy(DecodePolicy(video = modes[selector.selectedItemPosition])) + if (result != CommandResult.Accepted) status.text = result.toString() + } + button("切换 SurfaceView / TextureView") { useTexture = !useTexture; bindOutput() } + controls.addView(status) + videoHost = FrameLayout(this) + root.addView(videoHost, LinearLayout.LayoutParams(-1, 0, 1f)) + videoHost.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> fitVideo() } + setContentView(root) + root.requestApplyInsets() + bindOutput() + lifecycleScope.launch { + engine.state.collect { state -> + if (!casting.isRemote) { + val position = state.positionMs + (currentPlayback?.positionOffsetMs ?: 0) + val duration = currentPlayback?.originalDurationMs ?: state.durationMs?.plus(currentPlayback?.positionOffsetMs ?: 0) + status.text = "${currentPlayback?.title.orEmpty()}\n${state.phase} ${position / 1000}s / ${duration?.div(1000) ?: "?"}s\n${state.error?.message ?: ""}" + seek.isEnabled = duration != null && duration > 0 + if (!seeking && duration != null && duration > 0) seek.progress = (position * 1000 / duration).coerceIn(0, 1000).toInt() + } + } + } + lifecycleScope.launch { + engine.events.collect { event -> + if (event is PlaybackEvent.VideoSize && event.height > 0) { + videoRatio = event.width * event.pixelRatio / event.height + fitVideo() + } + } + } + consumeLibraryIntent(intent) + } + override fun onNewIntent(intent: Intent) { super.onNewIntent(intent); setIntent(intent); consumeLibraryIntent(intent) } + private fun consumeLibraryIntent(intent: Intent) { + val ticket = intent.getStringExtra("libraryTicket") ?: return + intent.removeExtra("libraryTicket") + val playback = LibraryPlaybackInbox.take(ticket) ?: return + lifecycleScope.launch { play(playback) } + } + private suspend fun play(playback: LibraryPlayback) { + val validation = SourceRouting.validate(playback.request, Media3TransportRegistry.schemes()) + if (validation != null) { playbackStatus.text = validation.toString(); return } + casting.stop(false) + tracker.close() + if (playback.request.cacheKey != null) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + // 缓存不是播放前提,磁盘空间/数据库不可用时继续走上游。 + runCatching { Media3FileCache.get(applicationContext) } + } + val result = engine.prepare(playback.request) + if (result == CommandResult.Accepted) { currentPlayback = playback; tracker.bind(playback) } + else playbackStatus.text = result.toString() + } + /** 投屏结束后重新解析来源,避免复用已结束的 Jellyfin 转码会话或短效地址。 */ + private suspend fun resumeLocal(position: Long, playing: Boolean) { + val previous = currentPlayback ?: return + try { + val refreshed = previous.refresh?.invoke(position + previous.positionOffsetMs) + ?: previous.copy(request = previous.request.copy(startPositionMs = position)) + play(refreshed.copy(request = refreshed.request.copy(autoplay = playing))) + } catch (_: Exception) { playbackStatus.text = "恢复本机播放失败,请重新打开来源" } + } + /** 设置只保存在当前实例内;不记录地址/请求头,不写入偏好或日志。 */ + private fun showConnectionSettings() { + val form = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(24, 8, 24, 8) } + val types = MediaSourceType.entries + form.addView(TextView(this).apply { text = "媒体类型(无扩展名地址请手动选择)" }) + val typeInput = Spinner(this).apply { + adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, types.map { it.name }) + setSelection(types.indexOf(sourceType)) + } + form.addView(typeInput) + val tcp = CheckBox(this).apply { text = "RTSP 强制 TCP"; isChecked = network.rtspTransport == RtspTransport.TCP } + form.addView(tcp) + form.addView(TextView(this).apply { text = "HTTP 请求头:每行 Name: value;仅用于 HTTP(S)" }) + val headerInput = EditText(this).apply { + isSaveEnabled = false + inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE or android.text.InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS + minLines = 3 + hint = "Authorization: Bearer …\nReferer: https://…" + setText(headers.entries.joinToString("\n") { "${it.key}: ${it.value}" }) + } + form.addView(headerInput) + val error = TextView(this) + form.addView(error) + val dialog = AlertDialog.Builder(this).setTitle("连接设置") + .setView(ScrollView(this).apply { addView(form) }) + .setPositiveButton("保存", null).setNegativeButton("取消", null).create() + dialog.setOnShowListener { + dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + val parsed = runCatching { HttpHeaders.parseLines(headerInput.text.toString()) } + if (parsed.isFailure) { error.text = parsed.exceptionOrNull()?.message; return@setOnClickListener } + headers = parsed.getOrThrow() + sourceType = types[typeInput.selectedItemPosition] + network = network.copy(rtspTransport = if (tcp.isChecked) RtspTransport.TCP else RtspTransport.AUTO) + dialog.dismiss() + Toast.makeText(this, "已保存,加载媒体时生效", Toast.LENGTH_SHORT).show() + } + } + dialog.show() + } + private fun bindOutput() { + outputBinding?.close() + videoHost.removeAllViews() + val view: View = if (useTexture) TextureView(this) else SurfaceView(this) + videoHost.addView(view, FrameLayout.LayoutParams(-1, -1, Gravity.CENTER)) + outputBinding = if (view is TextureView) TextureViewBinding(view, engine) else SurfaceViewBinding(view as SurfaceView, engine) + fitVideo() + } + private fun fitVideo() { + val view = videoHost.getChildAt(0) ?: return + val width = videoHost.width + val height = videoHost.height + if (width <= 0 || height <= 0 || videoRatio <= 0) return + val w = minOf(width, (height * videoRatio).toInt()) + val h = minOf(height, (width / videoRatio).toInt()) + if (view.layoutParams.width != w || view.layoutParams.height != h) + view.layoutParams = FrameLayout.LayoutParams(w, h, Gravity.CENTER) + } + override fun onDestroy() { + casting.close() + tracker.close() + outputBinding?.close() + telemetry.close() + // 生命周期绑定在 ON_DESTROY 释放内核,示例不做旋转保活。 + super.onDestroy() + } + override fun onStop() { tracker.checkpoint(); super.onStop() } +} diff --git a/app-demo/src/main/kotlin/com/ttstd/player/demo/PlayerApplication.kt b/app-demo/src/main/kotlin/com/ttstd/player/demo/PlayerApplication.kt new file mode 100644 index 0000000..190e980 --- /dev/null +++ b/app-demo/src/main/kotlin/com/ttstd/player/demo/PlayerApplication.kt @@ -0,0 +1,25 @@ +package com.ttstd.player.demo + +import android.app.Application +import com.ttstd.player.library.LibraryPlayback +import com.ttstd.player.library.media3.SmbSourceInstaller +import com.ttstd.player.library.storage.LibraryAccounts +import java.util.UUID + +/** 注册来源传输,账户解密延迟到数据源 IO 线程。 */ +class PlayerApplication : Application() { + override fun onCreate() { + super.onCreate() + SmbSourceInstaller.install { id -> LibraryAccounts(this).all().firstOrNull { it.id == id } } + } +} + +/** 进程内一次性交接,Intent 不传递密码、HTTP headers 或服务端会话对象。 */ +object LibraryPlaybackInbox { + private val entries = java.util.concurrent.ConcurrentHashMap() + fun put(playback: LibraryPlayback): String { + entries.clear() + return UUID.randomUUID().toString().also { entries[it] = playback } + } + fun take(ticket: String): LibraryPlayback? = entries.remove(ticket) +} diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..14236d7 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,53 @@ +plugins { + id("com.android.application") + kotlin("android") +} + +android { + namespace = "com.ttstd.player.app" + compileSdk = 37 + testOptions { unitTests.isIncludeAndroidResources = true } + + defaultConfig { + minSdk = 23 + targetSdk = 37 + applicationId = "com.ttstd.player.demo" + versionCode = 4 + versionName = "1.0.0" + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} + +kotlin { jvmToolchain(17) } + +dependencies { + implementation("androidx.appcompat:appcompat:1.7.1") + implementation("androidx.activity:activity-ktx:1.10.1") + implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.9.1") + implementation("androidx.core:core-ktx:1.16.0") + + testImplementation("junit:junit:4.13.2") + testImplementation("org.robolectric:robolectric:4.14.1") + + implementation(project(":library-api")) + implementation(project(":library-webdav")) + implementation(project(":library-smb")) + implementation(project(":library-jellyfin")) + implementation(project(":library-storage")) + implementation(project(":library-media3")) + + implementation(project(":player-media3-source")) + implementation(project(":player-cast-api")) + implementation(project(":player-cast-dlna")) + implementation(project(":player-cast-relay")) + implementation(project(":player-cast-google")) + implementation(project(":player-core")) + implementation(project(":player-media3")) + implementation(project(":player-render-android")) + implementation(project(":player-lifecycle")) + implementation(project(":player-telemetry")) +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..e435b02 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/app/src/main/kotlin/com/ttstd/player/app/AppData.kt b/app/src/main/kotlin/com/ttstd/player/app/AppData.kt new file mode 100644 index 0000000..0ee1099 --- /dev/null +++ b/app/src/main/kotlin/com/ttstd/player/app/AppData.kt @@ -0,0 +1,156 @@ +package com.ttstd.player.app + +import android.app.Application +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import com.ttstd.player.api.* +import com.ttstd.player.library.* +import com.ttstd.player.library.jellyfin.JellyfinLibrary +import com.ttstd.player.library.media3.SmbSourceInstaller +import com.ttstd.player.library.smb.SmbLibrary +import com.ttstd.player.library.storage.LibraryAccounts +import com.ttstd.player.library.webdav.WebDavLibrary +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.json.JSONArray +import org.json.JSONObject +import java.security.KeyStore +import javax.crypto.* +import javax.crypto.spec.GCMParameterSpec + +/** 可持久化媒体身份。来源文件只保存账户 ID/条目,不保存短效播放链接。 */ +data class MediaRef( + val title: String, + val accountId: String? = null, + val entry: LibraryEntry? = null, + val uri: String? = null, + val headers: Map = emptyMap(), + val sourceType: MediaSourceType = MediaSourceType.AUTO, + val network: NetworkOptions = NetworkOptions(), + val extraSubtitles: List = emptyList(), +) { + val id: String get() = java.security.MessageDigest.getInstance("SHA-256") + .digest((accountId?.let { "$it:${entry?.id}" } ?: uri.orEmpty()).toByteArray()) + .joinToString("") { "%02x".format(it) } + override fun toString() = "MediaRef(id=$id, uri=REDACTED)" +} +data class RecentMedia(val ref: MediaRef, val positionMs: Long = 0, val durationMs: Long? = null, + val updatedAt: Long = System.currentTimeMillis(), val favorite: Boolean = false) + +/** 历史中可能含用户输入的签名 URL/请求头,整份记录 AES-GCM 加密,不做明文回退。 */ +class RecentStore(context: Context) { + private val prefs = context.getSharedPreferences("app-recent-media", Context.MODE_PRIVATE) + private fun key(): SecretKey { + val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (store.getKey("tt-video-history-v1", null) as? SecretKey)?.let { return it } + return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply { + init(KeyGenParameterSpec.Builder("tt-video-history-v1", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build()) + }.generateKey() + } + @Synchronized fun all(): List { + val encoded = prefs.getString("records", null) ?: return emptyList() + val bytes = Base64.decode(encoded, Base64.NO_WRAP) + val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, bytes.copyOfRange(0, 12))) } + val array = JSONArray(String(cipher.doFinal(bytes.copyOfRange(12, bytes.size)), Charsets.UTF_8)) + return (0 until array.length()).map { decode(array.getJSONObject(it)) }.sortedByDescending { it.updatedAt } + } + @Synchronized fun find(id: String): RecentMedia? = all().firstOrNull { it.ref.id == id } + @Synchronized fun save(ref: MediaRef, position: Long, duration: Long?): RecentMedia { + val entries = all() + val old = entries.firstOrNull { it.ref.id == ref.id } + val value = RecentMedia(ref, position.coerceAtLeast(0), duration, favorite = old?.favorite ?: false) + write((listOf(value) + entries.filterNot { it.ref.id == ref.id }).take(150)) + return value + } + @Synchronized fun favorite(id: String) { write(all().map { if (it.ref.id == id) it.copy(favorite = !it.favorite) else it }) } + @Synchronized fun remove(id: String) { write(all().filterNot { it.ref.id == id }) } + @Synchronized fun clear() { prefs.edit().remove("records").apply() } + private fun write(items: List) { + val array = JSONArray(); items.forEach { array.put(encode(it)) } + val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, key()) } + val encrypted = cipher.doFinal(array.toString().toByteArray()) + prefs.edit().putString("records", Base64.encodeToString(cipher.iv + encrypted, Base64.NO_WRAP)).apply() + } + companion object { + /** JSON 编解码独立于 Keystore,便于验证迁移与不丢失来源身份。 */ + fun encode(item: RecentMedia): JSONObject { + val r = item.ref + val headers = JSONObject(); r.headers.forEach { (k, v) -> headers.put(k, v) } + val subtitles = JSONArray(); r.extraSubtitles.forEach { subtitles.put(JSONObject().put("uri", it.uri).put("mime", it.mimeType).put("language", it.language).put("default", it.isDefault)) } + return JSONObject().put("title", r.title).put("account", r.accountId).put("uri", r.uri) + .put("entry", r.entry?.let { JSONObject().put("id", it.id).put("name", it.name).put("size", it.size).put("version", it.version).put("resume", it.resumeMs) }) + .put("headers", headers).put("type", r.sourceType.name).put("tcp", r.network.rtspTransport.name) + .put("connectTimeout", r.network.connectTimeoutMs).put("readTimeout", r.network.readTimeoutMs).put("rtspTimeout", r.network.rtspTimeoutMs) + .put("subtitles", subtitles).put("position", item.positionMs).put("duration", item.durationMs) + .put("updated", item.updatedAt).put("favorite", item.favorite) + } + fun decode(json: JSONObject): RecentMedia { + val entry = json.optJSONObject("entry")?.let { LibraryEntry(it.getString("id"), it.getString("name"), false, + it.optLong("size").takeIf { size -> size > 0 }, it.optString("version"), it.optLong("resume")) } + val headers = json.optJSONObject("headers") ?: JSONObject() + val map = headers.keys().asSequence().associateWith { headers.getString(it) } + val subtitles = json.optJSONArray("subtitles") ?: JSONArray() + val ref = MediaRef(json.getString("title"), json.optString("account").takeUnless { it.isBlank() || it == "null" }, entry, + json.optString("uri").takeUnless { it.isBlank() || it == "null" }, map, + runCatching { MediaSourceType.valueOf(json.optString("type")) }.getOrDefault(MediaSourceType.AUTO), + NetworkOptions(json.optInt("connectTimeout", 8000), json.optInt("readTimeout", 8000), json.optLong("rtspTimeout", 8000), + runCatching { RtspTransport.valueOf(json.optString("tcp")) }.getOrDefault(RtspTransport.AUTO)), + (0 until subtitles.length()).map { subtitles.getJSONObject(it).let { s -> ExternalSubtitle(s.getString("uri"), s.getString("mime"), + s.optString("language").takeUnless { it.isBlank() || it == "null" }, s.optBoolean("default")) } }) + return RecentMedia(ref, json.optLong("position"), json.optLong("duration").takeIf { it > 0 }, json.optLong("updated"), json.optBoolean("favorite")) + } + } +} + +class AppPreferences(context: Context) { + private val prefs = context.getSharedPreferences("app-preferences", Context.MODE_PRIVATE) + var decoder: DecodeMode + get() = runCatching { DecodeMode.valueOf(prefs.getString("decoder", "AUTO")!!) }.getOrDefault(DecodeMode.AUTO) + set(value) { prefs.edit().putString("decoder", value.name).apply() } + var texture: Boolean + get() = prefs.getBoolean("texture", false) + set(value) { prefs.edit().putBoolean("texture", value).apply() } + var autoSubtitle: Boolean + get() = prefs.getBoolean("subtitle", true) + set(value) { prefs.edit().putBoolean("subtitle", value).apply() } +} + +class VideoApplication : Application() { + override fun onCreate() { + super.onCreate() + androidx.appcompat.app.AppCompatDelegate.setDefaultNightMode(androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES) + SmbSourceInstaller.install { id -> LibraryAccounts(this).all().firstOrNull { it.id == id } } + } +} + +/** 页面只传加密记录 ID;账户和播放请求不经可导出的 Intent 传递。 */ +class AppRepository(private val context: Context) { + val accounts = LibraryAccounts(context.applicationContext) + val recent = sharedRecent(context.applicationContext) + val preferences = AppPreferences(context.applicationContext) + fun library(account: LibraryAccount): MediaLibrary = when (account.kind) { + LibraryKind.WEBDAV -> WebDavLibrary(account) + LibraryKind.SMB -> SmbLibrary(account) + LibraryKind.JELLYFIN -> JellyfinLibrary(account) + } + suspend fun resolve(ref: MediaRef, position: Long): LibraryPlayback = withContext(Dispatchers.IO) { + val playback = if (ref.accountId != null) { + val account = accounts.all().firstOrNull { it.id == ref.accountId } ?: throw LibraryException("来源已删除,请重新添加") + library(account).resolve(ref.entry ?: throw LibraryException("文件信息已失效"), LibraryPlaybackOptions(startPositionMs = position)) + } else LibraryPlayback(PlaybackRequest(ref.uri ?: throw LibraryException("地址不存在"), ref.headers, position, true, + sourceType = ref.sourceType, network = ref.network, cacheKey = "app:${ref.id}".takeIf { ref.sourceType !in setOf(MediaSourceType.RTSP, MediaSourceType.RTMP) }), + "app:${ref.id}", ref.title) + val allSubtitles = playback.request.subtitles + ref.extraSubtitles + val selected = if (ref.extraSubtitles.isNotEmpty()) playback.request.subtitles.size else if (preferences.autoSubtitle) 0 else -1 + playback.copy(request = playback.request.copy(subtitles = allSubtitles.mapIndexed { index, subtitle -> + subtitle.copy(isDefault = index == selected) + })) + } + companion object { + private var recentStore: RecentStore? = null + @Synchronized private fun sharedRecent(context: Context): RecentStore = recentStore ?: RecentStore(context).also { recentStore = it } + } +} diff --git a/app/src/main/kotlin/com/ttstd/player/app/BrowserActivity.kt b/app/src/main/kotlin/com/ttstd/player/app/BrowserActivity.kt new file mode 100644 index 0000000..6d5b19a --- /dev/null +++ b/app/src/main/kotlin/com/ttstd/player/app/BrowserActivity.kt @@ -0,0 +1,149 @@ +package com.ttstd.player.app + +import android.app.AlertDialog +import android.app.Application +import android.content.Intent +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.widget.* +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.* +import com.ttstd.player.library.* +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.MutableStateFlow +import com.ttstd.player.app.Ui.dp + +class BrowserModel(application: Application) : AndroidViewModel(application) { + private val repo = AppRepository(application) + var account: LibraryAccount? = null; private set + private var library: MediaLibrary? = null + val entries = MutableStateFlow>(emptyList()) + val message = MutableStateFlow("") + val busy = MutableStateFlow(false) + var more: Int? = null; private set + val folders = mutableListOf>() + private var job: Job? = null + fun open(id: String) { + if (account?.id == id) return + job = viewModelScope.launch { + try { + val selected = withContext(Dispatchers.IO) { repo.accounts.all().firstOrNull { it.id == id } } + ?: throw LibraryException("来源已删除") + account = selected; library = repo.library(selected); folders.clear(); folders += "" to selected.name + load() + } catch (e: Exception) { message.value = SourceDialogs.safeError(e) } + } + } + fun enter(entry: LibraryEntry) { folders += entry.id to entry.name; load() } + fun up(): Boolean = if (folders.size > 1) { folders.removeAt(folders.lastIndex); load(); true } else false + fun load(offset: Int = 0) { + job?.cancel() + val source = library ?: return + val folder = folders.lastOrNull()?.first.orEmpty() + job = viewModelScope.launch { + busy.value = true; message.value = "正在连接来源…" + try { + val page = source.list(folder, offset) + entries.value = (if (offset == 0) page.entries else entries.value + page.entries).distinctBy { it.id } + more = page.nextOffset + message.value = "${entries.value.size} 个条目" + } catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { message.value = SourceDialogs.safeError(e) } + finally { busy.value = false } + } + } +} + +/** 目录浏览保留在 ViewModel 中,转屏不会重新登录、丢失路径或重复发起网络请求。 */ +class BrowserActivity : AppCompatActivity() { + private lateinit var model: BrowserModel + private val repo by lazy { AppRepository(applicationContext) } + private lateinit var title: TextView + private lateinit var status: TextView + private lateinit var list: ListView + private lateinit var more: TextView + private lateinit var search: EditText + private var visible = emptyList() + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + model = ViewModelProvider(this)[BrowserModel::class.java] + val root = Ui.column(this) + Ui.inset(this, root) + val toolbar = LinearLayout(this).apply { setPadding(dp(16), dp(12), dp(16), dp(8)); gravity = android.view.Gravity.CENTER_VERTICAL } + toolbar.addView(Ui.button(this, "‹") { goBack() }) + title = Ui.label(this, "媒体浏览", 22f, bold = true) + toolbar.addView(title, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(12) }) + toolbar.addView(Ui.button(this, "刷新") { model.load() }) + root.addView(toolbar) + search = EditText(this).apply { + hint = "筛选当前目录"; setTextColor(Ui.ink); setHintTextColor(Ui.muted); setSingleLine(true) + setPadding(dp(20), 0, dp(20), 0) + addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { render() } + override fun afterTextChanged(s: Editable?) = Unit + }) + } + root.addView(search, LinearLayout.LayoutParams(-1, dp(52))) + status = Ui.label(this, "", 13f, Ui.muted).apply { setPadding(dp(20), dp(8), dp(20), dp(8)) } + root.addView(status) + list = ListView(this).apply { divider = null; clipToPadding = false; setPadding(dp(16), dp(4), dp(16), dp(12)) } + root.addView(list, LinearLayout.LayoutParams(-1, 0, 1f)) + more = Ui.button(this, "加载更多") { model.more?.let(model::load) } + root.addView(more, LinearLayout.LayoutParams(-1, -2).apply { setMargins(dp(16), dp(4), dp(16), dp(12)) }) + setContentView(root) + list.setOnItemClickListener { _, _, position, _ -> + val entry = visible[position] + if (entry.isFolder) { search.setText(""); model.enter(entry) } else play(entry) + } + list.setOnItemLongClickListener { _, _, position, _ -> + val entry = visible[position] + if (!entry.isFolder) AlertDialog.Builder(this).setTitle(entry.name).setItems(arrayOf("播放", "加入 / 取消收藏")) { _, choice -> + if (choice == 0) play(entry) else lifecycleScope.launch { + withContext(Dispatchers.IO) { + val ref = reference(entry); val old = repo.recent.find(ref.id) + if (old == null) repo.recent.save(ref, entry.resumeMs, null) + repo.recent.favorite(ref.id) + } + Toast.makeText(this@BrowserActivity, "收藏已更新", Toast.LENGTH_SHORT).show() + } + }.show() + true + } + lifecycleScope.launch { model.entries.collect { render() } } + lifecycleScope.launch { model.message.collect { status.text = it; title.text = model.folders.lastOrNull()?.second ?: "媒体浏览" } } + lifecycleScope.launch { model.busy.collect { more.isEnabled = !it && model.more != null; more.visibility = if (model.more == null) android.view.View.GONE else android.view.View.VISIBLE } } + onBackPressedDispatcher.addCallback(this, object : androidx.activity.OnBackPressedCallback(true) { override fun handleOnBackPressed() { goBack() } }) + model.open(intent.getStringExtra("account").orEmpty()) + } + private fun reference(entry: LibraryEntry) = MediaRef(entry.name, model.account?.id, entry) + private fun render() { + if (!::list.isInitialized) return + val jellyfin = model.account?.kind == LibraryKind.JELLYFIN + val query = search.text.toString() + visible = model.entries.value.filter { (it.isFolder || jellyfin || LibraryFiles.isVideo(it.name)) && it.name.contains(query, true) } + list.adapter = object : BaseAdapter() { + override fun getCount() = visible.size + override fun getItem(position: Int) = visible[position] + override fun getItemId(position: Int) = position.toLong() + override fun getView(position: Int, convertView: android.view.View?, parent: android.view.ViewGroup?): android.view.View { + val entry = visible[position] + return Ui.card(this@BrowserActivity, (if (entry.isFolder) "▤ " else "▷ ") + entry.name, + if (entry.isFolder) "打开目录" else listOfNotNull(entry.size?.let(Ui::bytes), entry.resumeMs.takeIf { it > 0 }?.let { "已看 ${Ui.time(it)}" }, "点击播放 · 长按收藏").joinToString(" · ")) + .apply { minimumHeight = dp(84); isFocusable = false } + } + } + } + private fun play(entry: LibraryEntry) { + val ref = reference(entry) + PlaybackQueue.set(visible.filterNot { it.isFolder }.map(::reference)) + lifecycleScope.launch { + try { + withContext(Dispatchers.IO) { val old = repo.recent.find(ref.id); repo.recent.save(ref, old?.positionMs ?: entry.resumeMs, old?.durationMs) } + startActivity(Intent(this@BrowserActivity, PlayerActivity::class.java).putExtra("media", ref.id)) + } catch (_: Exception) { status.text = "无法保存播放记录,请检查设备安全存储" } + } + } + private fun goBack() { if (model.up()) search.setText("") else finish() } +} diff --git a/app/src/main/kotlin/com/ttstd/player/app/DlnaPlaybackService.kt b/app/src/main/kotlin/com/ttstd/player/app/DlnaPlaybackService.kt new file mode 100644 index 0000000..566a55a --- /dev/null +++ b/app/src/main/kotlin/com/ttstd/player/app/DlnaPlaybackService.kt @@ -0,0 +1,130 @@ +package com.ttstd.player.app + +import android.app.* +import android.content.* +import android.media.MediaMetadata +import android.media.session.MediaSession +import android.media.session.PlaybackState +import android.os.Build +import android.os.IBinder +import com.ttstd.player.cast.* +import com.ttstd.player.cast.dlna.* +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +data class DlnaUiState(val active: Boolean = false, val connecting: Boolean = false, val title: String = "", + val device: String = "", val playback: RemotePlaybackState = RemotePlaybackState(), val error: String? = null) +data class DlnaLease(val device: DlnaDevice, val media: CastMedia, val observer: CastProgressObserver, val cleanup: () -> Unit, + val mediaId: String, val positionOffsetMs: Long) + +/** 进程内会话只持有应用级资源,不持有 Activity。系统终止进程后不伪造可恢复会话。 */ +object DlnaSession { + val state = MutableStateFlow(DlnaUiState()) + var lease: DlnaLease? = null + var resourcesOpen = false + fun command(context: Context, action: String) { context.startService(Intent(context, DlnaPlaybackService::class.java).setAction(action)) } +} + +/** DLNA 与手机 relay 由前台媒体服务持有,页面退出/旋转不再关闭投屏流。 */ +class DlnaPlaybackService : Service() { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private val mutex = Mutex() + private lateinit var controller: DlnaController + private lateinit var session: MediaSession + private var lease: DlnaLease? = null + override fun onBind(intent: Intent?): IBinder? = null + override fun onCreate() { + super.onCreate() + controller = DlnaController(this) + session = MediaSession(this, "TTVideoPlayer DLNA").apply { + setCallback(object : MediaSession.Callback() { + override fun onPlay() { perform("play") } + override fun onPause() { perform("pause") } + override fun onStop() { perform("stop") } + override fun onSeekTo(pos: Long) { scope.launch { runCatching { lease?.let { mutex.withLock { this@DlnaPlaybackService.controller.seek(it.device, pos) } } } } } + }) + isActive = true + } + if (Build.VERSION.SDK_INT >= 26) getSystemService(NotificationManager::class.java).createNotificationChannel( + NotificationChannel("dlna-playback", "电视投屏", NotificationManager.IMPORTANCE_LOW)) + startForeground(4102, notification()) + } + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent?.action == "seek") scope.launch { runCatching { lease?.let { mutex.withLock { controller.seek(it.device, intent.getLongExtra("position", 0)) } } } } + else if (intent?.action != null) perform(intent.action!!) else if (lease == null) { + lease = DlnaSession.lease + val current = lease + if (current == null) { stopSelf(); return START_NOT_STICKY } + DlnaSession.state.value = DlnaUiState(true, true, current.media.title, current.device.name, + RemotePlaybackState(current.media.startPositionMs)) + scope.launch { + try { + mutex.withLock { controller.load(current.device, current.media) } + runCatching { current.observer.started(current.media.startPositionMs) } + var reports = 0 + while (isActive) { + try { + val value = mutex.withLock { controller.state(current.device) } + DlnaSession.state.value = DlnaUiState(true, false, current.media.title, current.device.name, value) + if (reports++ % 3 == 0) runCatching { current.observer.progress(value) } + updateMediaSession(value) + } catch (cancelled: CancellationException) { throw cancelled } + catch (_: Exception) { DlnaSession.state.value = DlnaSession.state.value.copy(connecting = false, error = "暂时无法读取电视状态,可重试或结束投屏") } + delay(3000) + } + } catch (cancelled: CancellationException) { throw cancelled } + catch (_: Exception) { DlnaSession.state.value = DlnaSession.state.value.copy(error = "电视未接受播放请求"); stopSelf() } + } + } + return START_NOT_STICKY + } + private fun perform(action: String) { + val value = lease ?: return + if (action == "stop") { stopSelf(); return } + scope.launch { + try { mutex.withLock { when (action) { + "pause" -> controller.pause(value.device) + "play" -> controller.play(value.device) + "back" -> controller.seek(value.device, (DlnaSession.state.value.playback.positionMs - 30000).coerceAtLeast(0)) + "forward" -> controller.seek(value.device, DlnaSession.state.value.playback.positionMs + 30000) + } } } catch (_: Exception) { DlnaSession.state.value = DlnaSession.state.value.copy(error = "电视未接受该操作") } + } + } + private fun updateMediaSession(value: RemotePlaybackState) { + session.setMetadata(MediaMetadata.Builder().putString(MediaMetadata.METADATA_KEY_TITLE, DlnaSession.state.value.title) + .putLong(MediaMetadata.METADATA_KEY_DURATION, value.durationMs ?: -1).build()) + session.setPlaybackState(PlaybackState.Builder().setActions(PlaybackState.ACTION_PLAY or PlaybackState.ACTION_PAUSE or PlaybackState.ACTION_STOP or PlaybackState.ACTION_SEEK_TO) + .setState(if (value.playing) PlaybackState.STATE_PLAYING else PlaybackState.STATE_PAUSED, value.positionMs, 1f).build()) + // 同一个前台媒体通知同时更新状态;无需另发普通通知或申请通知权限。 + startForeground(4102, notification()) + } + private fun notification(): Notification { + val state = DlnaSession.state.value + fun command(action: String) = PendingIntent.getService(this, action.hashCode(), Intent(this, javaClass).setAction(action), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) + val builder = if (Build.VERSION.SDK_INT >= 26) Notification.Builder(this, "dlna-playback") else Notification.Builder(this) + return builder.setSmallIcon(R.drawable.ic_app).setContentTitle(state.title.ifBlank { "正在连接电视" }) + .setContentText(state.device.ifBlank { "同同影音投屏" }).setOngoing(true) + .setContentIntent(PendingIntent.getActivity(this, 0, Intent(this, HomeActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)) + .addAction(Notification.Action.Builder(null, if (state.playback.playing) "暂停" else "播放", command(if (state.playback.playing) "pause" else "play")).build()) + .addAction(Notification.Action.Builder(null, "结束", command("stop")).build()) + .setStyle(Notification.MediaStyle().setMediaSession(session.sessionToken).setShowActionsInCompactView(0, 1)).build() + } + override fun onDestroy() { + val old = lease + val snapshot = DlnaSession.state.value + scope.cancel() + session.release() + DlnaSession.lease = null; lease = null + CoroutineScope(Dispatchers.IO).launch { + withTimeoutOrNull(5000) { + if (old != null) { runCatching { controller.stop(old.device) }; runCatching { old.observer.stopped(snapshot.playback.positionMs) } } + } + old?.cleanup?.invoke() + DlnaSession.resourcesOpen = false + } + DlnaSession.state.value = snapshot.copy(active = false, connecting = false) + super.onDestroy() + } +} diff --git a/app/src/main/kotlin/com/ttstd/player/app/HomeActivity.kt b/app/src/main/kotlin/com/ttstd/player/app/HomeActivity.kt new file mode 100644 index 0000000..6e59347 --- /dev/null +++ b/app/src/main/kotlin/com/ttstd/player/app/HomeActivity.kt @@ -0,0 +1,259 @@ +package com.ttstd.player.app + +import android.app.AlertDialog +import android.content.Intent +import android.os.Bundle +import android.provider.OpenableColumns +import android.text.InputType +import android.view.Gravity +import android.widget.* +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.lifecycleScope +import com.ttstd.player.api.* +import com.ttstd.player.core.HttpHeaders +import com.ttstd.player.library.* +import com.ttstd.player.media3.source.Media3FileCache +import com.ttstd.player.cast.google.GoogleCastActivity +import com.ttstd.player.cast.google.GoogleCastResources +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.first +import com.ttstd.player.app.Ui.dp + +/** 正式应用入口:媒体、来源、历史、设置。宽屏使用侧边导航,手机使用底部导航。 */ +class HomeActivity : AppCompatActivity() { + private val repo by lazy { AppRepository(applicationContext) } + private lateinit var content: LinearLayout + private var tab = 0 + private var accounts: List = emptyList() + private var recent: List = emptyList() + private var favoritesOnly = false + private var loadJob: Job? = null + private val googleControl = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + val id = AppPlaybackRuntime.googleMediaId + if (id != null && result.data != null) lifecycleScope.launch { + withContext(Dispatchers.IO) { repo.recent.find(id)?.let { repo.recent.save(it.ref, result.data!!.getLongExtra("position", it.positionMs) + AppPlaybackRuntime.googleOffsetMs, it.durationMs) } } + startActivity(Intent(this@HomeActivity, PlayerActivity::class.java).putExtra("media", id)) + } + } + private val pickVideo = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> + if (uris.isNotEmpty()) lifecycleScope.launch { + val refs = withContext(Dispatchers.IO) { uris.take(150).map { uri -> + runCatching { contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } + val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor -> + if (cursor.moveToFirst()) cursor.getString(0) else null + } ?: "本地视频" + MediaRef(name, uri = uri.toString()) + } } + PlaybackQueue.set(refs) + open(refs.first()) + } + } + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + tab = savedInstanceState?.getInt("tab") ?: 0 + build() + if (intent.action == Intent.ACTION_VIEW && intent.data != null) { + val uri = intent.data!! + if (uri.scheme?.lowercase() in setOf("content", "http", "https", "rtsp", "rtmp")) + lifecycleScope.launch { open(MediaRef(uri.lastPathSegment ?: "外部视频", uri = uri.toString())) } + intent.action = null + } + } + override fun onResume() { super.onResume(); refresh() } + override fun onSaveInstanceState(outState: Bundle) { outState.putInt("tab", tab); super.onSaveInstanceState(outState) } + private fun build() { + val wide = resources.configuration.screenWidthDp >= 720 + val root = LinearLayout(this).apply { orientation = if (wide) LinearLayout.HORIZONTAL else LinearLayout.VERTICAL } + Ui.inset(this, root) + val nav = LinearLayout(this).apply { + orientation = if (wide) LinearLayout.VERTICAL else LinearLayout.HORIZONTAL + gravity = Gravity.CENTER; setPadding(dp(8), dp(8), dp(8), dp(8)) + } + listOf("首页", "来源", "历史", "设置").forEachIndexed { index, label -> + nav.addView(Ui.button(this, label, index == tab) { tab = index; build(); render() }, + if (wide) LinearLayout.LayoutParams(dp(100), dp(64)).apply { bottomMargin = dp(12) } + else LinearLayout.LayoutParams(0, dp(52), 1f).apply { marginStart = dp(3); marginEnd = dp(3) }) + } + val scroll = ScrollView(this).apply { isFillViewport = true } + content = Ui.column(this, if (wide) 32 else 20) + scroll.addView(content) + if (wide) { + root.addView(nav, LinearLayout.LayoutParams(dp(116), -1)) + root.addView(scroll, LinearLayout.LayoutParams(0, -1, 1f)) + } else { + root.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f)); root.addView(nav) + } + setContentView(root); render() + } + private fun refresh() { + loadJob?.cancel() + loadJob = lifecycleScope.launch { + try { + withContext(Dispatchers.IO) { accounts = repo.accounts.all(); recent = repo.recent.all() } + render() + } catch (cancelled: CancellationException) { throw cancelled } + catch (_: Exception) { content.removeAllViews(); content.addView(Ui.empty(this@HomeActivity, "本机数据暂不可读", "设备安全密钥可能发生变化,请在系统设置中检查应用数据。")) } + } + } + private fun heading(title: String, detail: String) { + content.addView(Ui.label(this, title, 28f, bold = true)) + content.addView(Ui.label(this, detail, 14f, Ui.muted).apply { setPadding(0, dp(8), 0, dp(24)) }) + } + private fun render() { + if (!::content.isInitialized) return + content.removeAllViews() + when (tab) { + 0 -> home() + 1 -> sources() + 2 -> history() + else -> settings() + } + } + private fun home() { + heading("同同影音", "你的媒体,随处播放") + if (DlnaSession.state.value.active) content.addView(Ui.card(this, "正在投屏 · ${DlnaSession.state.value.device}", DlnaSession.state.value.title) { + AlertDialog.Builder(this).setTitle("电视投屏").setItems(arrayOf("播放", "暂停", "结束投屏", "结束并在本机继续")) { _, choice -> + val lease = DlnaSession.lease + DlnaSession.command(this, listOf("play", "pause", "stop", "stop")[choice]) + if (choice == 3 && lease != null) lifecycleScope.launch { + withTimeoutOrNull(7000) { DlnaSession.state.first { !it.active } } + withContext(Dispatchers.IO) { repo.recent.find(lease.mediaId)?.let { repo.recent.save(it.ref, DlnaSession.state.value.playback.positionMs + lease.positionOffsetMs, it.durationMs) } } + startActivity(Intent(this@HomeActivity, PlayerActivity::class.java).putExtra("media", lease.mediaId)) + } + }.show() + }) + if (GoogleCastResources.observer != null && AppPlaybackRuntime.googleMedia != null) content.addView(Ui.card(this, "Google Cast 正在播放", "打开设备控制或返回本机") { + AppPlaybackRuntime.googleMedia?.let { googleControl.launch(GoogleCastActivity.intent(this, it)) } + }) + content.addView(Ui.card(this, "连接你的媒体世界", "本地文件、网盘、局域网与家庭媒体库,在这里汇合。")) + val row = LinearLayout(this) + row.addView(Ui.button(this, "打开本地视频", true) { pickVideo.launch(arrayOf("video/*")) }, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) }) + row.addView(Ui.button(this, "播放链接") { urlDialog() }, LinearLayout.LayoutParams(0, -2, 1f)) + content.addView(row) + content.addView(Ui.label(this, "继续观看", 19f, bold = true).apply { setPadding(0, dp(28), 0, dp(14)) }) + if (recent.isEmpty()) content.addView(Ui.empty(this, "从一部视频开始", "打开文件、粘贴链接,或添加你的媒体来源。")) + else recent.take(4).forEach { mediaCard(it) } + content.addView(Ui.label(this, "媒体来源", 19f, bold = true).apply { setPadding(0, dp(20), 0, dp(14)) }) + accounts.take(3).forEach { sourceCard(it) } + content.addView(Ui.button(this, if (accounts.isEmpty()) "+ 添加网盘或 NAS" else "管理全部来源") { + if (accounts.isEmpty()) SourceDialogs.edit(this) { refresh() } else { tab = 1; build() } + }) + } + private fun sources() { + heading("媒体来源", "WebDAV 网盘 · SMB 局域网 · Jellyfin") + content.addView(Ui.button(this, "+ 添加来源", true) { SourceDialogs.edit(this) { refresh() } }) + content.addView(Ui.label(this, "", 8f)) + if (accounts.isEmpty()) content.addView(Ui.empty(this, "连接你的网盘或 NAS", "WebDAV 可连接支持该协议的网盘或聚合服务;SMB 连接共享文件夹。")) + accounts.forEach { sourceCard(it) } + } + private fun sourceCard(account: LibraryAccount) { + val host = runCatching { java.net.URI(account.endpoint).host }.getOrNull().orEmpty() + val card = Ui.card(this, account.name, "${account.kind} · $host") { startActivity(Intent(this, BrowserActivity::class.java).putExtra("account", account.id)) } + card.addView(Ui.button(this, "管理来源") { + AlertDialog.Builder(this).setTitle(account.name).setItems(arrayOf("编辑连接", "删除来源")) { _, index -> + if (index == 0) SourceDialogs.edit(this, account) { refresh() } + else AlertDialog.Builder(this).setMessage("删除连接配置?服务器上的文件不会被修改。") + .setPositiveButton("删除") { _, _ -> lifecycleScope.launch { withContext(Dispatchers.IO) { repo.accounts.delete(account.id) }; refresh() } } + .setNegativeButton("取消", null).show() + }.show() + }.apply { layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(14) } }) + content.addView(card) + } + private fun history() { + heading("观看记录", "记录与播放链接加密保存在本机") + val filters = LinearLayout(this) + filters.addView(Ui.button(this, "全部", !favoritesOnly) { favoritesOnly = false; render() }, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) }) + filters.addView(Ui.button(this, "收藏", favoritesOnly) { favoritesOnly = true; render() }, LinearLayout.LayoutParams(0, -2, 1f)) + content.addView(filters); content.addView(Ui.label(this, "", 8f)) + val visible = recent.filter { !favoritesOnly || it.favorite } + if (visible.isEmpty()) content.addView(Ui.empty(this, if (favoritesOnly) "还没有收藏" else "还没有观看记录", "视频卡片的更多菜单可收藏或移除记录。")) + visible.forEach { mediaCard(it) } + } + private fun mediaCard(item: RecentMedia) { + val position = if (item.positionMs > 0) "已看 ${Ui.time(item.positionMs)}" else "从头播放" + val source = item.ref.accountId?.let { id -> accounts.firstOrNull { it.id == id }?.name } ?: if (item.ref.uri?.startsWith("content:") == true) "本地文件" else "在线视频" + val card = Ui.card(this, (if (item.favorite) "★ " else "") + item.ref.title, "$source · $position") { lifecycleScope.launch { open(item.ref) } } + if (item.durationMs != null && item.durationMs > 0) card.addView(ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { + max = 1000; progress = (item.positionMs * 1000 / item.durationMs).coerceIn(0, 1000).toInt() + progressTintList = android.content.res.ColorStateList.valueOf(Ui.accent) + }) + card.addView(Ui.button(this, "更多") { + AlertDialog.Builder(this).setTitle(item.ref.title).setItems(arrayOf(if (item.favorite) "取消收藏" else "加入收藏", "从头播放", "移除记录")) { _, choice -> + lifecycleScope.launch { + withContext(Dispatchers.IO) { + when (choice) { 0 -> repo.recent.favorite(item.ref.id); 1 -> repo.recent.save(item.ref, 0, item.durationMs); else -> repo.recent.remove(item.ref.id) } + } + if (choice == 1) open(item.ref) else refresh() + } + }.show() + }.apply { layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(12) } }) + content.addView(card) + } + private fun settings() { + heading("播放与存储", "为不同设备选择合适的播放方式") + val modes = DecodeMode.entries + val names = arrayOf("自动选择", "优先硬件解码", "仅硬件解码", "仅系统软件解码") + content.addView(Ui.card(this, "默认解码方式", names[modes.indexOf(repo.preferences.decoder)]) { + AlertDialog.Builder(this).setTitle("默认解码方式").setSingleChoiceItems(names, modes.indexOf(repo.preferences.decoder)) { dialog, index -> repo.preferences.decoder = modes[index]; dialog.dismiss(); render() }.show() + }) + content.addView(Ui.card(this, "视频显示", if (repo.preferences.texture) "TextureView · 适合界面变换" else "SurfaceView · 默认省电路径") { + repo.preferences.texture = !repo.preferences.texture; render() + }) + content.addView(Ui.card(this, "自动加载同名字幕", if (repo.preferences.autoSubtitle) "已开启" else "已关闭") { repo.preferences.autoSubtitle = !repo.preferences.autoSubtitle; render() }) + content.addView(Ui.card(this, "媒体缓存", "已使用 ${Ui.bytes(cacheBytes())} · 目标上限 256 MB\n缓存可被系统回收,不是离线下载。")) + content.addView(Ui.button(this, "清理媒体缓存") { + if (AppPlaybackRuntime.localActive || DlnaSession.resourcesOpen || GoogleCastResources.observer != null) { + Toast.makeText(this, "请先结束播放和投屏,再清理缓存", Toast.LENGTH_LONG).show(); return@button + } + AlertDialog.Builder(this).setMessage("确认清理已缓存的媒体片段?投屏或播放进行中时请先停止播放。") + .setPositiveButton("清理") { _, _ -> lifecycleScope.launch { + val result = withContext(Dispatchers.IO) { runCatching { Media3FileCache.get(applicationContext); Media3FileCache.clear() } } + Toast.makeText(this@HomeActivity, if (result.isSuccess) "缓存已清理" else "缓存暂时无法清理,请结束播放后重试", Toast.LENGTH_SHORT).show(); render() + } }.setNegativeButton("取消", null).show() + }) + content.addView(Ui.button(this, "清空历史与收藏") { + AlertDialog.Builder(this).setMessage("清空本机记录?媒体来源和远端文件会保留。") + .setPositiveButton("清空") { _, _ -> lifecycleScope.launch { withContext(Dispatchers.IO) { repo.recent.clear() }; refresh() } } + .setNegativeButton("取消", null).show() + }.apply { layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(12) } }) + content.addView(Ui.card(this, "关于同同影音", "1.0.0 · Android 6.0+\n本地 / 在线 / WebDAV / SMB / Jellyfin\n支持 DLNA 与 Google Cast;接收端需支持对应媒体格式。")) + } + private fun cacheBytes() = runCatching { Media3FileCache.bytes() }.getOrDefault(0) + private fun urlDialog() { + val form = Ui.column(this, 20) + val url = EditText(this).apply { hint = "视频地址或直播链接"; isSaveEnabled = false; inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI; setSingleLine(true) } + form.addView(url) + val types = MediaSourceType.entries + val selector = Spinner(this).apply { adapter = ArrayAdapter(this@HomeActivity, android.R.layout.simple_spinner_dropdown_item, types.map { it.name }) } + form.addView(selector) + val headers = EditText(this).apply { hint = "请求头(选填,每行 Name: value)"; minLines = 2; isSaveEnabled = false; inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE } + form.addView(headers) + val tcp = CheckBox(this).apply { text = "RTSP 使用 TCP" }; form.addView(tcp) + val error = Ui.label(this, "", 13f, Ui.muted); form.addView(error) + val dialog = AlertDialog.Builder(this).setTitle("播放网络链接").setView(ScrollView(this).apply { addView(form) }).setPositiveButton("播放", null).setNegativeButton("取消", null).create() + dialog.setOnShowListener { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { + val parsed = runCatching { + val address = url.text.toString().trim() + require(java.net.URI(address).isAbsolute) { "请输入完整播放地址" } + MediaRef(android.net.Uri.parse(address).lastPathSegment?.takeIf(String::isNotBlank) ?: "在线视频", uri = address, + headers = HttpHeaders.parseLines(headers.text.toString()), sourceType = types[selector.selectedItemPosition], + network = NetworkOptions(rtspTransport = if (tcp.isChecked) RtspTransport.TCP else RtspTransport.AUTO)) + } + parsed.onSuccess { ref -> dialog.dismiss(); lifecycleScope.launch { open(ref) } }.onFailure { error.text = "地址或请求头格式不正确" } + } } + dialog.show() + } + private suspend fun open(ref: MediaRef) { + try { + withContext(Dispatchers.IO) { val old = repo.recent.find(ref.id); repo.recent.save(ref, old?.positionMs ?: 0, old?.durationMs) } + startActivity(Intent(this, PlayerActivity::class.java).putExtra("media", ref.id)) + } catch (_: Exception) { Toast.makeText(this, "无法保存播放记录,请检查设备安全存储", Toast.LENGTH_LONG).show() } + } +} + +/** 播放队列只存来源身份;进程重建后至少恢复当前历史条目。 */ +object PlaybackQueue { + var refs: List = emptyList(); private set + fun set(values: List) { refs = values.toList() } +} diff --git a/app/src/main/kotlin/com/ttstd/player/app/PlayerActivity.kt b/app/src/main/kotlin/com/ttstd/player/app/PlayerActivity.kt new file mode 100644 index 0000000..bdfd6ab --- /dev/null +++ b/app/src/main/kotlin/com/ttstd/player/app/PlayerActivity.kt @@ -0,0 +1,244 @@ +package com.ttstd.player.app + +import android.app.AlertDialog +import android.content.Intent +import android.content.pm.ActivityInfo +import android.content.res.Configuration +import android.os.Bundle +import android.provider.OpenableColumns +import android.view.* +import android.widget.* +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat +import androidx.lifecycle.* +import com.ttstd.player.api.* +import com.ttstd.player.library.LibraryFiles +import com.ttstd.player.render.* +import kotlinx.coroutines.launch +import com.ttstd.player.app.Ui.dp + +/** 播放界面只拥有 Surface 与控件;内核/观看会话由 PlayerModel 管理。 */ +class PlayerActivity : AppCompatActivity() { + private lateinit var model: PlayerModel + private val repo by lazy { AppRepository(applicationContext) } + private var surfaceBinding: AutoCloseable? = null + private lateinit var video: FrameLayout + private lateinit var subtitle: TextView + private lateinit var center: TextView + private lateinit var title: TextView + private lateinit var playButton: TextView + private lateinit var time: TextView + private lateinit var seek: SeekBar + private lateinit var information: TextView + private var dragging = false + private var crop = false + private val google = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { + model.googleReturned(it.data?.getLongExtra("position", model.engine.state.value.positionMs) ?: model.engine.state.value.positionMs, + it.data?.getBooleanExtra("playing", true) ?: true) + } + private val pickSubtitle = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) { + runCatching { contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } + val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { if (it.moveToFirst()) it.getString(0) else "" }.orEmpty() + val mime = LibraryFiles.subtitleMime(name) + if (mime == null) Toast.makeText(this, "请选择 SRT、VTT、ASS 或 SSA 字幕", Toast.LENGTH_LONG).show() + else model.attachSubtitle(ExternalSubtitle(uri.toString(), mime, isDefault = true)) + } + } + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + volumeControlStream = android.media.AudioManager.STREAM_MUSIC + model = ViewModelProvider(this)[PlayerModel::class.java] + build() + lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { + launch { model.engine.state.collect { render() } } + launch { model.current.collect { item -> + item?.let { intent.putExtra("media", it.ref.id) } + render() + } } + launch { model.loading.collect { render() } } + launch { model.error.collect { render() } } + launch { model.remote.collect { render() } } + launch { model.notices.collect { Toast.makeText(this@PlayerActivity, it, Toast.LENGTH_LONG).show() } } + launch { model.videoRatio.collect { fitVideo() } } + launch { DlnaSession.state.collect { render() } } + } } + model.open(intent.getStringExtra("media").orEmpty()) + } + private fun build() { + surfaceBinding?.close() + val landscape = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE + val root = FrameLayout(this) + Ui.inset(this, root) + val stack = Ui.column(this) + root.addView(stack, FrameLayout.LayoutParams(-1, -1)) + val toolbar = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL; setPadding(dp(12), dp(8), dp(12), dp(8)); setBackgroundColor(0xd9111822.toInt()) } + toolbar.addView(Ui.button(this, "‹") { finish() }) + title = Ui.label(this, "正在准备视频", 16f, bold = true).apply { maxLines = 2; ellipsize = android.text.TextUtils.TruncateAt.END } + toolbar.addView(title, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(12); marginEnd = dp(12) }) + toolbar.addView(Ui.button(this, "投屏") { castDialog() }) + toolbar.addView(Ui.button(this, "⋮") { menu() }) + video = FrameLayout(this).apply { setBackgroundColor(android.graphics.Color.BLACK); clipChildren = true } + subtitle = Ui.label(this, "", 20f).apply { + gravity = Gravity.CENTER; setPadding(dp(20), dp(4), dp(20), dp(16)) + setShadowLayer(dp(2).toFloat(), 0f, 1f, android.graphics.Color.BLACK) + isClickable = false + } + center = Ui.label(this, "", 16f).apply { gravity = Gravity.CENTER; setBackgroundColor(0x77101822) } + val surface: View = if (repo.preferences.texture) TextureView(this) else SurfaceView(this) + video.addView(surface, FrameLayout.LayoutParams(-1, -1, Gravity.CENTER)) + video.addView(subtitle, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM)) + video.addView(center, FrameLayout.LayoutParams(-1, -1)) + val controls = Ui.column(this, 16).apply { setBackgroundColor(0xee101822.toInt()) } + time = Ui.label(this, "0:00 / --:--", 13f, Ui.muted) + controls.addView(time) + seek = SeekBar(this).apply { max = 1000 } + controls.addView(seek, LinearLayout.LayoutParams(-1, dp(44))) + seek.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { + override fun onStartTrackingTouch(seekBar: SeekBar) { dragging = true } + override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) = Unit + override fun onStopTrackingTouch(seekBar: SeekBar) { + dragging = false + val duration = currentDuration() ?: return + val target = duration * seekBar.progress / 1000 + if (model.remote.value == "dlna") startService(Intent(this@PlayerActivity, DlnaPlaybackService::class.java).setAction("seek").putExtra("position", target)) + else model.seek(target) + } + }) + val buttons = LinearLayout(this).apply { gravity = Gravity.CENTER } + fun control(label: String, primary: Boolean = false, action: () -> Unit): TextView = Ui.button(this, label, primary, action).also { + buttons.addView(it, LinearLayout.LayoutParams(0, dp(52), 1f).apply { marginStart = dp(3); marginEnd = dp(3) }) + } + control("上一部") { model.next(-1) } + control("−10s") { seekBy(-10000) } + playButton = control("播放", true) { + if (model.remote.value == "dlna") DlnaSession.command(this, if (DlnaSession.state.value.playback.playing) "pause" else "play") else model.toggle() + } + control("+10s") { seekBy(10000) } + control("下一部") { model.next(1) } + controls.addView(buttons) + information = Ui.label(this, "", 13f, Ui.muted).apply { setPadding(0, dp(14), 0, dp(8)) } + controls.addView(information) + controls.addView(Ui.button(this, if (landscape) "退出全屏" else "全屏播放") { + requestedOrientation = if (landscape) ActivityInfo.SCREEN_ORIENTATION_PORTRAIT else ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + }) + if (landscape) { + root.removeView(stack) + root.addView(video, FrameLayout.LayoutParams(-1, -1)) + root.addView(toolbar, FrameLayout.LayoutParams(-1, -2, Gravity.TOP)) + root.addView(controls, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM)) + subtitle.setPadding(dp(24), dp(4), dp(24), dp(240)) + } else { + stack.addView(toolbar) + stack.addView(video, LinearLayout.LayoutParams(-1, (resources.displayMetrics.widthPixels * 9 / 16).coerceAtLeast(dp(180)))) + val scroll = ScrollView(this).apply { addView(controls) } + stack.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f)) + } + val gesture = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() { + override fun onDown(e: android.view.MotionEvent) = true + override fun onDoubleTap(e: android.view.MotionEvent): Boolean { + if (model.remote.value == null) model.seek((model.absolutePosition() + if (e.x < video.width / 2) -10000 else 10000).coerceAtLeast(0)) + return true + } + override fun onSingleTapConfirmed(e: android.view.MotionEvent): Boolean { + if (landscape) { toolbar.visibility = if (toolbar.visibility == View.VISIBLE) View.GONE else View.VISIBLE; controls.visibility = toolbar.visibility } + return true + } + }) + video.setOnTouchListener { _, event -> gesture.onTouchEvent(event) } + center.setOnClickListener { if (model.error.value != null || model.engine.state.value.phase == PlaybackPhase.ERROR) model.retry() } + setContentView(root) + WindowInsetsControllerCompat(window, root).apply { if (landscape) hide(WindowInsetsCompat.Type.systemBars()) else show(WindowInsetsCompat.Type.systemBars()) } + video.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> fitVideo() } + surfaceBinding = if (surface is TextureView) TextureViewBinding(surface, model.engine) else SurfaceViewBinding(surface as SurfaceView, model.engine) + render() + } + private fun currentDuration(): Long? = if (model.remote.value == "dlna") DlnaSession.state.value.playback.durationMs else model.duration() + private fun render() { + if (!::center.isInitialized) return + val state = model.engine.state.value + val remote = model.remote.value + val error = model.error.value ?: state.error?.message + title.text = model.current.value?.ref?.title ?: "正在准备视频" + val pos = if (remote == "dlna") DlnaSession.state.value.playback.positionMs else model.absolutePosition() + val duration = currentDuration() + time.text = "${Ui.time(pos)} / ${duration?.let(Ui::time) ?: "--:--"}" + if (!dragging && duration != null && duration > 0) seek.progress = (pos * 1000 / duration).coerceIn(0, 1000).toInt() + seek.isEnabled = duration != null && duration > 0 + val playing = if (remote == "dlna") DlnaSession.state.value.playback.playing else state.playWhenReady + playButton.text = if (playing) "暂停" else "播放" + subtitle.text = if (remote == null) state.subtitleLines.joinToString("\n") else "" + center.text = when { + remote == "dlna" -> "正在 ${DlnaSession.state.value.device} 播放\n${DlnaSession.state.value.error ?: "可关闭页面,投屏会继续"}" + model.loading.value || state.phase in setOf(PlaybackPhase.PREPARING, PlaybackPhase.BUFFERING) -> "正在缓冲…" + error != null -> "$error\n点击重试" + state.phase == PlaybackPhase.ENDED -> "播放结束" + else -> "" + } + center.visibility = if (center.text.isEmpty()) View.GONE else View.VISIBLE + information.text = if (remote != null) "投屏中 · 点击右上角投屏管理连接" else "${if (model.current.value?.ref?.accountId != null) "媒体来源播放" else "本机 / 在线播放"} · 双击画面快进 / 后退\n音轨、字幕、倍速与显示选项在更多菜单中" + if (state.isPlaying && remote == null) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + private fun seekBy(delta: Long) { + if (model.remote.value == "dlna") startService(Intent(this, DlnaPlaybackService::class.java).setAction("seek") + .putExtra("position", (DlnaSession.state.value.playback.positionMs + delta).coerceAtLeast(0))) + else model.seek((model.absolutePosition() + delta).coerceAtLeast(0)) + } + private fun fitVideo() { + if (!::video.isInitialized) return + val child = video.getChildAt(0) ?: return + val ratio = model.videoRatio.value + if (video.width <= 0 || video.height <= 0 || ratio <= 0) return + val width = if (crop) maxOf(video.width, (video.height * ratio).toInt()) else minOf(video.width, (video.height * ratio).toInt()) + val height = if (crop) maxOf(video.height, (video.width / ratio).toInt()) else minOf(video.height, (video.width / ratio).toInt()) + if (child.layoutParams.width != width || child.layoutParams.height != height) child.layoutParams = FrameLayout.LayoutParams(width, height, Gravity.CENTER) + } + private fun menu() { + if (model.remote.value == "dlna") { castDialog(); return } + val labels = arrayOf("音轨", "字幕", "加载外挂字幕", "播放速度", "显示比例:${if (crop) "填充" else "适应"}", "收藏 / 取消收藏", "视频显示方式", "解码方式") + AlertDialog.Builder(this).setTitle("播放选项").setItems(labels) { _, index -> when (index) { + 0 -> tracks(TrackType.AUDIO) + 1 -> tracks(TrackType.TEXT) + 2 -> pickSubtitle.launch(arrayOf("*/*")) + 3 -> AlertDialog.Builder(this).setTitle("播放速度").setItems(arrayOf("0.5×", "0.75×", "1×", "1.25×", "1.5×", "2×")) { _, i -> model.setSpeed(listOf(.5f, .75f, 1f, 1.25f, 1.5f, 2f)[i]) }.show() + 4 -> { crop = !crop; fitVideo() } + 5 -> { model.favorite(); Toast.makeText(this, "收藏已更新", Toast.LENGTH_SHORT).show() } + 6 -> { repo.preferences.texture = !repo.preferences.texture; build() } + 7 -> AlertDialog.Builder(this).setTitle("解码方式").setItems(arrayOf("自动选择", "优先硬解", "仅硬解", "仅系统软解")) { _, i -> model.setDecoder(DecodeMode.entries[i]) }.show() + } }.show() + } + private fun tracks(type: TrackType) { + val list = model.engine.state.value.tracks.filter { it.type == type } + val options = if (type == TrackType.TEXT) listOf("关闭字幕") else listOf("自动选择") + AlertDialog.Builder(this).setTitle(if (type == TrackType.TEXT) "字幕" else "音轨") + .setItems((options + list.map { "${it.label ?: it.language ?: "轨道 ${it.id}"}${if (it.selected) " ✓" else ""}" }).toTypedArray()) { _, index -> + model.selectTrack(if (index == 0) TrackSelection(type, disabled = type == TrackType.TEXT) else TrackSelection(type, list[index - 1].id)) + }.show() + } + private fun castDialog() { + if (model.remote.value == "dlna") { + AlertDialog.Builder(this).setTitle(DlnaSession.state.value.device).setItems(arrayOf("播放", "暂停", "后退 30 秒", "前进 30 秒", "结束投屏并返回本机")) { _, index -> + DlnaSession.command(this, listOf("play", "pause", "back", "forward", "stop")[index]) + }.show(); return + } + AlertDialog.Builder(this).setTitle("投屏到设备").setItems(arrayOf("DLNA · 电视 / 盒子", "Google Cast")) { _, index -> + lifecycleScope.launch { + if (index == 1) model.googleIntent()?.let(google::launch) else { + val progress = AlertDialog.Builder(this@PlayerActivity).setMessage("正在搜索同一局域网的电视…").create(); progress.show() + try { + val devices = model.devices(); progress.dismiss() + if (devices.isEmpty()) Toast.makeText(this@PlayerActivity, "未发现设备,请确认电视投屏已开启", Toast.LENGTH_LONG).show() + else AlertDialog.Builder(this@PlayerActivity).setTitle("选择电视").setItems(devices.map { it.name }.toTypedArray()) { _, i -> model.dlna(devices[i]) }.show() + } catch (cancelled: kotlinx.coroutines.CancellationException) { progress.dismiss(); throw cancelled } + catch (_: Exception) { progress.dismiss(); Toast.makeText(this@PlayerActivity, "设备搜索失败,请检查网络", Toast.LENGTH_LONG).show() } + } + } + }.show() + } + override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig); build() } + override fun onStart() { super.onStart(); model.onVisible() } + override fun onStop() { model.onHidden(isChangingConfigurations); super.onStop() } + override fun onDestroy() { surfaceBinding?.close(); surfaceBinding = null; super.onDestroy() } +} diff --git a/app/src/main/kotlin/com/ttstd/player/app/PlayerModel.kt b/app/src/main/kotlin/com/ttstd/player/app/PlayerModel.kt new file mode 100644 index 0000000..554f780 --- /dev/null +++ b/app/src/main/kotlin/com/ttstd/player/app/PlayerModel.kt @@ -0,0 +1,219 @@ +package com.ttstd.player.app + +import android.app.Application +import android.content.Intent +import androidx.core.content.ContextCompat +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import com.ttstd.player.api.* +import com.ttstd.player.cast.* +import com.ttstd.player.cast.dlna.* +import com.ttstd.player.cast.google.* +import com.ttstd.player.cast.relay.CastRelay +import com.ttstd.player.library.* +import com.ttstd.player.library.media3.LibraryPlaybackTracker +import com.ttstd.player.media3.Media3Engine +import com.ttstd.player.media3.source.Media3FileCache +import com.ttstd.player.telemetry.PlaybackTelemetry +import com.ttstd.player.telemetry.TelemetrySink +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.* + +object AppPlaybackRuntime { + private var localOwners = 0 + val localActive: Boolean get() = localOwners > 0 + fun acquireLocal() { localOwners++ } + fun releaseLocal() { localOwners = (localOwners - 1).coerceAtLeast(0) } + var googleMedia: CastMedia? = null + var googleMediaId: String? = null + var googleOffsetMs: Long = 0 +} + +/** 播放器归 ViewModel 所有,Surface 和界面归 Activity 所有;旋转只重绑输出。 */ +class PlayerModel(application: Application) : AndroidViewModel(application) { + val engine = Media3Engine(application) + private val repo = AppRepository(application) + private val tracker = LibraryPlaybackTracker(application, engine, viewModelScope) + private val telemetry = PlaybackTelemetry(engine, viewModelScope, java.util.UUID.randomUUID().toString(), + TelemetrySink { name, attributes -> android.util.Log.d("TTVideoPlayer", "$name $attributes") }) + val current = MutableStateFlow(null) + val error = MutableStateFlow(null) + val notices = MutableSharedFlow(extraBufferCapacity = 16) + val loading = MutableStateFlow(false) + val remote = MutableStateFlow(null) + val videoRatio = MutableStateFlow(16f / 9f) + var playback: LibraryPlayback? = null; private set + private var loadJob: Job? = null + private var resumeOnVisible = false + private var historyAt = 0L + private var visible = false + init { + AppPlaybackRuntime.acquireLocal() + viewModelScope.launch { engine.events.collect { event -> + if (event is PlaybackEvent.VideoSize && event.height > 0) videoRatio.value = event.width * event.pixelRatio / event.height + } } + viewModelScope.launch { engine.state.collect { state -> + if (!loading.value && remote.value == null && state.phase !in setOf(PlaybackPhase.IDLE, PlaybackPhase.RELEASED, PlaybackPhase.PREPARING)) { + val now = android.os.SystemClock.elapsedRealtime() + if (now - historyAt >= 5000 || !state.playWhenReady || state.phase == PlaybackPhase.ENDED) { + checkpointHistory(state, now) + } + } + } } + // 引擎事件在厂商实现上可能不按秒分发;独立时钟保证播放中至少每五秒落盘一次。 + viewModelScope.launch { + while (isActive) { + delay(5_000) + val state = engine.state.value + if (!loading.value && remote.value == null && state.phase !in setOf(PlaybackPhase.IDLE, PlaybackPhase.RELEASED, PlaybackPhase.PREPARING)) + checkpointHistory(state, android.os.SystemClock.elapsedRealtime()) + } + } + viewModelScope.launch { DlnaSession.state.collect { state -> + if (remote.value == "dlna" && !state.active && !loading.value) { + remote.value = null + state.error?.let { error.value = it } + resumeOnVisible = state.playback.playing && !visible + resumeLocal(state.playback.positionMs, state.playback.playing && visible) + } + } } + } + fun open(id: String) { + if (current.value?.ref?.id == id && playback != null) return + loadJob?.cancel() + loadJob = viewModelScope.launch { + loading.value = true; error.value = null + try { + tracker.close(); engine.pause() + val item = withContext(Dispatchers.IO) { repo.recent.find(id) } ?: throw LibraryException("播放记录已移除,请重新选择视频") + current.value = item + playResolved(repo.resolve(item.ref, item.positionMs), true) + } catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { error.value = SourceDialogs.safeError(e) } + finally { loading.value = false } + } + } + private suspend fun playResolved(value: LibraryPlayback, autoplay: Boolean) { + tracker.close() + if (value.request.cacheKey != null) withContext(Dispatchers.IO) { runCatching { Media3FileCache.get(getApplication()) } } + engine.setDecodePolicy(DecodePolicy(video = repo.preferences.decoder)) + val result = engine.prepare(value.request.copy(autoplay = autoplay)) + if (result != CommandResult.Accepted) throw LibraryException("媒体无法加载,请检查播放地址与设置") + playback = value; tracker.bind(value) + } + fun retry() { val id = current.value?.ref?.id ?: return; playback = null; open(id) } + fun toggle() { viewModelScope.launch { if (engine.state.value.playWhenReady) engine.pause() else engine.play() } } + fun seek(position: Long) { viewModelScope.launch { + val p = playback ?: return@launch + if (p.positionOffsetMs > 0) resumeLocal((position - p.positionOffsetMs).coerceAtLeast(-p.positionOffsetMs), engine.state.value.playWhenReady) + else { val result = engine.seekTo(position); if (result != CommandResult.Accepted) notices.tryEmit("此来源暂不支持拖动") } + } } + fun next(direction: Int) { + if (remote.value != null) { notices.tryEmit("请先结束投屏,再切换视频"); return } + val refs = PlaybackQueue.refs + val index = refs.indexOfFirst { it.id == current.value?.ref?.id } + val next = refs.getOrNull(index + direction) ?: run { notices.tryEmit("没有更多视频"); return } + viewModelScope.launch { + withContext(Dispatchers.IO) { val old = repo.recent.find(next.id); repo.recent.save(next, old?.positionMs ?: next.entry?.resumeMs ?: 0, old?.durationMs) } + playback = null; open(next.id) + } + } + fun favorite() { val id = current.value?.ref?.id ?: return; viewModelScope.launch { + withContext(Dispatchers.IO) { repo.recent.favorite(id) } + current.value = withContext(Dispatchers.IO) { repo.recent.find(id) } + } } + fun setSpeed(value: Float) { viewModelScope.launch { engine.setSpeed(value) } } + fun setDecoder(value: DecodeMode) { repo.preferences.decoder = value; viewModelScope.launch { engine.setDecodePolicy(DecodePolicy(video = value)) } } + fun selectTrack(selection: TrackSelection) { viewModelScope.launch { engine.selectTrack(selection) } } + fun attachSubtitle(subtitle: ExternalSubtitle) { viewModelScope.launch { + val item = current.value ?: return@launch + val ref = item.ref.copy(extraSubtitles = listOf(subtitle)) + val pos = absolutePosition() + withContext(Dispatchers.IO) { repo.recent.save(ref, pos, item.durationMs) } + current.value = item.copy(ref = ref) + resumeLocal(engine.state.value.positionMs, engine.state.value.playWhenReady) + } } + fun onVisible() { visible = true; if (resumeOnVisible && remote.value == null) { resumeOnVisible = false; viewModelScope.launch { engine.play() } } } + fun onHidden(changingConfiguration: Boolean) { + if (!changingConfiguration) visible = false + tracker.checkpoint() + checkpointHistory(engine.state.value, android.os.SystemClock.elapsedRealtime(), force = true) + if (!changingConfiguration && remote.value == null) { resumeOnVisible = engine.state.value.playWhenReady; viewModelScope.launch { engine.pause() } } + } + private fun checkpointHistory(state: PlaybackState, now: Long, force: Boolean = false) { + val item = current.value ?: return + if (!force && now - historyAt < 5_000) return + historyAt = now + val p = state.positionMs + (playback?.positionOffsetMs ?: 0) + val d = playback?.originalDurationMs ?: state.durationMs?.plus(playback?.positionOffsetMs ?: 0) + viewModelScope.launch(Dispatchers.IO) { + runCatching { repo.recent.save(item.ref, if (d != null && d - p < 3_000) 0 else p, d) } + } + } + fun absolutePosition() = engine.state.value.positionMs + (playback?.positionOffsetMs ?: 0) + fun duration() = playback?.originalDurationMs ?: engine.state.value.durationMs?.plus(playback?.positionOffsetMs ?: 0) + suspend fun resumeLocal(position: Long, playing: Boolean) { + val item = current.value ?: return + loading.value = true; error.value = null + try { playResolved(repo.resolve(item.ref, (position + (playback?.positionOffsetMs ?: 0)).coerceAtLeast(0)), playing) } + catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { error.value = SourceDialogs.safeError(e) } + finally { loading.value = false } + } + private fun media(relay: CastRelay): CastMedia { + val p = playback ?: throw LibraryException("请先加载视频") + val request = p.receiverRequest ?: p.request + val decision = CastPolicy.assess(request) + require(decision.route != CastRoute.UNSUPPORTED) { decision.reason } + val uri = if (decision.route == CastRoute.DIRECT) request.uri else relay.publish(request, decision.mimeType, p.contentLength) + return CastMedia(uri, p.title, decision.mimeType, engine.state.value.positionMs) + } + suspend fun devices(): List = DlnaController(getApplication()).discover() + fun dlna(device: DlnaDevice) { viewModelScope.launch { + if (DlnaSession.state.value.active || DlnaSession.resourcesOpen) { notices.tryEmit("请先结束当前电视投屏并等待连接释放"); return@launch } + val p = playback ?: return@launch + val relay = CastRelay(getApplication()) + try { + val media = media(relay) + DlnaSession.lease = DlnaLease(device, media, castObserver(p), relay::close, current.value!!.ref.id, p.positionOffsetMs) + DlnaSession.resourcesOpen = true + DlnaSession.state.value = DlnaUiState(true, true, media.title, device.name, RemotePlaybackState(media.startPositionMs)) + tracker.detach(); engine.pause(); remote.value = "dlna" + ContextCompat.startForegroundService(getApplication(), Intent(getApplication(), DlnaPlaybackService::class.java)) + } catch (_: Exception) { relay.close(); DlnaSession.resourcesOpen = false; remote.value = null; notices.tryEmit("无法启动电视投屏"); resumeLocal(engine.state.value.positionMs, true) } + } } + suspend fun googleIntent(): Intent? { + val p = playback ?: return null + val relay = CastRelay(getApplication()) + return try { + val value = media(relay) + GoogleCastResources.hold(castObserver(p), relay::close) + AppPlaybackRuntime.googleMedia = value + AppPlaybackRuntime.googleMediaId = current.value?.ref?.id + AppPlaybackRuntime.googleOffsetMs = p.positionOffsetMs + tracker.detach(); engine.pause(); remote.value = "google" + GoogleCastActivity.intent(getApplication(), value) + } catch (e: Exception) { relay.close(); notices.tryEmit(e.message ?: "该视频不能投屏"); null } + } + fun googleReturned(position: Long, playing: Boolean) { remote.value = null; viewModelScope.launch { resumeLocal(position, playing) } } + private fun castObserver(value: LibraryPlayback): CastProgressObserver { + val ref = current.value!!.ref + val store = repo.recent + return object : CastProgressObserver { + override suspend fun started(positionMs: Long) { value.session?.started(positionMs) } + override suspend fun progress(state: RemotePlaybackState) { + withContext(Dispatchers.IO) { store.save(ref, state.positionMs + value.positionOffsetMs, value.originalDurationMs ?: state.durationMs?.plus(value.positionOffsetMs)) } + value.session?.progress(state.positionMs, !state.playing) + } + override suspend fun stopped(positionMs: Long) { + withContext(Dispatchers.IO) { store.save(ref, positionMs + value.positionOffsetMs, value.originalDurationMs) } + value.session?.stopped(positionMs) + } + } + } + override fun onCleared() { + tracker.close(); telemetry.close(); AppPlaybackRuntime.releaseLocal() + CoroutineScope(Dispatchers.Main.immediate).launch { engine.release() } + super.onCleared() + } +} diff --git a/app/src/main/kotlin/com/ttstd/player/app/SourceDialogs.kt b/app/src/main/kotlin/com/ttstd/player/app/SourceDialogs.kt new file mode 100644 index 0000000..9407d01 --- /dev/null +++ b/app/src/main/kotlin/com/ttstd/player/app/SourceDialogs.kt @@ -0,0 +1,74 @@ +package com.ttstd.player.app + +import android.app.AlertDialog +import android.text.InputType +import android.widget.* +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.lifecycleScope +import com.ttstd.player.library.* +import kotlinx.coroutines.* +import java.net.URI +import java.util.UUID +import com.ttstd.player.app.Ui.dp + +/** 来源编辑与连接测试共用同一个校验边界,保存前不向服务器发起请求。 */ +object SourceDialogs { + fun edit(activity: AppCompatActivity, existing: LibraryAccount? = null, saved: () -> Unit) { + val repo = AppRepository(activity.applicationContext) + val form = Ui.column(activity, 20) + val kinds = LibraryKind.entries + form.addView(Ui.label(activity, "选择连接方式", 13f, Ui.muted)) + val kind = Spinner(activity).apply { + adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_dropdown_item, listOf("WebDAV · 网盘 / NAS", "SMB · 局域网共享", "Jellyfin · 媒体服务器")) + setSelection(kinds.indexOf(existing?.kind ?: LibraryKind.WEBDAV)) + } + form.addView(kind) + fun input(label: String, value: String, secret: Boolean = false): EditText { + form.addView(Ui.label(activity, label, 13f, Ui.muted).apply { setPadding(0, activity.dp(12), 0, 0) }) + return EditText(activity).apply { + setSingleLine(true); isSaveEnabled = false + inputType = InputType.TYPE_CLASS_TEXT or if (secret) InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS + setText(value); form.addView(this) + } + } + val name = input("名称", existing?.name.orEmpty()) + val endpoint = input("服务地址(SMB 需包含共享名)", existing?.endpoint.orEmpty()).apply { hint = "https://nas.example/dav/" } + val user = input("用户名", existing?.username.orEmpty()) + val password = input("密码 / 应用专用密码", existing?.password.orEmpty(), true) + val domain = input("SMB 域(选填)", existing?.domain.orEmpty()) + val status = Ui.label(activity, "凭证加密保存在本机。WebDAV 支持匿名与 Basic 认证。", 12f, Ui.muted) + form.addView(status) + fun account(): LibraryAccount { + val selected = kinds[kind.selectedItemPosition] + val uri = runCatching { URI(endpoint.text.toString().trim()) }.getOrNull() + require(name.text.isNotBlank() && uri?.host != null && uri.userInfo == null && uri.query == null && uri.fragment == null) { "请填写名称和正确的服务根地址" } + require(if (selected == LibraryKind.SMB) uri.scheme == "smb" && uri.path.trim('/').isNotEmpty() else uri.scheme in setOf("http", "https")) { "地址与连接方式不匹配" } + return LibraryAccount(existing?.id ?: UUID.randomUUID().toString(), name.text.toString().trim(), selected, uri.toASCIIString(), + user.text.toString(), password.text.toString(), domain.text.toString()) + } + val test = Ui.button(activity, "测试连接") { + val value = runCatching { account() }.getOrElse { status.text = it.message; return@button } + status.text = "正在连接…" + activity.lifecycleScope.launch { + try { val page = withContext(Dispatchers.IO) { repo.library(value).list() }; status.text = "连接成功,当前目录 ${page.entries.size} 项" } + catch (cancelled: CancellationException) { throw cancelled } + catch (e: Exception) { status.text = safeError(e) } + } + } + form.addView(test) + val dialog = AlertDialog.Builder(activity).setTitle(if (existing == null) "添加媒体来源" else "编辑来源") + .setView(ScrollView(activity).apply { addView(form) }).setPositiveButton("保存", null).setNegativeButton("取消", null).create() + dialog.setOnShowListener { + dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { button -> + val value = runCatching { account() }.getOrElse { status.text = it.message; return@setOnClickListener } + button.isEnabled = false + activity.lifecycleScope.launch { + try { withContext(Dispatchers.IO) { repo.accounts.save(value) }; dialog.dismiss(); saved() } + catch (_: Exception) { status.text = "保存失败,请检查设备安全存储"; button.isEnabled = true } + } + } + } + dialog.show() + } + fun safeError(error: Exception) = if (error is LibraryException) error.message ?: "来源请求失败" else "连接失败,请检查地址、账户和网络" +} diff --git a/app/src/main/kotlin/com/ttstd/player/app/Ui.kt b/app/src/main/kotlin/com/ttstd/player/app/Ui.kt new file mode 100644 index 0000000..d37f74b --- /dev/null +++ b/app/src/main/kotlin/com/ttstd/player/app/Ui.kt @@ -0,0 +1,73 @@ +package com.ttstd.player.app + +import android.content.Context +import android.content.res.ColorStateList +import android.graphics.Color +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.graphics.drawable.RippleDrawable +import android.view.Gravity +import android.view.View +import android.widget.* +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat +import androidx.core.view.doOnAttach + +/** 轻量原生界面组件,触摸目标至少 48dp,同时支持键盘焦点与大字体。 */ +object Ui { + val bg = Color.rgb(12, 18, 28) + val panel = Color.rgb(22, 32, 46) + val raised = Color.rgb(31, 44, 61) + val ink = Color.rgb(236, 243, 249) + val muted = Color.rgb(149, 168, 188) + val accent = Color.rgb(100, 227, 190) + fun Context.dp(value: Int) = (value * resources.displayMetrics.density).toInt() + fun shape(color: Int, radius: Float = 18f) = GradientDrawable().apply { setColor(color); cornerRadius = radius } + fun label(context: Context, value: String, size: Float = 15f, color: Int = ink, bold: Boolean = false) = TextView(context).apply { + text = value; textSize = size; setTextColor(color) + if (bold) setTypeface(typeface, Typeface.BOLD) + } + fun column(context: Context, padding: Int = 0) = LinearLayout(context).apply { + orientation = LinearLayout.VERTICAL + setPadding(context.dp(padding), context.dp(padding), context.dp(padding), context.dp(padding)) + } + fun button(context: Context, title: String, primary: Boolean = false, action: () -> Unit) = TextView(context).apply { + text = title; textSize = 15f; gravity = Gravity.CENTER; minHeight = context.dp(48); minimumWidth = context.dp(48) + setPadding(context.dp(16), context.dp(8), context.dp(16), context.dp(8)) + setTextColor(if (primary) bg else ink) + background = RippleDrawable(ColorStateList.valueOf(0x2264e3be), shape(if (primary) accent else raised, context.dp(14).toFloat()), null) + isFocusable = true; isClickable = true; contentDescription = title; setOnClickListener { action() } + } + fun card(context: Context, title: String, subtitle: String, action: (() -> Unit)? = null): LinearLayout = column(context, 18).apply { + background = shape(panel, context.dp(18).toFloat()) + addView(label(context, title, 18f, bold = true)) + addView(label(context, subtitle, 13f, muted).apply { setPadding(0, context.dp(8), 0, 0) }) + layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = context.dp(12) } + if (action != null) { isFocusable = true; isClickable = true; setOnClickListener { action() } } + } + fun inset(activity: AppCompatActivity, view: View) { + view.setBackgroundColor(bg) + // API 35 的窗口在 setContentView 前尚无 DecorView,等根视图附着后再访问控制器。 + view.doOnAttach { + WindowInsetsControllerCompat(activity.window, view).apply { isAppearanceLightStatusBars = false; isAppearanceLightNavigationBars = false } + ViewCompat.requestApplyInsets(view) + } + ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets -> + val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime()) + v.setPadding(bars.left, bars.top, bars.right, bars.bottom); insets + } + } + fun empty(context: Context, title: String, description: String) = column(context, 28).apply { + gravity = Gravity.CENTER; minimumHeight = context.dp(220) + addView(label(context, "▷", 52f, accent)) + addView(label(context, title, 20f, bold = true)) + addView(label(context, description, 14f, muted).apply { gravity = Gravity.CENTER; setPadding(0, context.dp(12), 0, 0) }) + } + fun time(ms: Long): String { + val s = ms.coerceAtLeast(0) / 1000 + return if (s >= 3600) "%d:%02d:%02d".format(s / 3600, s / 60 % 60, s % 60) else "%d:%02d".format(s / 60, s % 60) + } + fun bytes(value: Long): String = if (value >= 1024L * 1024 * 1024) "%.1f GB".format(value / (1024.0 * 1024 * 1024)) else "%.1f MB".format(value / (1024.0 * 1024)) +} diff --git a/app/src/main/res/drawable/ic_app.xml b/app/src/main/res/drawable/ic_app.xml new file mode 100644 index 0000000..a072534 --- /dev/null +++ b/app/src/main/res/drawable/ic_app.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..a19e120 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + 同同影音 + 你的媒体,随处播放 + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..f43b48a --- /dev/null +++ b/app/src/main/res/values/styles.xml @@ -0,0 +1,13 @@ + + + diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 0000000..c5fa274 --- /dev/null +++ b/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/app/src/test/kotlin/com/ttstd/player/app/RecentStoreTest.kt b/app/src/test/kotlin/com/ttstd/player/app/RecentStoreTest.kt new file mode 100644 index 0000000..8bba5ca --- /dev/null +++ b/app/src/test/kotlin/com/ttstd/player/app/RecentStoreTest.kt @@ -0,0 +1,33 @@ +package com.ttstd.player.app + +import com.ttstd.player.api.* +import com.ttstd.player.library.LibraryEntry +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class RecentStoreTest { + @Test fun signedLinkSettingsAndSubtitlesSurviveProcessRestoration() { + val ref = MediaRef("测试视频", uri = "https://host/movie?token=secret", + headers = mapOf("Authorization" to "Bearer secret"), sourceType = MediaSourceType.HLS, + network = NetworkOptions(4000, 12000, 15000, RtspTransport.TCP), + extraSubtitles = listOf(ExternalSubtitle("content://subtitles/1", "application/x-subrip", "zh", true))) + val item = RecentMedia(ref, 43210, 99999, 123456, true) + assertEquals(item, RecentStore.decode(RecentStore.encode(item))) + assertFalse(ref.toString().contains("secret")) + assertFalse(ref.toString().contains("host")) + } + + @Test fun sourceIdentityRetainsVersionAndServerResumeWithoutTemporaryUrl() { + val ref = MediaRef("影片", "account-1", LibraryEntry("/movie.mp4", "影片", false, 12345, "etag-2", 8000)) + val restored = RecentStore.decode(RecentStore.encode(RecentMedia(ref, 9000))) + assertEquals(ref, restored.ref) + assertEquals(ref.id, restored.ref.id) + assertNull(restored.ref.uri) + assertNotEquals(ref.id, ref.copy(accountId = "another-account").id) + } +} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..5bee9c5 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,6 @@ +plugins { + id("com.android.library") version "8.13.2" apply false + id("com.android.application") version "8.13.2" apply false + kotlin("android") version "2.4.21" apply false + kotlin("jvm") version "2.4.21" apply false +} diff --git a/docs/app.md b/docs/app.md new file mode 100644 index 0000000..f0f8bb4 --- /dev/null +++ b/docs/app.md @@ -0,0 +1,53 @@ +# 同同影音 1.0.0 + +完整 Android App 位于 `app/`,最低 Android 6.0(API 23)。播放协议、媒体来源、投屏传输均复用独立 module,UI 不直接操作 ExoPlayer。`app-demo` 继续用于最小接入演示。 + +## 使用 + +1. 首页「打开本地视频」调用系统文件选择器,支持多选;「播放链接」支持协议选择、请求头与 RTSP TCP。 +2. 「来源」添加 WebDAV、SMB 或 Jellyfin,可先测试连接,再保存。WebDAV 地址示例 `https://nas.example/dav/`,SMB 示例 `smb://192.168.1.10/videos/`,Jellyfin 填服务根地址。反向代理的路径前缀应保留。 +3. 打开来源,浏览文件夹、筛选当前目录、加载下一页,点击视频播放,长按收藏。网盘通过其 WebDAV 接口或 OpenList 等网关接入;没有实现各商业网盘的独立登录 SDK。 +4. 播放页支持拖动、前后跳转、上一部/下一部、全屏、音轨、字幕、外部字幕、倍速、画面适配、Surface/Texture、硬软解策略。双击画面左右区域跳转 10 秒。 +5. 「历史」继续播放、从头播放、收藏与移除。「设置」配置默认解码/渲染/同名字幕,查看和清理缓存。 +6. 加载视频后点「投屏」。DLNA 搜索同一局域网中的电视,Google Cast 打开路由选择。私有普通文件由手机代理给电视,手机需保持联网。退出播放页后可从首页或系统媒体通知继续控制 DLNA。 + +## 功能与边界 + +| 功能 | 实现 | +| --- | --- | +| 本地文件 | SAF 持久授权,多个视频组成当前进程的播放队列 | +| 在线 | HTTP(S) 文件、HLS、DASH、SmoothStreaming、HTTP-FLV、RTMP、RTSP | +| WebDAV | 匿名/Basic,来源根目录内浏览、同名字幕、带鉴权播放 | +| SMB/NAS | SMB2/3 浏览与随机读取;不支持 SMB1 | +| Jellyfin | 登录、媒体库分页、PlaybackInfo 能力协商、直放/HLS 转码、观看进度和停止转码 | +| 字幕 | 文本字幕状态进入平台无关接口,UI 显示文本;支持选择轨道和 SAF 外挂 SRT/VTT/ASS/SSA;不完整保留 ASS 特效或位图字幕 | +| 续播 | 本机历史保存稳定来源身份,重新解析临时链接;Jellyfin 同步服务端进度 | +| 缓存 | 普通文件按需缓存,256 MB LRU;不缓存自适应流,不提供完整离线下载 | +| 解码 | 系统 MediaCodec 硬解/系统软件解码筛选;无 FFmpeg 通用视频软解,无跨内核回退 | +| DLNA | SSDP 发现、加载/暂停/播放/seek/停止,前台服务与媒体通知 | +| Google Cast | Media3 CastPlayer + MediaSessionService,路由选择及回切 | + +SRT/RIST、WebRTC、DRM、AirPlay、网盘专有认证和 Emby/Plex 等独立服务适配尚未实现。投屏接收端是否能解码取决于电视;不支持的封装/编码需由 Jellyfin 等服务器转码。带私有鉴权的自适应流不能通过当前文件代理投屏。没有真实 NAS/电视时,不能把接口测试当作设备兼容验收。 + +## 所有权与生命周期 + +- `PlayerModel`(AndroidViewModel)持有内核、进度协调器和日志采集器;`PlayerActivity` 只持有渲染绑定与 UI。旋转或全屏只重绑输出,不重建播放内核。 +- 本机播放进入后台暂停,手动暂停后返回前台不自动播放;销毁 ViewModel 最终释放内核。进程重建从加密记录恢复当前条目,队列不跨进程保存。 +- DLNA 的设备会话、进度上报和 token 代理交给 `DlnaPlaybackService`,页面退出不会关闭代理。释放期间阻止开启新会话;系统杀进程后不伪造远端连接恢复。 +- Google Cast 资源由应用级持有器和媒体服务管理。接收端继续播放/停止、返回本机的路径由 Cast 会话驱动。 +- Jellyfin HLS 从转码起点重新计时,界面/历史使用原片绝对时间,服务端会话按适配层偏移换算。 + +## 数据与安全 + +账户由 `library-storage` 使用 Android Keystore 加密。完整历史(含用户输入的 token URL、请求头、外部字幕 URI)也使用 AES-GCM 加密,不提供明文回退;页面 Intent 只传记录 ID。来源文件记录账户 ID、路径与版本,不持久化 Jellyfin 临时 URL。应用关闭备份/设备迁移,避免密文脱离设备密钥;设备密钥失效时需重新配置。 + +日志埋点不记录地址和凭证。缓存中媒体片段未单独加密,存放于应用私有缓存目录,可以清理或被系统回收。投屏 HTTP relay 使用随机 token,仍应使用受信任的家庭局域网。测试源脚本只绑定本机回环,用虚构账号,不适合生产部署。 + +## 构建与后续接入 + +```powershell +.\gradlew.bat :app:assembleDebug :app:lintDebug :app:testDebugUnitTest +python tools/verify_apk_native.py app/build/outputs/apk/debug/app-debug.apk +``` + +产物为 debug 签名测试包,发布商店前需配置自己的 release 签名和发行流程。界面使用原生 Views,手机为底部导航、宽屏为侧边导航,横屏播放全屏显示。来源契约、播放契约和 cast 契约允许继续添加服务与内核;当前 JVM 模块尚未迁移成 KMP。 diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..4d9cd78 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,59 @@ +# 接口与架构 + +0.3.0 在播放层之外增加来源、存储与投屏层。来源适配输出 LibraryPlayback,包含稳定身份、播放请求、字幕、观看会话与重新解析函数;LibraryPlaybackTracker 管理本地书签与进度。投屏期间观看会话交给对应 CastProgressObserver,返回本机重新解析来源。完整模块表见 README,业务契约见 [媒体来源](media-libraries.md) 和 [投屏](casting.md)。 + +## 依赖方向 + +```mermaid +flowchart TD + Demo[app-demo] --> Engine[player-media3] + Demo --> Render[player-render-android] + Demo --> Lifecycle[player-lifecycle] + Demo --> Telemetry[player-telemetry] + Engine --> Core[player-core] + Engine --> Sources[player-media3-source] + Sources --> Core + Sources --> Native[player-rtmp-native] + Engine --> AndroidApi[player-android-api] + Render --> AndroidApi + Core --> Api[player-api] + AndroidApi --> Api + Lifecycle --> Api + Telemetry --> Api +``` + +## 命令与状态 + +PlayerEngine 是业务边界,不暴露 ExoPlayer。命令为 suspend,Media3 实现切换 Dispatchers.Main.immediate,单次命令执行中不挂起;按主线程执行顺序串行处理,并发调用不保证调用方发起时的全局先后顺序。创建实例和 Surface 操作要求主线程。 + +协议工厂独立为 player-media3-source。PlaybackRequest 的 sourceType 支持 AUTO 和显式媒体类型,network 保存 HTTP 超时、RTSP 超时及传输模式。SourceRouting 在替换当前播放前校验 scheme 和类型,不支持的 SRT/RIST/WebRTC 等返回 Unsupported。协议选项随 request 保存,因此解码策略重建仍保留相同连接设置。参见 [在线协议接入](online-protocols.md)。 + +CommandResult.Accepted 只表示命令接受,网络、解封装、解码失败异步通过 state.error 和 Error 事件报告。InvalidArgument、Unsupported、Released、Failed 分开处理。release 幂等,不关闭 state/events 流;state 最终为 RELEASED,调用方仍应取消自己的订阅。 + +状态流保存当前快照,播放时位置按 1 秒采样并在播放器事件后刷新,暂停/空闲不轮询。READY 表示可以播放,不等于正在播放;isPlaying 表示实际推进,playWhenReady 表示用户播放意图,可因音频焦点抑制而不实际播放。PREPARING 表示首帧之前的缓冲,BUFFERING 表示首帧之后的缓冲;纯音频没有视频首帧,不能据此计算音频卡顿。 + +events 是无回放热流,缓冲 64 条,溢出丢最旧事件。用于 UI 提示和诊断,不用于可靠审计或计费。关键当前错误保存在 state。原始错误信息不透传,避免带 token 的地址泄漏;保留 Media3 errorCodeName 作为定位线索。 + +## 硬软解策略 + +AUTO 沿用系统排序,PREFER_HARDWARE 将硬解靠前,HARDWARE_ONLY 过滤到硬解,SOFTWARE_ONLY 过滤到系统软件解码器。音视频分别设置。支持设置策略不表示该设备对每种编码都有匹配解码器。实际 decoder 名称通过 DecoderChanged 上报,不能用请求策略推测实际运行结果。 + +切换策略会释放并重建 ExoPlayer,恢复当前进度、播放意图、速度、音量、轨道选择参数和仍有效的 Surface。重建可能重新缓冲,不承诺无缝切换;直播窗口移动时恢复位置可能被内核调整。轨道 id 仅对当前媒体有效。实际硬件分类在 API 29+ 查询平台 MediaCodecInfo,旧系统为 unknown。当前不做运行中错误自动软解、跨内核回退或清晰度降级;这些策略必须在获得真机数据后实现。 + +## 渲染与所有权 + +PlayerEngine 不依赖 Surface。AndroidVideoOutput 只绑定输出,不拥有外部传入的 Surface。 + +- SurfaceViewBinding 不释放系统 Surface,close 时移除 holder callback。 +- TextureViewBinding 独占 SurfaceTextureListener,释放自己构造的 Surface;SurfaceTexture 销毁返回 true,由 View 释放。 +- detach 携带 Surface 身份,旧 View 销毁不会清除新 View 输出。 +- Surface 销毁不自动释放播放器;生命周期策略独立控制暂停和销毁。 +- 默认 SurfaceView。TextureView 适用于确有变换需求的 UI,应实测功耗和帧率。 + +适配层不实现宽高比布局;示例通过 VideoSize 事件做居中等比缩放。业务需处理自己的布局、旋转和镜像需求。 + +## 生命周期与埋点 + +PlaybackLifecycleBinding 在 STOP 暂停,仅在它造成暂停时于 START 恢复;用户按钮通过 playByUser/pauseByUser,避免手动暂停被误恢复。后台应避免绕过绑定直接 autoplay prepare。后台播放服务不使用页面绑定。close 仅解绑,不释放;默认 ON_DESTROY 才释放。 + +PlaybackTelemetry 将事件和阶段变化交给 TelemetrySink。sink 必须快速返回、不可阻塞主线程,上传请排队到业务后台任务。异常隔离,close 停止采集。first_frame 为呈现首帧;startup 从最近一次 prepare/策略重建到呈现首帧,包含等待 Surface 和网络的时间,不是纯解码耗时。当前记录阶段变化,尚未计算卡顿率和卡顿持续时长。 diff --git a/docs/casting.md b/docs/casting.md new file mode 100644 index 0000000..2addd78 --- /dev/null +++ b/docs/casting.md @@ -0,0 +1,42 @@ +# DLNA 与 Google Cast(0.3.0) + +## 使用与区别 + +先在 Demo 加载视频,再选择「DLNA 投屏:搜索电视」或「Google Cast 投屏」。两者都是远端播放控制,不是屏幕镜像,也不包含接收端 App。 + +| 项目 | DLNA | Google Cast | +| --- | --- | --- | +| 接收设备 | 支持 UPnP MediaRenderer/AVTransport 的电视、盒子 | Cast-enabled 接收设备 | +| 发现/控制 | SSDP M-SEARCH、SOAP | Media3 MediaRouteButtonFactory/CastPlayer | +| 控制入口 | 播放、暂停、前后跳转、结束并返回本机 | 投屏验证页 PlayerView、设备路由按钮、媒体通知 | +| 生命周期 | 当前 Demo 页面拥有,销毁会停止和关闭 relay | MediaSessionService 拥有,可在后台继续 | +| 环境 | 同一可互访局域网,路由器未隔离客户端 | 同一可互访网络,Android 设备需可用的 Google Play 服务 | + +DLNA 的名称不代表所有电视均具备相同编码/字幕能力。接收端不能解码时,需要媒体服务器转码;手机 relay 只转发字节,不做视频转换。 + +## 地址可达性 + +`player-cast-api` 将请求分类为 DIRECT、RELAY、UNSUPPORTED: + +- 无自定义认证头的 HTTP(S) 文件/HLS/DASH 可以直接交给接收端,但仍要求接收端能访问服务器和解码媒体。 +- 带认证的普通 HTTP 文件、SMB、本地 file/content 来源通过手机 relay。接收端拿到的是本次会话专用的随机 token URL,账户密码和原始认证头留在手机。 +- Jellyfin 返回的授权地址可直接投屏,其中 ApiKey 是访问令牌,会作为媒体 URL 发给接收端,不应把它当作公开无凭证链接传播。 +- 带认证头的 HLS/DASH 暂不代理清单、密钥和分片;RTSP/RTMP/FLV/SmoothStreaming 不作为本轮远端格式承诺。需要服务器提供合适的 HTTP 版本。 + +手机 relay 仅公布 Wi-Fi/以太网 IPv4 地址,支持 GET、HEAD、单段 Range、后缀范围、206/416 与 CORS,不暴露目录,不接受任意上游 URL 参数。多 Range 明确拒绝。停止会话撤销 token 并关闭服务器;只保存当前注册的媒体请求。当前不代理外挂字幕到接收端,DLNA 也未实现各品牌私有字幕协议。 + +## 播放交接 + +本机暂停后,投屏会话接管书签与 Jellyfin 观看进度。DLNA 通过 GetPositionInfo/GetTransportInfo 查询状态;Google Cast 由服务内 CastPlayer 获取位置。返回本机时恢复位置与播放意图,并重新解析来源,必要时重新创建 Jellyfin 转码会话。 + +Google Cast 使用 Media3 1.11.1 的 CastPlayer、DefaultCastOptionsProvider 和 MediaSessionService;没有新建旧 RemoteMediaClient 包装层。服务持有独立本地 ExoPlayer,负责本机/远端之间转移。验证页在设备切换后重新绑定 PlayerView,结束时撤销路由、停止媒体服务并返回本机播放器。 + +DLNA 目前是前台验证实现,没有用于长时间后台保活的独立前台服务;锁屏、进程被回收或页面销毁可能中断手机代理。Google Cast 服务后台播放也不能跨越系统强制停止/应用进程终止。不可将 Demo 的资源清理逻辑等同于完整产品的跨进程恢复。 + +## 尚需设备验证 + +自动测试覆盖投屏决策、凭证来源的 relay 选择、Range 解析、HTTP 代理、设备描述解析、SOAP 参数转义和时轴控制。没有真实电视/Chromecast 时,不能标记设备发现、实际解码、系统路由、后台保活或回切为已验收。 + +建议用普通 MP4/H.264/AAC 样片先测试直连,再测试需要手机代理的 WebDAV/SMB 文件,最后测试 Jellyfin HLS 转码。检查拖动、暂停、断开 Wi-Fi、接收端退出以及返回本机时的进度与服务端会话释放。 + +上游参考:[Media3 CastPlayer](https://developer.android.com/media/media3/cast/create-castplayer)、[Media3 CastPlayer 源码](https://github.com/androidx/media/blob/1.11.1/libraries/cast/src/main/java/androidx/media3/cast/CastPlayer.java)。 diff --git a/docs/framework-selection.md b/docs/framework-selection.md new file mode 100644 index 0000000..26997c5 --- /dev/null +++ b/docs/framework-selection.md @@ -0,0 +1,39 @@ +# 框架选型 + +记录日期:2026-11-30。最低 Android API 23;首期 Android,未来可能扩展 Apple 或桌面平台。目标包含低端、32 位和旧版本设备。以下性能取舍是工程判断,尚需真机验证。 + +## 对比 + +| 内核 | 优点 | 代价 | 结论 | +| --- | --- | --- | --- | +| 原版 ijkplayer | FFmpeg 软解、MediaCodec 硬解、MediaPlayer 风格 API;Android/iOS | 上游说明仍使用旧 FFmpeg、JCenter 和旧 NDK;升级与设备维护成本较高 | 不作为空白项目的基础,设计参考 | +| FSPlayer(debugly/fsplayer) | ijk 衍生,更新 FFmpeg,Android/Apple,硬软解、复杂字幕和广格式 | 需验证发布产物 ABI、渲染要求和低端设备稳定性;不是 Windows/Linux 通用方案 | 广格式/FFmpeg 视频软解候选 | +| mpv/libmpv | 格式与字幕丰富,桌面多平台,属性与事件接口成熟 | JNI、构建、渲染上下文和平台集成工作多;Android 必须单独调优 | 桌面跨平台明确后优先验证 | +| Media3 ExoPlayer | Android 集成、HLS/DASH、状态与诊断接口完善,Apache 2.0 | Android 专用,视频编码依赖系统或特定扩展;不提供通用 FFmpeg 视频软解 | 首期默认内核 | + +当前 Media3 1.11.1;从 1.9.0 起 minSdk 23。FSPlayer 当前上游声明 API 21,Vulkan 优先、GLES 3 回退,必须区分系统版本和 GPU 能力。mpv-android 当前示例应用最低 API 23,这不等同于任意 libmpv 构建的绝对最低版本。 + +## 解码与格式边界 + +Media3 的官方 FFmpeg 扩展主要补音频,不是通用 H.264/HEVC 视频软解。项目当前不打包 FFmpeg、AV1、VP9 等可选软件扩展,SOFTWARE_ONLY 仅选择系统提供的软件 MediaCodec;无匹配解码器时异步上报播放错误。HARDWARE_ONLY 也不保证设备具备对应编码的硬解。 + +格式支持要按协议 → 容器 → 视频编码/profile → 音频编码 → 字幕验证。MKV 可解析不代表其中 HEVC 10-bit、DTS、PGS 都能播放。当前引入 progressive、HLS、DASH、RTSP、SmoothStreaming 和 RTMP 模块,支持显式 FLV 类型;SMB、蓝光、DRM、离线下载、复杂 ASS 特效没有实现或验证,不能作为支持承诺。具体协议与测试边界见 [在线协议接入](online-protocols.md)。 + +mpv 在 Android 的 mediacodec_embed 路径直接输出 Surface,但不具备完整字幕/OSD/滤镜能力;GPU 路径功能更全,需控制低端机渲染开销。跨平台需求不能直接推导为所有平台必须同一内核。 + +## 后续内核适配 + +实现 PlayerEngine 和独立 AndroidVideoOutput;暴露真实能力,统一错误、状态与轨道映射。验证 Surface 销毁/重建、线程和释放语义后才加入工厂。跨内核切换应由上层显式执行,保存媒体、位置、播放意图和轨道偏好;限制重试次数,不允许无限循环回退。直播还要定义恢复到直播边缘还是原窗口位置。 + +FFmpeg 系构建需保存版本、配置、第三方库和许可清单。mpv 默认整体为 GPL,可通过排除 GPL 文件等方式构建 LGPL 版本,不能拿 Android 外壳 MIT 许可替代内核许可。FSPlayer 的 LGPL 和第三方依赖也需按实际构建产物核对。 + +## 上游依据 + +- [Media3 发行页](https://developer.android.com/jetpack/androidx/releases/media3) +- [Media3 支持的格式](https://developer.android.com/media/media3/exoplayer/supported-formats) +- [Media3 发行记录](https://github.com/androidx/media/blob/release/RELEASENOTES.md) +- [ijkplayer](https://github.com/bilibili/ijkplayer) +- [FSPlayer](https://github.com/debugly/fsplayer) +- [mpv Android 构建](https://github.com/mpv-android/mpv-android/blob/master/app/build.gradle) +- [mpv 手册](https://mpv.io/manual/master/) +- [mpv 许可](https://github.com/mpv-player/mpv/blob/master/Copyright) diff --git a/docs/media-libraries.md b/docs/media-libraries.md new file mode 100644 index 0000000..8a291c5 --- /dev/null +++ b/docs/media-libraries.md @@ -0,0 +1,55 @@ +# WebDAV、SMB 与 Jellyfin(0.3.0) + +## 使用 + +1. 打开 Demo「来源管理:WebDAV / SMB / Jellyfin」。 +2. 添加来源并选择类型,填写名称、服务根地址与账户。长按已有来源可编辑或删除。 +3. WebDAV 地址示例 `https://nas.example/dav/`;SMB 地址示例 `smb://192.168.1.10/Movies/`,必须包含共享名,可追加起始目录;Jellyfin 填服务根地址,可带反向代理子路径。 +4. 浏览目录或媒体库,选择视频。同名 `movie.srt`、`movie.zh.srt`、`movie.ass` 等会列为外挂字幕候选;也可不使用外挂字幕。 +5. 播放页提供进度条、音轨/字幕选择。书签绑定来源、文件 ID 与版本,下次打开恢复进度,接近结尾时清零。 + +来源与播放内核分开,`MediaLibrary.list()` 负责浏览,`resolve()` 负责生成 `LibraryPlayback`;后者持有本机播放请求、稳定标识、字幕、服务会话与重新解析函数。短效地址不作为书签身份。共享来源契约目前为 JVM,Android 账户仓库、SMB 桥接及 JSON/XML 适配仍需为其他平台实现。 + +## WebDAV + +使用 PROPFIND Depth:1,解析命名空间与每个 propstat 状态。忽略当前目录和越出配置根目录的 href,同源验证避免向其他主机发送 Basic 凭证。地址需填写最终规范根地址,客户端不自动带认证跨域或跨协议重定向。 + +当前支持 Basic 认证与匿名来源;Digest、NTLM、OAuth、客户端证书与自签名证书管理尚未实现。HTTPS 默认使用系统信任,不跳过证书校验。服务器应支持普通 GET 与 Range 随机读取;不支持 Range 的来源可能从头读取或无法有效拖动。 + +目录枚举取得 ETag/修改时间/长度作为缓存版本,并在解析视频时重新枚举父目录刷新版本、匹配字幕。没有实现批量目录索引、全库搜索、上传或删除远端文件。 + +## SMB + +基于 SMBJ 0.13.0,支持 SMB2/SMB3,不包含 SMB1。用户名、密码和域单独保存,不放入 smb URI。列表读取与随机文件读取在 IO 线程进行;媒体 URI 内只保存账户 ID 和路径。 + +一个播放 DataSource 持有独立连接、认证会话、共享和文件句柄;连续读取复用句柄,seek 使用服务器字节偏移,不以 skip 从头读取。close 按文件→共享→会话→连接→客户端清理;连接与 socket 设有超时。尚未做多文件连接池或 DFS/企业域环境的实际验收。 + +`library-media3` 在宿主启动时注册 tt-source 传输插件,不在核心播放器中耦合 SMB。外部字幕按自己的 URI 打开独立读取句柄。 + +## 缓存与续播 + +普通文件使用 Media3 SimpleCache + LRU,默认目标上限 256 MB,位于应用私有 cacheDir。宿主在 IO 线程预热缓存,播放器创建数据源时不在主线程打开数据库。进程只持有一个目录锁;缓存可能被系统清理,不属于可靠离线下载。 + +缓存 key 包含来源 ID、文件 ID 和版本,避免临时地址变更造成重复缓存,或不同账户串用同一个 URL 的缓存。HLS/DASH/转码流不套用普通文件缓存 key;当前没有离线下载、下载队列或全片预下载。 + +书签持久化稳定 ID 的 SHA-256 和位置,不保存带凭证的地址。播放过程中节流保存,暂停、页面停止和会话结束时补充 checkpoint。新版本文件使用新 key;小于结尾 10 秒的进度视为完成。Demo 不通过 ViewModel 保活本地主播放器,旋转会释放并重建,需要重新打开视频,仍可从保存的书签恢复。 + +## Jellyfin + +- 用户名/密码调用 Users/AuthenticateByName,令牌仅留在当前适配器内存;账户配置由 Keystore 加密仓库保存。 +- 从用户 Views 浏览媒体库,Items 按 100 条分页,读取服务端观看位置。 +- PlaybackInfo 上报保守设备 Profile:H.264/AAC/MP4 直放,默认 1280×720、4 Mbps,其他组合由服务器决定是否提供 HLS 转码。 +- 选择服务器返回的首个 MediaSource,直放使用授权 HTTP 文件地址,否则使用 TranscodingUrl。不提供转码时明确失败,不在手机上假装转换。 +- 使用当前 ApiKey 查询参数和 MediaBrowser Authorization,兼容不接受 legacy api_key 的服务;媒体地址和外挂字幕必须保持与服务根地址同源。 +- 上报 Sessions/Playing、Progress、Stopped;停止转码时按 DeviceId/PlaySessionId 结束对应 ActiveEncodings。 +- 转码从指定位置开始时保存原媒体时间偏移,书签与服务端进度统一换算为绝对位置。拖动和投屏回切重新协商来源,避免复用已结束的转码会话。 + +能力声明目前是面向旧机的保守配置,不是完整动态设备能力探测。尚未实现 SSO/Quick Connect、海报墙、详情页、多版本手选、搜索、服务端字幕烧录策略 UI 或管理员功能。媒体库以分页列表浏览,服务器权限和转码能力按实际部署决定。 + +## 账户与数据 + +来源配置由 Android Keystore AES-GCM 加密,禁止明文回退;Demo 关闭备份。设备密钥丢失/失效时需要重新配置。媒体缓存本身是应用私有文件,没有额外内容加密。账户只用于读取与播放,当前没有修改远端文件的功能。 + +API/协议测试使用本地 MockWebServer。Keystore 账户保存和进程重启恢复已在 Pixel_8 模拟器验证;真实 SMB 共享、实体设备密钥持久化、Jellyfin 部署的鉴权和硬件转码仍需真机验收。 + +上游参考:[Media3 自定义数据源](https://developer.android.com/media/media3/exoplayer/customization)、[SMBJ](https://github.com/hierynomus/smbj)、[Jellyfin 转码](https://jellyfin.org/docs/general/post-install/transcoding/)、[Jellyfin API 实现注意事项](https://github.com/jellyfin/jellyfin-mpv-shim/blob/master/docs/jellyfin-api-notes.md)。 diff --git a/docs/online-protocols.md b/docs/online-protocols.md new file mode 100644 index 0000000..3dcda77 --- /dev/null +++ b/docs/online-protocols.md @@ -0,0 +1,69 @@ +# 在线协议接入(0.2.0) + +## 范围 + +| 类型 | API sourceType | 说明 | +| --- | --- | --- | +| HTTP(S) 文件流 | PROGRESSIVE / AUTO | MP4、WebM、MKV 等,实际编码取决于设备 | +| HLS | HLS / AUTO | .m3u8,点播、直播、自适应码率 | +| DASH | DASH / AUTO | .mpd,点播、直播、自适应码率 | +| SmoothStreaming | SMOOTH_STREAMING / AUTO | .ism/Manifest、.isml/Manifest,FMP4 | +| HTTP(S)-FLV | FLV / AUTO | .flv,无扩展名时显式指定 FLV;传统 FLV,非 Enhanced RTMP/HEVC 承诺 | +| RTMP | RTMP / AUTO | rtmp://,官方 datasource-rtmp + FLV extractor;不包含推流 | +| RTSP | RTSP / AUTO | rtsp://,UDP 单播或 RTP/TCP;可强制 TCP | + +AUTO 按 scheme/path 推断,忽略查询参数。网关 URL `https://host/play?id=1` 必须指定真实 sourceType,不能期望仅凭 HTTP Content-Type 自动选择 HLS/DASH。HTTP 请求头用于主清单、分片、密钥和通过同工厂加载的外挂字幕。RTSP/RTMP 的 headers 和外挂字幕配置会明确拒绝,避免静默忽略。RTSP BASIC/DIGEST 认证使用 `rtsp://user:password@host/path`,不要记录完整地址。 + +## 调用示例 + +```kotlin +engine.prepare(PlaybackRequest( + uri = "https://host/play?id=1", + sourceType = MediaSourceType.HLS, + headers = mapOf("Authorization" to "Bearer TOKEN", "Referer" to "https://host/"), + network = NetworkOptions(connectTimeoutMs = 8_000, readTimeoutMs = 15_000), + autoplay = true, +)) + +engine.prepare(PlaybackRequest( + uri = "rtsp://host/live", + network = NetworkOptions(rtspTransport = RtspTransport.TCP, rtspTimeoutMs = 10_000), + autoplay = true, +)) +``` + +超时单位为毫秒,允许 1–120000。HTTP 连接/读取超时不作用于 RTSP/RTMP。RTSP rtspTimeoutMs 是缺少 RTP 数据的超时,并非完整连接超时。RTMP 超时由底层 native 库管理,本接口尚不能调整。RTSP AUTO 是先 UDP、无数据后由内核回退 TCP,不提供 UDP_ONLY。 + +请求头每次 prepare 独立构造,不跨媒体残留。HTTP 自适应来源可能包含其他域名的分片/密钥;调用方必须确认这些域名受信任,因为同一请求的 headers 会应用于它们。没有启用跨协议 HTTP 重定向。Demo 中地址和 header 编辑器不保存实例状态,框架事件不携带 URL/headers。 + +## Demo + +点击「连接设置」选择类型、填写每行 `Name: value` 的 HTTP 请求头,以及 RTSP TCP 选项,保存后点击「加载并播放」。切换到 RTMP/RTSP 前清空 HTTP 请求头。仅 Demo Manifest 开放任意明文 HTTP,业务宿主应根据自己的来源范围配置网络策略。连接设置不写偏好文件,旋转或退出后不保留凭证。 + +## 已知边界 + +- 接入模块不等于已验证全部服务器与编码;公网实流和低端机性能仍需验收。 +- HTTP-FLV 未实现断线重连、追帧或端到端低延迟控制;服务器断开后可能结束或报错,不会无限自动重试。 +- RTMP 使用官方 datasource-rtmp 扩展,但排除预编译 `io.antmedia:rtmp-client:3.2.0`(检查发现其 ELF LOAD 为 4 KB 对齐)。替换为 player-rtmp-native 中固定提交的源码构建,配置四 ABI 和 16 KB 对齐。提交、源码哈希、许可和本地修改均在 module 中保留;构建检查不代替 native 真机握手验证。 +- 当前不接 rtmps://、RTSP 组播、裸 UDP/RTP、SRT、RIST、WebRTC/WHIP/WHEP;输入将返回 Unsupported。 +- WebRTC 需要明确 WHEP 或自有信令、认证与会话生命周期;SRT/RIST 需要额外 native 传输适配,不能只通过添加一个 URL scheme 完成。 +- 没有接入 DRM 许可证获取、推流、服务端转码和跨内核回退。 + +## 自动验证 + +core 覆盖带查询参数/大小写路径、无扩展名显式类型、协议不匹配、不支持协议、header 冒号与重复字段、超时边界。source module 使用 Robolectric 验证实际 MediaSource 类型,并使用本地 MockWebServer 验证请求头发送/跨请求隔离、无 Content-Length 的 chunked HTTP-FLV 数据读取与容器识别。测试不表示完整 live 解码或 RTMP native 握手已通过。 + +测试样片 `player-media3-source/src/test/resources/sample.flv` 为自主生成的 32×32 黑色视频+静音,H.264 baseline/AAC,0.4 秒。生成命令: + +```text +ffmpeg -f lavfi -i color=c=black:s=32x32:r=5 -f lavfi -i anullsrc=r=44100:cl=mono -t 0.4 -c:v libx264 -pix_fmt yuv420p -profile:v baseline -c:a aac -f flv sample.flv +``` + +本次结果:17 项测试通过,Lint 0 errors / 8 warnings。四 ABI APK 已通过签名、ELF 16 KB 与 ZIP 对齐检查。native 对应源码归档见 `dist/TTVideoPlayer-rtmp-source-0.2.0.zip`;分发 APK 时请一并保留可用的对应源码和许可。完整检查记录见 [验证文档](validation.md)。 + +## 上游依据 + +- [SmoothStreaming](https://developer.android.com/media/media3/exoplayer/smoothstreaming) +- [RTSP](https://developer.android.com/media/media3/exoplayer/rtsp) +- [官方 RTMP 数据源](https://github.com/androidx/media/blob/1.11.1/libraries/datasource_rtmp/src/main/java/androidx/media3/datasource/rtmp/RtmpDataSource.java) +- [FLV 提取器](https://github.com/androidx/media/blob/1.11.1/libraries/extractor/src/main/java/androidx/media3/extractor/flv/FlvExtractor.java) diff --git a/docs/validation.md b/docs/validation.md new file mode 100644 index 0000000..9e2a61e --- /dev/null +++ b/docs/validation.md @@ -0,0 +1,83 @@ +# 验证与设备矩阵 + +## 0.3.0 来源与投屏检查结果(2026-11-30) + +- 完整 Demo 构建与 27 项测试通过,无失败、无跳过。 +- 新增覆盖:字幕匹配、WebDAV 认证/目录/越界 href/重定向、Jellyfin 登录/协商/进度/转码结束、书签、投屏决策、DLNA 描述和 SOAP、Range 代理、断网后读取已缓存范围。 +- Debug Lint:0 errors、12 warnings,主要为 target SDK、依赖升级提示、备份/图标、示例文本国际化与 KTX 建议;未关闭检查。 +- Pixel_8 模拟器已安装启动,来源管理和添加表单正常;使用虚构账户验证 Android Keystore 加密保存、配置文件无明文测试密码/地址、进程重启后解密恢复。测试账户已删除,本次启动的无窗口模拟器已关闭。没有操作实体手机。 +- APK 中四 ABI 的 RTMP 和 AndroidX graphics native 库均通过 16 KB ELF/ZIP 对齐检查。 +- 仍需真实环境验收:SMB2/3 服务器读/seek/重连、Jellyfin 实际硬件转码与部署差异、DLNA SSDP 发现与接收端解码、Google Cast 路由/后台/回切。模拟器页面检查不代替这些验证。 +- 新能力和边界见 [媒体来源文档](media-libraries.md) 与 [投屏文档](casting.md)。 + +复现自动检查: + +```powershell +.\gradlew.bat :app-demo:assembleDebug :player-core:test :player-media3:testDebugUnitTest :player-lifecycle:testDebugUnitTest :player-media3-source:testDebugUnitTest :library-api:test :library-webdav:testDebugUnitTest :library-jellyfin:testDebugUnitTest :library-storage:testDebugUnitTest :player-cast-api:test :player-cast-dlna:testDebugUnitTest :player-cast-relay:testDebugUnitTest :app-demo:lintDebug +``` + +## 1.0.0 完整 App 检查结果(2026-11-30) + +- `:app:assembleDebug`、`:app:lintDebug`、`:app:testDebugUnitTest` 通过;Lint 为 0 errors、19 warnings。并回归执行了 core、Media3、生命周期、WebDAV、SMB、Jellyfin、Cast API/relay/DLNA 测试。 +- 新增应用记录 JSON 的 round-trip 测试,覆盖签名链接、请求头、网络参数、字幕默认项、稳定来源身份和日志脱敏;新增自适应 HLS 不携带普通文件 cache key 的回归测试。 +- 使用 Pixel_8 模拟器和本机回环 WebDAV fixture(虚构账号 `demo`)完成:Basic 认证、目录列举、MP4 Range/读取、同名 SRT 自动加载、480×270 H.264 硬件解码、首帧、字幕显示、横屏不丢失播放进度、强制结束进程后的加密续播恢复。测试来源与模拟器在交付前关闭;没有操作实体手机。 +- 首次实机 UI 启动发现 API 35 在 `setContentView` 前构造系统栏控制器会因 DecorView 未创建而崩溃,已改为根视图 attach 后初始化并复验首页可启动。 +- 真实 SMB/NAS、Jellyfin 转码、DLNA 电视和 Google Cast 接收端仍需现场设备验收,模拟器不代替该矩阵。 + +## 0.2.0 协议扩展检查结果(2026-11-30) + +- APK 构建成功:`dist/TTVideoPlayer-demo-0.2.0-debug.apk`,最低 API 23。 +- 17 项测试通过,无跳过:公共校验 3、协议路由/header 5、Media3 3、生命周期 2、协议工厂/本地 HTTP 4。 +- Debug Lint:0 errors、8 warnings(示例 target SDK、依赖升级提示、备份/图标、文本国际化)。未屏蔽检查。 +- RTMP 源码重建四 ABI 成功。APK 实际 ELF LOAD 均为 16384,未压缩 native entry 的 ZIP 数据偏移也通过 16 KB 检查;APK 签名验证通过。 +- native 编译仍有上游指针类型、浮点字节序默认假设警告,以及本机 SDK 元数据版本提示;不作为 native 安全审计或真机验证通过的依据。 +- RTMP 对应源码与重建脚本:`dist/TTVideoPlayer-rtmp-source-0.2.0.zip`。原预编译 RTMP 库已从依赖中排除。 +- HTTP-FLV 使用本地 chunked 流验证读取和容器识别;RTMP/RTSP/公网直播的握手、解码、重连与功耗尚未真机验收。 + +## 0.1.0 初始检查结果(2026-11-30) + +- JDK 17 / Gradle 8.13 构建成功,生成 `app-demo/build/outputs/apk/debug/app-demo-debug.apk`。 +- core 3 项、Media3 适配器 3 项、生命周期 2 项测试全部通过,无跳过。 +- Debug Lint:0 errors、6 warnings。警告为示例 targetSdk 36 未跟随最新 API、activity/core 可升级、备份规则、缺少示例图标、状态文本国际化。未配置 lint baseline 或关闭这些检查。 +- 官方 Maven Central 下载一项 Kotlin 依赖时 TLS 握手失败,使用 README 中的可选镜像完成检查。 +- ADB 无在线设备;尚未执行真机播放、画面、性能或功耗测试。 + +## 自动检查 + +```powershell +.\gradlew.bat :player-core:test :app-demo:assembleDebug :app-demo:lintDebug +.\gradlew.bat :player-media3:testDebugUnitTest :player-lifecycle:testDebugUnitTest +.\gradlew.bat :player-media3-source:testDebugUnitTest +python tools/verify_apk_native.py dist/TTVideoPlayer-demo-0.2.0-debug.apk +``` + +core 测试覆盖非法 URI、负起播位置、请求头换行注入、非法字幕、content/file/HTTPS URI 以及不支持的解码策略。编译和 Lint 只能检查静态集成,不能证明设备解码性能。 + +Media3 适配器与生命周期使用 Robolectric API 28 测试,覆盖非法输入不启动播放、解码策略重建后的意图、幂等释放、释放后命令拒绝、前后台恢复、手动暂停阻止恢复,以及外部所有者释放策略。不加载媒体,不替代真机解码测试。 + +## 真机验收(待执行) + +至少包含 API 23 的 32 位低端机、旧 64 位低端机和当前系统设备。记录芯片、RAM、系统、ABI、GPU、实际 decoder,不能仅用模拟器验收低端表现。 + +| 场景 | 验证重点 | +| --- | --- | +| H.264 + AAC,MP4,360p/720p/1080p | 首帧、掉帧、内存、CPU 和发热 | +| HLS/DASH 多码率、断网恢复、RTSP | 缓冲、错误、seek 能力、直播位置 | +| HEVC 8/10-bit、VP9、AV1 | 设备能力、不支持错误、软解成本 | +| MKV 多音轨、SRT/WebVTT | 轨道切换、字幕选择、时轴 | +| AUTO/强制硬解/强制软解 | 实际 decoder、无匹配解码器错误 | +| SurfaceView/TextureView 切换 | 有声音无画面、Surface 泄漏、宽高比 | +| 旋转、快速前后台、返回退出 | 恢复意图、释放、无残留音频 | +| 手动暂停后前后台切换 | 不自动恢复 | +| 播放中切换解码策略 | 位置、音量、速度、轨道和画面恢复 | +| 长时间播放、反复创建销毁 | 内存、线程、句柄和温度 | + +## 当前明确边界 + +- API 23 起;没有 Android 5 或更低版本的兼容分支。 +- 不包含 FFmpeg native so,未实现 FSPlayer/libmpv;系统自带 codec 是否支持 32 位设备由设备决定。 +- 本地主播放器尚未实现后台媒体服务;Google Cast 已有独立 MediaSessionService。未实现 DRM 配置、离线下载、播放列表或通用自动重试。 +- 示例是验证宿主,不是完整播放器 UI;旋转会重建播放,不做 ViewModel 保活。 +- 不承诺所有格式、所有设备流畅播放;高分辨率新编码应提供服务器转码或多清晰度来源。 +- 首帧、掉帧、解码器事件已实现;CPU/内存/温度与卡顿持续时间尚未采集。 +- Gradle/SDK 实际检查结果由本次交付说明记录;真机矩阵不能标记为已通过,除非执行对应设备测试。 diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..5bf8190 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx4096m -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8 +android.useAndroidX=true +android.enableJetifier=true +kotlin.code.style=official +android.suppressUnsupportedCompileSdk=37.0 +kotlin.suppressGradlePluginWarnings=DeprecatedGradleVersionWarning diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f6b961f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c09bdf5 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Oct 11 20:25:09 CST 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/library-api/build.gradle.kts b/library-api/build.gradle.kts new file mode 100644 index 0000000..030ed3e --- /dev/null +++ b/library-api/build.gradle.kts @@ -0,0 +1,6 @@ +plugins { kotlin("jvm"); `java-library` } +kotlin { jvmToolchain(17) } +dependencies { +api(project(":player-api")) +testImplementation("junit:junit:4.13.2") +} diff --git a/library-api/src/main/kotlin/com/ttstd/player/library/MediaLibrary.kt b/library-api/src/main/kotlin/com/ttstd/player/library/MediaLibrary.kt new file mode 100644 index 0000000..4c4510e --- /dev/null +++ b/library-api/src/main/kotlin/com/ttstd/player/library/MediaLibrary.kt @@ -0,0 +1,77 @@ +package com.ttstd.player.library + +import com.ttstd.player.api.* + +enum class LibraryKind { WEBDAV, SMB, JELLYFIN } + +/** 账户配置只存储于宿主私有加密仓库;禁止把该对象输出至日志。 */ +class LibraryAccount( + val id: String, + val name: String, + val kind: LibraryKind, + val endpoint: String, + val username: String = "", + val password: String = "", + val domain: String = "", +) { + override fun toString() = "LibraryAccount(id=$id, kind=$kind, credentials=REDACTED)" +} + +data class LibraryEntry( + val id: String, + val name: String, + val isFolder: Boolean, + val size: Long? = null, + val version: String = "", + val resumeMs: Long = 0, +) +data class LibraryPage(val entries: List, val nextOffset: Int? = null) + +/** 来源适配负责授权、浏览和播放协商,不引用播放器内核。 */ +interface MediaLibrary { + val account: LibraryAccount + suspend fun list(folderId: String = "", offset: Int = 0): LibraryPage + suspend fun resolve(entry: LibraryEntry, options: LibraryPlaybackOptions = LibraryPlaybackOptions()): LibraryPlayback +} +data class LibraryPlaybackOptions(val startPositionMs: Long = 0, val maxBitrate: Int = 4_000_000, val maxWidth: Int = 1280, val maxHeight: Int = 720) + +/** 观看进度上报与解码独立;服务端出错不得阻塞本地播放。 */ +interface LibraryPlaybackSession { + suspend fun started(positionMs: Long) + suspend fun progress(positionMs: Long, paused: Boolean) + suspend fun stopped(positionMs: Long) +} +data class LibraryPlayback( + val request: PlaybackRequest, + val stableId: String, + val title: String, + val contentLength: Long? = null, + val session: LibraryPlaybackSession? = null, + val subtitles: List = request.subtitles, + /** 服务端已提供无需自定义请求头的接收端 URL 时,可直接投屏。 */ + val receiverRequest: PlaybackRequest? = null, + /** 从指定位置启动的服务端转码流,其本地时轴可能从零开始。 */ + val positionOffsetMs: Long = 0, + /** 重新取得临时地址或重新协商转码;位置为原媒体的绝对毫秒。 */ + val refresh: (suspend (Long) -> LibraryPlayback)? = null, + val originalDurationMs: Long? = null, +) + +class LibraryException(message: String) : Exception(message) + +object LibraryFiles { + private val videos = setOf("mp4", "mkv", "webm", "mov", "m4v", "avi", "ts", "m2ts", "flv", "wmv", "mpg", "mpeg") + fun isVideo(name: String) = name.substringAfterLast('.', "").lowercase() in videos + fun subtitleMime(name: String): String? = when (name.substringAfterLast('.', "").lowercase()) { + "srt" -> "application/x-subrip" + "vtt" -> "text/vtt" + "ass", "ssa" -> "text/x-ssa" + else -> null + } + /** 包含 movie.srt、movie.zh.srt,不把 movie2.srt 错配给 movie.mp4。 */ + fun matchesSubtitle(video: String, subtitle: String): Boolean { + val base = video.substringBeforeLast('.', video) + val stem = subtitle.substringBeforeLast('.', subtitle) + return subtitleMime(subtitle) != null && (stem.equals(base, true) || stem.startsWith("$base.", true)) + } +} diff --git a/library-api/src/test/kotlin/com/ttstd/player/library/LibraryFilesTest.kt b/library-api/src/test/kotlin/com/ttstd/player/library/LibraryFilesTest.kt new file mode 100644 index 0000000..1c3c58a --- /dev/null +++ b/library-api/src/test/kotlin/com/ttstd/player/library/LibraryFilesTest.kt @@ -0,0 +1,13 @@ +package com.ttstd.player.library +import org.junit.Assert.* +import org.junit.Test + +class LibraryFilesTest { + @Test fun subtitleMatchingDoesNotCrossMovieNames() { + assertTrue(LibraryFiles.matchesSubtitle("Movie.MKV", "movie.zh.srt")) + assertTrue(LibraryFiles.matchesSubtitle("电影.mp4", "电影.ass")) + assertFalse(LibraryFiles.matchesSubtitle("movie.mp4", "movie2.srt")) + assertFalse(LibraryFiles.matchesSubtitle("movie.mp4", "movie.mp4")) + assertTrue(LibraryFiles.isVideo("A.M2TS")) + } +} diff --git a/library-http/build.gradle.kts b/library-http/build.gradle.kts new file mode 100644 index 0000000..2b9a1ee --- /dev/null +++ b/library-http/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { id("com.android.library"); kotlin("android") } +android { + namespace = "com.ttstd.player.libraryhttp" + compileSdk = 37 + defaultConfig { minSdk = 23 } + testOptions { unitTests.isIncludeAndroidResources = true } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } +} +kotlin { jvmToolchain(17) } +dependencies { +api(project(":library-api")) +api("com.squareup.okhttp3:okhttp:4.12.0") +implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +testImplementation("org.robolectric:robolectric:4.14.1") +testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") +testImplementation("junit:junit:4.13.2") +} diff --git a/library-http/src/main/AndroidManifest.xml b/library-http/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/library-http/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/library-http/src/main/kotlin/com/ttstd/player/library/http/LibraryHttp.kt b/library-http/src/main/kotlin/com/ttstd/player/library/http/LibraryHttp.kt new file mode 100644 index 0000000..0479ccb --- /dev/null +++ b/library-http/src/main/kotlin/com/ttstd/player/library/http/LibraryHttp.kt @@ -0,0 +1,68 @@ +package com.ttstd.player.library.http + +import com.ttstd.player.library.LibraryException +import kotlinx.coroutines.suspendCancellableCoroutine +import okhttp3.* +import java.io.IOException +import java.io.ByteArrayInputStream +import javax.xml.parsers.DocumentBuilderFactory +import org.w3c.dom.Element +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException + +/** 不自动跨域重定向,避免认证头传到其他域名;不安装任何日志拦截器。 */ +object LibraryHttp { + val client: OkHttpClient = OkHttpClient.Builder().followRedirects(false).followSslRedirects(false) + .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(20, java.util.concurrent.TimeUnit.SECONDS) + .callTimeout(30, java.util.concurrent.TimeUnit.SECONDS).build() + + suspend fun execute(request: Request): Response = suspendCancellableCoroutine { continuation -> + val call = client.newCall(request) + continuation.invokeOnCancellation { call.cancel() } + call.enqueue(object : Callback { + override fun onFailure(call: Call, e: IOException) { + if (!continuation.isCancelled) continuation.resumeWithException(LibraryException("网络连接失败")) + } + override fun onResponse(call: Call, response: Response) { + if (continuation.isCancelled) response.close() else continuation.resume(response) + } + }) + } + + fun checkedBody(response: Response, maxBytes: Long = 4 * 1024 * 1024): String { + if (!response.isSuccessful) throw LibraryException("服务返回 HTTP ${response.code}") + val body = response.body ?: throw LibraryException("服务未返回内容") + if (body.contentLength() > maxBytes) throw LibraryException("服务响应过大") + val input = body.byteStream() + val output = java.io.ByteArrayOutputStream() + val buffer = ByteArray(8192) + while (true) { + val read = input.read(buffer) + if (read < 0) break + if (output.size().toLong() + read > maxBytes) throw LibraryException("服务响应过大") + output.write(buffer, 0, read) + } + return output.toString("UTF-8") + } +} + +/** WebDAV 与 UPnP 共享的命名空间感知 XML 解析。拒绝 DTD,禁用外部实体。 */ +object SafeXml { + fun parse(text: String): Element { + require(!text.contains(" { + val nodes = parent.getElementsByTagNameNS("*", name) + return (0 until nodes.length).map { nodes.item(it) as Element } + } + fun text(parent: Element, name: String): String = elements(parent, name).firstOrNull()?.textContent.orEmpty() + fun escape(text: String) = text.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """).replace("'", "'") +} diff --git a/library-jellyfin/build.gradle.kts b/library-jellyfin/build.gradle.kts new file mode 100644 index 0000000..b038a59 --- /dev/null +++ b/library-jellyfin/build.gradle.kts @@ -0,0 +1,16 @@ +plugins { id("com.android.library"); kotlin("android") } +android { + namespace = "com.ttstd.player.libraryjellyfin" + compileSdk = 37 + defaultConfig { minSdk = 23 } + testOptions { unitTests.isIncludeAndroidResources = true } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } +} +kotlin { jvmToolchain(17) } +dependencies { +api(project(":library-http")) +implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +testImplementation("org.robolectric:robolectric:4.14.1") +testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") +testImplementation("junit:junit:4.13.2") +} diff --git a/library-jellyfin/src/main/AndroidManifest.xml b/library-jellyfin/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/library-jellyfin/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/library-jellyfin/src/main/kotlin/com/ttstd/player/library/jellyfin/JellyfinLibrary.kt b/library-jellyfin/src/main/kotlin/com/ttstd/player/library/jellyfin/JellyfinLibrary.kt new file mode 100644 index 0000000..3d39aaf --- /dev/null +++ b/library-jellyfin/src/main/kotlin/com/ttstd/player/library/jellyfin/JellyfinLibrary.kt @@ -0,0 +1,147 @@ +package com.ttstd.player.library.jellyfin + +import com.ttstd.player.api.* +import com.ttstd.player.library.* +import com.ttstd.player.library.http.LibraryHttp +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONArray +import org.json.JSONObject + +/** Jellyfin 用户认证、媒体库与播放协商。客户端保守声明 H.264/AAC、720p/4Mbps, + * 服务端不兼容的来源请求转码;不把“服务器能转码”视为已完成转码的保证。 + */ +class JellyfinLibrary(override val account: LibraryAccount) : MediaLibrary { + private val root = (account.endpoint.trimEnd('/') + "/").toHttpUrl() + private val loginMutex = Mutex() + private var token = "" + private var userId = "" + private val deviceId = "tt-${account.id}" + private fun endpoint(vararg paths: String): HttpUrl = root.newBuilder().apply { paths.forEach { addPathSegment(it) } }.build() + private fun authorization(withToken: Boolean = true): String = + "MediaBrowser Client=\"TTVideoPlayer\", Device=\"Android\", DeviceId=\"$deviceId\", Version=\"0.3.0\"" + + if (withToken && token.isNotEmpty()) ", Token=\"$token\"" else "" + + private suspend fun login() = loginMutex.withLock { + if (token.isNotEmpty()) return@withLock + val body = JSONObject().put("Username", account.username).put("Pw", account.password) + val request = Request.Builder().url(endpoint("Users", "AuthenticateByName")) + .header("Authorization", authorization(false)).post(jsonBody(body)).build() + val result = LibraryHttp.execute(request).use { JSONObject(LibraryHttp.checkedBody(it)) } + token = result.getString("AccessToken") + userId = result.getJSONObject("User").getString("Id") + } + private suspend fun json(url: HttpUrl, body: JSONObject? = null): JSONObject { + login() + val request = Request.Builder().url(url).header("Authorization", authorization()) + .apply { if (body != null) post(jsonBody(body)) }.build() + return LibraryHttp.execute(request).use { response -> + if (response.code == 401) { token = ""; throw LibraryException("Jellyfin 登录已失效,请重新打开来源") } + JSONObject(LibraryHttp.checkedBody(response)) + } + } + override suspend fun list(folderId: String, offset: Int): LibraryPage = withContext(Dispatchers.IO) { + login() + val url = if (folderId.isEmpty()) endpoint("Users", userId, "Views") else endpoint("Users", userId, "Items") + .newBuilder().addQueryParameter("ParentId", folderId).addQueryParameter("StartIndex", "$offset") + .addQueryParameter("Limit", "100").addQueryParameter("Fields", "MediaSources,MediaStreams,DateModified") + .addQueryParameter("SortBy", "SortName").addQueryParameter("SortOrder", "Ascending").build() + val result = json(url) + val items = result.optJSONArray("Items") ?: JSONArray() + val entries = (0 until items.length()).mapNotNull { index -> + val item = items.getJSONObject(index) + val folder = item.optBoolean("IsFolder") + if (!folder && item.optString("MediaType") != "Video") return@mapNotNull null + LibraryEntry(item.getString("Id"), item.optString("Name", "未命名"), folder, + resumeMs = (item.optJSONObject("UserData")?.optLong("PlaybackPositionTicks") ?: 0) / 10_000) + } + val next = offset + items.length() + LibraryPage(entries, next.takeIf { folderId.isNotEmpty() && it < result.optInt("TotalRecordCount") }) + } + + override suspend fun resolve(entry: LibraryEntry, options: LibraryPlaybackOptions): LibraryPlayback = withContext(Dispatchers.IO) { + login() + val url = endpoint("Items", entry.id, "PlaybackInfo").newBuilder() + .addQueryParameter("UserId", userId).addQueryParameter("StartTimeTicks", "${options.startPositionMs * 10_000}") + .addQueryParameter("IsPlayback", "true").addQueryParameter("AutoOpenLiveStream", "true") + .addQueryParameter("MaxStreamingBitrate", "${options.maxBitrate}").build() + val info = json(url, JSONObject().put("DeviceProfile", deviceProfile(options))) + val source = info.optJSONArray("MediaSources")?.optJSONObject(0) ?: throw LibraryException("服务器未提供可播放的媒体版本") + val sourceId = source.getString("Id") + val sessionId = info.optString("PlaySessionId") + val direct = source.optBoolean("SupportsDirectPlay") + val transcode = source.optString("TranscodingUrl").takeUnless { it.isBlank() || it == "null" } + val playbackUrl = if (direct) endpoint("Videos", entry.id, "stream").newBuilder() + .addQueryParameter("Static", "true").addQueryParameter("MediaSourceId", sourceId).build() + else if (transcode != null) trustedUrl(transcode) else throw LibraryException("设备无法直放,服务器也未提供转码地址") + // 使用当前 ApiKey 名称,兼容关闭 legacy api_key 的 Jellyfin 服务。 + val authorizedUrl = withKey(playbackUrl) + val streams = source.optJSONArray("MediaStreams") ?: JSONArray() + val subtitles = (0 until streams.length()).mapNotNull { index -> + val stream = streams.getJSONObject(index) + if (stream.optString("Type") != "Subtitle" || !stream.optBoolean("IsExternal")) return@mapNotNull null + val delivery = stream.optString("DeliveryUrl").takeUnless { it.isBlank() || it == "null" } ?: return@mapNotNull null + val mime = when (stream.optString("Codec").lowercase()) { "srt", "subrip" -> "application/x-subrip"; "webvtt", "vtt" -> "text/vtt"; "ass", "ssa" -> "text/x-ssa"; else -> return@mapNotNull null } + ExternalSubtitle(withKey(trustedUrl(delivery)).toString(), mime, stream.optString("Language").ifBlank { null }) + } + val key = "${account.id}:${entry.id}:$sourceId" + val request = PlaybackRequest(authorizedUrl.toString(), startPositionMs = if (direct) options.startPositionMs else 0, + autoplay = true, subtitles = subtitles, sourceType = if (direct) MediaSourceType.PROGRESSIVE else MediaSourceType.HLS, + cacheKey = key.takeIf { direct }) + val report = object : LibraryPlaybackSession { + private fun body(positionMs: Long) = JSONObject().put("ItemId", entry.id).put("MediaSourceId", sourceId) + .put("PlaySessionId", sessionId).put("PositionTicks", (positionMs + if (direct) 0 else options.startPositionMs) * 10_000) + .put("CanSeek", true).put("PlayMethod", if (direct) "DirectPlay" else "Transcode") + override suspend fun started(positionMs: Long) { report("", body(positionMs)) } + override suspend fun progress(positionMs: Long, paused: Boolean) { report("Progress", body(positionMs).put("IsPaused", paused)) } + override suspend fun stopped(positionMs: Long) { + report("Stopped", body(positionMs)) + if (!direct && sessionId.isNotEmpty()) { + val stop = endpoint("Videos", "ActiveEncodings").newBuilder().addQueryParameter("DeviceId", deviceId) + .addQueryParameter("PlaySessionId", sessionId).build() + LibraryHttp.execute(Request.Builder().url(stop).header("Authorization", authorization()).delete().build()).use { } + } + } + } + LibraryPlayback(request, key, entry.name, source.optLong("Size").takeIf { it > 0 && direct }, report, + subtitles, receiverRequest = request, positionOffsetMs = if (direct) 0 else options.startPositionMs, + refresh = { position -> resolve(entry, options.copy(startPositionMs = position)) }, + originalDurationMs = source.optLong("RunTimeTicks").takeIf { it > 0 }?.div(10_000)) + } + private suspend fun report(event: String, data: JSONObject) { + val url = if (event.isEmpty()) endpoint("Sessions", "Playing") else endpoint("Sessions", "Playing", event) + LibraryHttp.execute(Request.Builder().url(url).header("Authorization", authorization()).post(jsonBody(data)).build()).use { + if (!it.isSuccessful) throw LibraryException("观看进度同步失败 HTTP ${it.code}") + } + } + private fun trustedUrl(path: String): HttpUrl { + val result = root.resolve(path) ?: throw LibraryException("服务器返回无效媒体地址") + require(result.host == root.host && result.port == root.port && result.scheme == root.scheme) { "服务器媒体地址跨域" } + return result + } + private fun withKey(url: HttpUrl) = url.newBuilder().setQueryParameter("ApiKey", token).build() + private fun jsonBody(body: JSONObject) = body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()) + + companion object { + /** 保守能力声明,避免低端机广告式宣称 4K/HEVC 软解能力。 */ + fun deviceProfile(options: LibraryPlaybackOptions): JSONObject { + val conditions = JSONArray().put(JSONObject().put("Condition", "LessThanEqual").put("Property", "Width").put("Value", "${options.maxWidth}").put("IsRequired", true)) + .put(JSONObject().put("Condition", "LessThanEqual").put("Property", "Height").put("Value", "${options.maxHeight}").put("IsRequired", true)) + .put(JSONObject().put("Condition", "LessThanEqual").put("Property", "VideoBitDepth").put("Value", "8").put("IsRequired", false)) + return JSONObject().put("Name", "TTVideoPlayer Android compatible").put("MaxStreamingBitrate", options.maxBitrate) + .put("MaxStaticBitrate", options.maxBitrate) + .put("DirectPlayProfiles", JSONArray().put(JSONObject().put("Container", "mp4,m4v").put("Type", "Video").put("VideoCodec", "h264").put("AudioCodec", "aac,mp3"))) + .put("CodecProfiles", JSONArray().put(JSONObject().put("Type", "Video").put("Codec", "h264").put("Conditions", conditions))) + .put("TranscodingProfiles", JSONArray().put(JSONObject().put("Container", "ts").put("Type", "Video").put("Protocol", "hls") + .put("VideoCodec", "h264").put("AudioCodec", "aac").put("Context", "Streaming").put("MaxAudioChannels", "2").put("MinSegments", 1))) + .put("SubtitleProfiles", JSONArray().put(JSONObject().put("Format", "srt").put("Method", "External")) + .put(JSONObject().put("Format", "vtt").put("Method", "External"))) + } + } +} diff --git a/library-jellyfin/src/test/kotlin/com/ttstd/player/library/jellyfin/JellyfinLibraryTest.kt b/library-jellyfin/src/test/kotlin/com/ttstd/player/library/jellyfin/JellyfinLibraryTest.kt new file mode 100644 index 0000000..40f697d --- /dev/null +++ b/library-jellyfin/src/test/kotlin/com/ttstd/player/library/jellyfin/JellyfinLibraryTest.kt @@ -0,0 +1,51 @@ +package com.ttstd.player.library.jellyfin + +import com.ttstd.player.library.* +import com.ttstd.player.api.MediaSourceType +import kotlinx.coroutines.runBlocking +import okhttp3.mockwebserver.* +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class JellyfinLibraryTest { + @Test fun authenticatesBrowsesNegotiatesTranscodingAndReportsAbsolutePosition() = runBlocking { + MockWebServer().use { server -> + server.enqueue(MockResponse().setBody("""{"AccessToken":"token-test","User":{"Id":"user-id"}}""")) + server.enqueue(MockResponse().setBody("""{"Items":[{"Id":"library","Name":"Movies","IsFolder":true}],"TotalRecordCount":1}""")) + server.enqueue(MockResponse().setBody("""{"PlaySessionId":"session-id","MediaSources":[{"Id":"source-id","SupportsDirectPlay":false,"TranscodingUrl":"Videos/item/master.m3u8","MediaStreams":[]}]}""")) + repeat(4) { server.enqueue(MockResponse().setResponseCode(204)) } + server.start() + val library = JellyfinLibrary(LibraryAccount("id", "JF", LibraryKind.JELLYFIN, server.url("/jf/").toString(), "user", "secret")) + assertTrue(library.list().entries.single().isFolder) + val playback = library.resolve(LibraryEntry("item", "Movie", false), LibraryPlaybackOptions(startPositionMs = 5000)) + assertEquals(MediaSourceType.HLS, playback.request.sourceType) + assertEquals(0L, playback.request.startPositionMs) + assertEquals(5000L, playback.positionOffsetMs) + assertTrue(playback.request.uri.contains("ApiKey=token-test")) + val session = checkNotNull(playback.session) + session.started(0) + session.progress(1000, true) + session.stopped(2000) + val login = server.takeRequest() + assertEquals("/jf/Users/AuthenticateByName", login.path) + assertEquals("secret", JSONObject(login.body.readUtf8()).getString("Pw")) + server.takeRequest() + val negotiation = server.takeRequest() + assertTrue(negotiation.getHeader("Authorization")!!.contains("Token=\"token-test\"")) + val profile = JSONObject(negotiation.body.readUtf8()).getJSONObject("DeviceProfile") + assertEquals(4_000_000, profile.getInt("MaxStreamingBitrate")) + assertEquals("h264", profile.getJSONArray("TranscodingProfiles").getJSONObject(0).getString("VideoCodec")) + assertTrue(server.takeRequest().path!!.endsWith("/Sessions/Playing")) + val progress = server.takeRequest() + assertEquals(60_000_000L, JSONObject(progress.body.readUtf8()).getLong("PositionTicks")) + assertTrue(server.takeRequest().path!!.endsWith("/Sessions/Playing/Stopped")) + assertTrue(server.takeRequest().path!!.contains("PlaySessionId=session-id")) + } + } +} diff --git a/library-media3/build.gradle.kts b/library-media3/build.gradle.kts new file mode 100644 index 0000000..76dda63 --- /dev/null +++ b/library-media3/build.gradle.kts @@ -0,0 +1,16 @@ +plugins { id("com.android.library"); kotlin("android") } +android { + namespace = "com.ttstd.player.librarymedia3" + compileSdk = 37 + defaultConfig { minSdk = 23 } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } +} +kotlin { jvmToolchain(17) } +dependencies { + api(project(":library-api")) + implementation(project(":library-smb")) + implementation(project(":library-storage")) + implementation(project(":player-media3-source")) + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") + implementation("androidx.media3:media3-datasource:1.11.1") +} diff --git a/library-media3/src/main/AndroidManifest.xml b/library-media3/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/library-media3/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/library-media3/src/main/kotlin/com/ttstd/player/library/media3/LibraryPlaybackBridge.kt b/library-media3/src/main/kotlin/com/ttstd/player/library/media3/LibraryPlaybackBridge.kt new file mode 100644 index 0000000..860ab66 --- /dev/null +++ b/library-media3/src/main/kotlin/com/ttstd/player/library/media3/LibraryPlaybackBridge.kt @@ -0,0 +1,119 @@ +@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +package com.ttstd.player.library.media3 + +import android.content.Context +import android.net.Uri +import androidx.media3.common.C +import androidx.media3.datasource.* +import com.ttstd.player.api.* +import com.ttstd.player.library.* +import com.ttstd.player.library.smb.* +import com.ttstd.player.library.storage.PlaybackBookmarks +import com.ttstd.player.media3.source.Media3TransportRegistry +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.* +import java.io.EOFException +import java.io.IOException + +/** 宿主进程初始化一次。账户查找在数据源 IO 线程进行,不把凭证写入媒体 URI。 */ +object SmbSourceInstaller { + fun install(accounts: (String) -> LibraryAccount?) { + Media3TransportRegistry.register("tt-source") { + DataSource.Factory { + object : BaseDataSource(true) { + private var reader: SmbRandomReader? = null + private var currentUri: Uri? = null + private var position = 0L + private var remaining = 0L + private var opened = false + override fun open(dataSpec: DataSpec): Long { + transferInitializing(dataSpec) + try { + val account = accounts(dataSpec.uri.host.orEmpty()) ?: throw IOException("来源账户不存在") + val handle = SmbLibrary(account).openReader(dataSpec.uri.path.orEmpty().trimStart('/')) + reader = handle + if (dataSpec.position > handle.length) throw EOFException("读取位置超过文件长度") + position = dataSpec.position + remaining = (handle.length - position).let { if (dataSpec.length == C.LENGTH_UNSET.toLong()) it else minOf(it, dataSpec.length) } + currentUri = dataSpec.uri; opened = true; transferStarted(dataSpec) + return remaining + } catch (_: Exception) { close(); throw IOException("SMB 文件读取失败") } + } + override fun read(buffer: ByteArray, offset: Int, length: Int): Int { + if (length == 0) return 0 + if (remaining == 0L) return C.RESULT_END_OF_INPUT + val count = try { reader?.read(buffer, position, offset, minOf(length.toLong(), remaining).toInt()) ?: -1 } + catch (_: Exception) { throw IOException("SMB 连接中断") } + if (count < 0) return C.RESULT_END_OF_INPUT + if (count == 0) throw IOException("SMB 未返回数据") + position += count; remaining -= count; bytesTransferred(count) + return count + } + override fun getUri(): Uri? = currentUri + override fun close() { + try { reader?.close() } finally { + reader = null; currentUri = null + if (opened) { opened = false; transferEnded() } + } + } + } + } + } + } +} + +/** 断点与媒体服务会话协调器。上报失败与本地播放隔离,间隔 10 秒。 + * close 在播放器 release 前调用;远端 stopped 有独立的有界清理协程。 + */ +class LibraryPlaybackTracker(context: Context, private val engine: PlayerEngine, private val scope: CoroutineScope) : AutoCloseable { + private val bookmarks = PlaybackBookmarks(context) + private var current: LibraryPlayback? = null + private var job: Job? = null + fun bind(playback: LibraryPlayback) { + close() + current = playback + job = scope.launch { + var started = false + var savedAt = 0L + var reportedAt = 0L + var lastPaused: Boolean? = null + val ticks = flow { while (currentCoroutineContext().isActive) { emit(Unit); delay(10_000) } } + combine(engine.state, ticks) { state, _ -> state }.collect { state -> + if (state.phase != PlaybackPhase.IDLE && state.phase != PlaybackPhase.RELEASED && state.phase != PlaybackPhase.ERROR) { + val now = android.os.SystemClock.elapsedRealtime() + val paused = !state.playWhenReady + if (now - savedAt >= 5000 || lastPaused != paused || state.phase == PlaybackPhase.ENDED) { + bookmarks.save(playback.stableId, state.positionMs + playback.positionOffsetMs, playback.originalDurationMs ?: state.durationMs?.plus(playback.positionOffsetMs)) + savedAt = now + } + try { + if (!started && state.isPlaying) { playback.session?.started(state.positionMs); started = true } + else if (started && (now - reportedAt >= 10_000 || lastPaused != paused || state.phase == PlaybackPhase.ENDED)) { + playback.session?.progress(state.positionMs, paused) + reportedAt = now + } + } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { } + lastPaused = paused + } + } + } + } + fun checkpoint() { + val playback = current ?: return + val state = engine.state.value + if (state.phase != PlaybackPhase.IDLE && state.phase != PlaybackPhase.RELEASED) + bookmarks.save(playback.stableId, state.positionMs + playback.positionOffsetMs, playback.originalDurationMs ?: state.durationMs?.plus(playback.positionOffsetMs)) + } + /** 将会话交给投屏,不发送 Stopped;新所有者必须继续上报并最终结束会话。 */ + fun detach() { checkpoint(); job?.cancel(); job = null; current = null } + override fun close() { + val old = current + checkpoint() + job?.cancel(); job = null; current = null + val session = old?.session + if (session != null) { + val position = engine.state.value.positionMs + CoroutineScope(Dispatchers.IO).launch { withTimeoutOrNull(5000) { runCatching { session.stopped(position) } } } + } + } +} diff --git a/library-smb/build.gradle.kts b/library-smb/build.gradle.kts new file mode 100644 index 0000000..ac1317b --- /dev/null +++ b/library-smb/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { id("com.android.library"); kotlin("android") } +android { + namespace = "com.ttstd.player.librarysmb" + compileSdk = 37 + defaultConfig { minSdk = 23 } + testOptions { unitTests.isIncludeAndroidResources = true } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } +} +kotlin { jvmToolchain(17) } +dependencies { +api(project(":library-api")) +implementation("com.hierynomus:smbj:0.13.0") +implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +testImplementation("org.robolectric:robolectric:4.14.1") +testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") +testImplementation("junit:junit:4.13.2") +} diff --git a/library-smb/src/main/AndroidManifest.xml b/library-smb/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/library-smb/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/library-smb/src/main/kotlin/com/ttstd/player/library/smb/SmbLibrary.kt b/library-smb/src/main/kotlin/com/ttstd/player/library/smb/SmbLibrary.kt new file mode 100644 index 0000000..693774f --- /dev/null +++ b/library-smb/src/main/kotlin/com/ttstd/player/library/smb/SmbLibrary.kt @@ -0,0 +1,93 @@ +package com.ttstd.player.library.smb + +import com.hierynomus.msdtyp.AccessMask +import com.hierynomus.msfscc.FileAttributes +import com.hierynomus.msfscc.fileinformation.FileStandardInformation +import com.hierynomus.mssmb2.* +import com.hierynomus.smbj.SMBClient +import com.hierynomus.smbj.SmbConfig +import com.hierynomus.smbj.auth.AuthenticationContext +import com.hierynomus.smbj.share.DiskShare +import com.ttstd.player.api.* +import com.ttstd.player.library.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.net.URI +import java.util.EnumSet +import java.util.concurrent.TimeUnit + +/** SMB2/3 来源,不把密码写入 smb URI。连接超时有界,每个随机读取句柄独占连接。 */ +class SmbLibrary(override val account: LibraryAccount) : MediaLibrary { + private val root = URI(account.endpoint) + private val parts = root.path.trim('/').split('/').filter { it.isNotEmpty() } + private val shareName = parts.firstOrNull() ?: throw LibraryException("SMB 地址必须包含共享名") + private val base = parts.drop(1).joinToString("\\") + + fun openConnection(): SmbConnection { + require(root.scheme.equals("smb", true) && root.host != null && root.userInfo == null) + val client = SMBClient(SmbConfig.builder().withTimeout(10, TimeUnit.SECONDS).withSoTimeout(10, TimeUnit.SECONDS).build()) + try { + val connection = client.connect(root.host, if (root.port > 0) root.port else 445) + try { + val auth = if (account.username.isBlank()) AuthenticationContext.anonymous() + else AuthenticationContext(account.username, account.password.toCharArray(), account.domain) + val session = connection.authenticate(auth) + val share = session.connectShare(shareName) as? DiskShare ?: throw LibraryException("不是磁盘共享") + return SmbConnection(client, connection, session, share) + } catch (e: Exception) { connection.close(); throw e } + } catch (e: Exception) { client.close(); throw LibraryException("SMB 连接或认证失败") } + } + private fun path(id: String): String { + require(id.split('/', '\\').none { it == ".." || it == "." } && !id.startsWith('/') && !id.startsWith('\\')) { "非法 SMB 路径" } + return listOf(base, id.replace('/', '\\')).filter { it.isNotEmpty() }.joinToString("\\") + } + override suspend fun list(folderId: String, offset: Int): LibraryPage = withContext(Dispatchers.IO) { + openConnection().use { connection -> + val entries = connection.share.list(path(folderId)).filter { it.fileName != "." && it.fileName != ".." }.map { + LibraryEntry(listOf(folderId, it.fileName).filter(String::isNotEmpty).joinToString("/"), it.fileName, + it.fileAttributes and FileAttributes.FILE_ATTRIBUTE_DIRECTORY.value != 0L, + it.endOfFile, it.lastWriteTime.toString()) + }.sortedWith(compareBy { !it.isFolder }.thenBy { it.name.lowercase() }) + LibraryPage(entries) + } + } + /** tt-source URI 只包含账户 ID 与路径,DataSource 通过宿主账户仓库取得凭证。 */ + fun uri(id: String): String = URI("tt-source", account.id, "/$id", null).toASCIIString() + override suspend fun resolve(entry: LibraryEntry, options: LibraryPlaybackOptions): LibraryPlayback { + require(!entry.isFolder) + val parent = entry.id.substringBeforeLast('/', "") + val siblings = list(parent).entries + val fresh = siblings.firstOrNull { it.id == entry.id } ?: entry + val subtitles = siblings.filter { LibraryFiles.matchesSubtitle(entry.name, it.name) && !it.isFolder } + .map { ExternalSubtitle(uri(it.id), LibraryFiles.subtitleMime(it.name)!!) } + val key = "${account.id}:${fresh.id}:${fresh.version}:${fresh.size}" + return LibraryPlayback(PlaybackRequest(uri(entry.id), startPositionMs = options.startPositionMs, autoplay = true, + subtitles = subtitles, cacheKey = key), key, fresh.name, fresh.size, subtitles = subtitles, + refresh = { position -> resolve(fresh, options.copy(startPositionMs = position)) }) + } + fun openReader(id: String): SmbRandomReader { + val connection = openConnection() + try { + val file = connection.share.openFile(path(id), EnumSet.of(AccessMask.GENERIC_READ), EnumSet.of(FileAttributes.FILE_ATTRIBUTE_NORMAL), + SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OPEN, EnumSet.of(SMB2CreateOptions.FILE_NON_DIRECTORY_FILE)) + return SmbRandomReader(connection, file) + } catch (e: Exception) { connection.close(); throw LibraryException("无法打开 SMB 文件") } + } +} + +class SmbConnection( + private val client: SMBClient, + private val connection: com.hierynomus.smbj.connection.Connection, + private val session: com.hierynomus.smbj.session.Session, + val share: DiskShare, +) : AutoCloseable { + override fun close() { + runCatching { share.close() }; runCatching { session.close() }; runCatching { connection.close() }; runCatching { client.close() } + } +} +/** 连续读取复用句柄,seek 直接使用服务器偏移,不通过 skip 从头读。 */ +class SmbRandomReader(private val connection: SmbConnection, private val file: com.hierynomus.smbj.share.File) : AutoCloseable { + val length: Long = file.getFileInformation(FileStandardInformation::class.java).endOfFile + fun read(buffer: ByteArray, position: Long, offset: Int, length: Int): Int = file.read(buffer, position, offset, length) + override fun close() { try { file.close() } finally { connection.close() } } +} diff --git a/library-storage/build.gradle.kts b/library-storage/build.gradle.kts new file mode 100644 index 0000000..0882a95 --- /dev/null +++ b/library-storage/build.gradle.kts @@ -0,0 +1,16 @@ +plugins { id("com.android.library"); kotlin("android") } +android { + namespace = "com.ttstd.player.librarystorage" + compileSdk = 37 + defaultConfig { minSdk = 23 } + testOptions { unitTests.isIncludeAndroidResources = true } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } +} +kotlin { jvmToolchain(17) } +dependencies { +api(project(":library-api")) +implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +testImplementation("org.robolectric:robolectric:4.14.1") +testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") +testImplementation("junit:junit:4.13.2") +} diff --git a/library-storage/src/main/AndroidManifest.xml b/library-storage/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/library-storage/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/library-storage/src/main/kotlin/com/ttstd/player/library/storage/LibraryStorage.kt b/library-storage/src/main/kotlin/com/ttstd/player/library/storage/LibraryStorage.kt new file mode 100644 index 0000000..508845b --- /dev/null +++ b/library-storage/src/main/kotlin/com/ttstd/player/library/storage/LibraryStorage.kt @@ -0,0 +1,61 @@ +package com.ttstd.player.library.storage + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import com.ttstd.player.library.* +import org.json.JSONArray +import org.json.JSONObject +import java.security.KeyStore +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** Android Keystore AES-GCM 加密来源配置;密文和 IV 存在应用私有 preferences。 + * 不做明文回退,密钥失效时应由 UI 提示重新配置。凭证不进入日志/备份。 + */ +class LibraryAccounts(context: Context) { + private val prefs = context.applicationContext.getSharedPreferences("library-accounts", Context.MODE_PRIVATE) + private fun key(): SecretKey { + val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (store.getKey("tt-video-accounts-v1", null) as? SecretKey)?.let { return it } + return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply { + init(KeyGenParameterSpec.Builder("tt-video-accounts-v1", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build()) + }.generateKey() + } + @Synchronized fun all(): List { + val value = prefs.getString("accounts", null) ?: return emptyList() + val bytes = Base64.decode(value, Base64.NO_WRAP) + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, bytes.copyOfRange(0, 12))) + val items = JSONArray(String(cipher.doFinal(bytes.copyOfRange(12, bytes.size)), Charsets.UTF_8)) + return (0 until items.length()).map { i -> items.getJSONObject(i).let { + LibraryAccount(it.getString("id"), it.getString("name"), LibraryKind.valueOf(it.getString("kind")), + it.getString("endpoint"), it.optString("username"), it.optString("password"), it.optString("domain")) + } } + } + @Synchronized fun save(account: LibraryAccount) { write(all().filterNot { it.id == account.id } + account) } + @Synchronized fun delete(id: String) { write(all().filterNot { it.id == id }) } + private fun write(accounts: List) { + val array = JSONArray() + accounts.forEach { a -> array.put(JSONObject().put("id", a.id).put("name", a.name).put("kind", a.kind.name) + .put("endpoint", a.endpoint).put("username", a.username).put("password", a.password).put("domain", a.domain)) } + val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, key()) } + val bytes = cipher.doFinal(array.toString().toByteArray()) + prefs.edit().putString("accounts", Base64.encodeToString(cipher.iv + bytes, Base64.NO_WRAP)).apply() + } +} + +/** 书签使用稳定媒体标识的哈希,不保存带密码/签名参数的播放 URL。 */ +class PlaybackBookmarks(context: Context) { + private val prefs = context.applicationContext.getSharedPreferences("playback-bookmarks", Context.MODE_PRIVATE) + private fun key(id: String) = java.security.MessageDigest.getInstance("SHA-256").digest(id.toByteArray()).joinToString("") { "%02x".format(it) } + fun position(id: String): Long = prefs.getLong(key(id), 0) + fun save(id: String, positionMs: Long, durationMs: Long?) { + val position = if (durationMs != null && durationMs > 0 && durationMs - positionMs < 10_000) 0 else positionMs.coerceAtLeast(0) + prefs.edit().putLong(key(id), position).apply() + } +} diff --git a/library-storage/src/test/kotlin/com/ttstd/player/library/storage/PlaybackBookmarksTest.kt b/library-storage/src/test/kotlin/com/ttstd/player/library/storage/PlaybackBookmarksTest.kt new file mode 100644 index 0000000..58d3151 --- /dev/null +++ b/library-storage/src/test/kotlin/com/ttstd/player/library/storage/PlaybackBookmarksTest.kt @@ -0,0 +1,20 @@ +package com.ttstd.player.library.storage +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class PlaybackBookmarksTest { + @Test fun restoresPositionsAndClearsCompletedItems() { + val store = PlaybackBookmarks(RuntimeEnvironment.getApplication()) + store.save("source:movie:v1", 15000, 60000) + assertEquals(15000L, store.position("source:movie:v1")) + assertEquals(0L, store.position("source:movie:v2")) + store.save("source:movie:v1", 55000, 60000) + assertEquals(0L, store.position("source:movie:v1")) + } +} diff --git a/library-webdav/build.gradle.kts b/library-webdav/build.gradle.kts new file mode 100644 index 0000000..ed05450 --- /dev/null +++ b/library-webdav/build.gradle.kts @@ -0,0 +1,16 @@ +plugins { id("com.android.library"); kotlin("android") } +android { + namespace = "com.ttstd.player.librarywebdav" + compileSdk = 37 + defaultConfig { minSdk = 23 } + testOptions { unitTests.isIncludeAndroidResources = true } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } +} +kotlin { jvmToolchain(17) } +dependencies { +api(project(":library-http")) +implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +testImplementation("org.robolectric:robolectric:4.14.1") +testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") +testImplementation("junit:junit:4.13.2") +} diff --git a/library-webdav/src/main/AndroidManifest.xml b/library-webdav/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/library-webdav/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/library-webdav/src/main/kotlin/com/ttstd/player/library/webdav/WebDavLibrary.kt b/library-webdav/src/main/kotlin/com/ttstd/player/library/webdav/WebDavLibrary.kt new file mode 100644 index 0000000..bf1d4e5 --- /dev/null +++ b/library-webdav/src/main/kotlin/com/ttstd/player/library/webdav/WebDavLibrary.kt @@ -0,0 +1,59 @@ +package com.ttstd.player.library.webdav + +import com.ttstd.player.api.* +import com.ttstd.player.library.* +import com.ttstd.player.library.http.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody + +/** 支持 Basic 认证和匿名 WebDAV。href 必须同源且处于配置根目录内。 */ +class WebDavLibrary(override val account: LibraryAccount) : MediaLibrary { + private val root = (account.endpoint.trimEnd('/') + "/").toHttpUrl() + private val headers = if (account.username.isEmpty()) emptyMap() else mapOf("Authorization" to Credentials.basic(account.username, account.password)) + + private fun url(id: String): HttpUrl { + val result = if (id.isEmpty()) root else id.toHttpUrl() + require(result.scheme == root.scheme && result.host == root.host && result.port == root.port && + result.encodedPath.startsWith(root.encodedPath)) { "目录超出来源范围" } + return result + } + override suspend fun list(folderId: String, offset: Int): LibraryPage = withContext(Dispatchers.IO) { + val target = url(folderId) + val xml = """""" + val request = Request.Builder().url(target).method("PROPFIND", xml.toRequestBody("application/xml; charset=utf-8".toMediaType())) + .header("Depth", "1").apply { headers.forEach { (k, v) -> header(k, v) } }.build() + LibraryHttp.execute(request).use { response -> + val document = SafeXml.parse(LibraryHttp.checkedBody(response)) + val entries = SafeXml.elements(document, "response").mapNotNull { item -> + val href = SafeXml.text(item, "href") + val child = target.resolve(href) ?: return@mapNotNull null + if (runCatching { url(child.toString()) }.isFailure || child.encodedPath.trimEnd('/') == target.encodedPath.trimEnd('/')) return@mapNotNull null + val propstat = SafeXml.elements(item, "propstat").firstOrNull { SafeXml.text(it, "status").contains(" 200 ") } ?: return@mapNotNull null + val name = SafeXml.text(propstat, "displayname").ifBlank { child.pathSegments.lastOrNull { it.isNotEmpty() }.orEmpty() } + LibraryEntry(child.toString(), name, SafeXml.elements(propstat, "collection").isNotEmpty(), + SafeXml.text(propstat, "getcontentlength").toLongOrNull(), + SafeXml.text(propstat, "getetag").ifBlank { SafeXml.text(propstat, "getlastmodified") }) + }.sortedWith(compareBy { !it.isFolder }.thenBy { it.name.lowercase() }) + LibraryPage(entries) + } + } + + override suspend fun resolve(entry: LibraryEntry, options: LibraryPlaybackOptions): LibraryPlayback { + require(!entry.isFolder) + val target = url(entry.id) + val parent = target.newBuilder().removePathSegment(target.pathSegments.lastIndex).addPathSegment("").build() + val siblings = list(parent.toString()).entries + val fresh = siblings.firstOrNull { it.id == entry.id } ?: entry + val subtitles = siblings.filter { !it.isFolder && LibraryFiles.matchesSubtitle(entry.name, it.name) } + .map { ExternalSubtitle(url(it.id).toString(), LibraryFiles.subtitleMime(it.name)!!) } + val key = "${account.id}:${fresh.id}:${fresh.version}:${fresh.size}" + val request = PlaybackRequest(target.toString(), headers, options.startPositionMs, true, subtitles, + cacheKey = key) + return LibraryPlayback(request, key, fresh.name, fresh.size, subtitles = subtitles, + receiverRequest = request.takeIf { headers.isEmpty() }, refresh = { position -> resolve(fresh, options.copy(startPositionMs = position)) }) + } +} diff --git a/library-webdav/src/test/kotlin/com/ttstd/player/library/webdav/WebDavLibraryTest.kt b/library-webdav/src/test/kotlin/com/ttstd/player/library/webdav/WebDavLibraryTest.kt new file mode 100644 index 0000000..689e752 --- /dev/null +++ b/library-webdav/src/test/kotlin/com/ttstd/player/library/webdav/WebDavLibraryTest.kt @@ -0,0 +1,51 @@ +package com.ttstd.player.library.webdav + +import com.ttstd.player.library.* +import kotlinx.coroutines.runBlocking +import okhttp3.Credentials +import okhttp3.mockwebserver.* +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class WebDavLibraryTest { + private val listing = """ + /dav/HTTP/1.1 200 OK + /dav/Movie.mp4Movie.mp4123v1HTTP/1.1 200 OK + /dav/Movie.zh.srtMovie.zh.srtHTTP/1.1 200 OK + http://other.test/stealHTTP/1.1 200 OK + """ + @Test fun browsesAuthenticatedDirectoryAndResolvesSubtitles() = runBlocking { + MockWebServer().use { server -> + server.enqueue(MockResponse().setResponseCode(207).setBody(listing)) + server.enqueue(MockResponse().setResponseCode(207).setBody(listing)) + server.start() + val library = WebDavLibrary(LibraryAccount("id", "DAV", LibraryKind.WEBDAV, server.url("/dav/").toString(), "user", "secret")) + val entries = library.list().entries + assertEquals(2, entries.size) + val playback = library.resolve(entries.first { it.name == "Movie.mp4" }) + assertEquals(123L, playback.contentLength) + assertEquals(1, playback.request.subtitles.size) + assertEquals("application/x-subrip", playback.request.subtitles[0].mimeType) + assertNotNull(playback.request.cacheKey) + assertNull(playback.receiverRequest) + val request = server.takeRequest() + assertEquals("PROPFIND", request.method) + assertEquals("1", request.getHeader("Depth")) + assertEquals(Credentials.basic("user", "secret"), request.getHeader("Authorization")) + } + } + @Test fun rejectsRedirectInsteadOfForwardingCredentials() = runBlocking { + MockWebServer().use { server -> + server.enqueue(MockResponse().setResponseCode(302).setHeader("Location", "https://other.test/dav")) + server.start() + val library = WebDavLibrary(LibraryAccount("id", "DAV", LibraryKind.WEBDAV, server.url("/dav/").toString(), "user", "secret")) + assertTrue(runCatching { library.list() }.exceptionOrNull() is LibraryException) + assertEquals(1, server.requestCount) + } + } +} diff --git a/player-android-api/build.gradle.kts b/player-android-api/build.gradle.kts new file mode 100644 index 0000000..b349970 --- /dev/null +++ b/player-android-api/build.gradle.kts @@ -0,0 +1,24 @@ +plugins { + id("com.android.library") + kotlin("android") +} + +android { + namespace = "com.ttstd.player.androidapi" + compileSdk = 37 + + defaultConfig { + minSdk = 23 + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} + +kotlin { jvmToolchain(17) } + +dependencies { + api(project(":player-api")) +} diff --git a/player-android-api/src/main/AndroidManifest.xml b/player-android-api/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/player-android-api/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/player-android-api/src/main/kotlin/com/ttstd/player/android/AndroidVideoOutput.kt b/player-android-api/src/main/kotlin/com/ttstd/player/android/AndroidVideoOutput.kt new file mode 100644 index 0000000..e033e3d --- /dev/null +++ b/player-android-api/src/main/kotlin/com/ttstd/player/android/AndroidVideoOutput.kt @@ -0,0 +1,12 @@ +package com.ttstd.player.android + +import android.view.Surface +import com.ttstd.player.api.CommandResult + +/** 平台输出扩展。必须在主线程调用;实现不拥有传入 Surface,不负责 release 它。 + * 清理时携带原 Surface 身份,防止旧 View 的销毁回调清除新 View 的输出。 + */ +interface AndroidVideoOutput { + fun attachSurface(surface: Surface): CommandResult + fun detachSurface(surface: Surface) +} diff --git a/player-api/build.gradle.kts b/player-api/build.gradle.kts new file mode 100644 index 0000000..e156399 --- /dev/null +++ b/player-api/build.gradle.kts @@ -0,0 +1,10 @@ +plugins { + kotlin("jvm") + `java-library` +} + +kotlin { jvmToolchain(17) } + +dependencies { + api("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") +} diff --git a/player-api/src/main/kotlin/com/ttstd/player/api/PlayerEngine.kt b/player-api/src/main/kotlin/com/ttstd/player/api/PlayerEngine.kt new file mode 100644 index 0000000..ccd99d5 --- /dev/null +++ b/player-api/src/main/kotlin/com/ttstd/player/api/PlayerEngine.kt @@ -0,0 +1,106 @@ +package com.ttstd.player.api + +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.StateFlow + +/** 平台无关播放契约。命令按调用顺序串行执行;成功仅代表接受命令,首帧由事件报告。 + * release 幂等;释放后其他命令返回 Released。实现不得把内核类型泄漏到业务层。 + */ +interface PlayerEngine { + val capabilities: PlayerCapabilities + val state: StateFlow + /** 热流,无历史回放;诊断不能代替 state。先订阅再 prepare。 */ + val events: Flow + suspend fun prepare(request: PlaybackRequest): CommandResult + suspend fun play(): CommandResult + suspend fun pause(): CommandResult + suspend fun seekTo(positionMs: Long): CommandResult + suspend fun setSpeed(speed: Float): CommandResult + suspend fun setVolume(volume: Float): CommandResult + suspend fun selectTrack(selection: TrackSelection): CommandResult + /** 策略针对后续和当前媒体;实现若需重建,必须保留进度、轨道及播放意图。 */ + suspend fun setDecodePolicy(policy: DecodePolicy): CommandResult + suspend fun release() +} + +/** 工厂每次创建独立实例;创建过程不加载媒体。 */ +fun interface PlayerEngineFactory { fun create(): PlayerEngine } + +data class PlaybackRequest( + val uri: String, + val headers: Map = emptyMap(), + val startPositionMs: Long = 0, + val autoplay: Boolean = false, + val subtitles: List = emptyList(), + /** 无扩展名的网关地址必须显式指定 HLS/DASH 等,不能靠响应头猜测。 */ + val sourceType: MediaSourceType = MediaSourceType.AUTO, + val network: NetworkOptions = NetworkOptions(), + /** 来源提供的稳定文件标识(含版本),不得使用短效 token;仅用于普通文件缓存。 */ + val cacheKey: String? = null, +) + +enum class MediaSourceType { AUTO, PROGRESSIVE, HLS, DASH, SMOOTH_STREAMING, FLV, RTMP, RTSP } + +/** HTTP headers 仅用于 HTTP(S);RTSP 认证使用 URI 中的用户信息。 + * RTSP AUTO 为先 UDP、无数据时由内核尝试 TCP;TCP 为强制交错 RTP/TCP。 + */ +enum class RtspTransport { AUTO, TCP } +data class NetworkOptions( + val connectTimeoutMs: Int = 8_000, + val readTimeoutMs: Int = 8_000, + val rtspTimeoutMs: Long = 8_000, + val rtspTransport: RtspTransport = RtspTransport.AUTO, +) + +/** mimeType 例如 application/x-subrip;字幕与主媒体共享 headers。 */ +data class ExternalSubtitle(val uri: String, val mimeType: String, val language: String? = null, val isDefault: Boolean = false) +enum class DecodeMode { AUTO, PREFER_HARDWARE, HARDWARE_ONLY, SOFTWARE_ONLY } +data class DecodePolicy(val video: DecodeMode = DecodeMode.AUTO, val audio: DecodeMode = DecodeMode.AUTO) +enum class TrackType { VIDEO, AUDIO, TEXT } +/** id 仅在当前媒体轨道列表内有效,不保证跨媒体或内核重建稳定。 */ +data class MediaTrack(val id: String, val type: TrackType, val label: String?, val language: String?, val selected: Boolean) +/** id=null 恢复自动选择;disabled=true 关闭该类轨道。 */ +data class TrackSelection(val type: TrackType, val id: String? = null, val disabled: Boolean = false) +enum class PlaybackPhase { IDLE, PREPARING, BUFFERING, READY, ENDED, ERROR, RELEASED } +data class PlaybackState( + val phase: PlaybackPhase = PlaybackPhase.IDLE, + val playWhenReady: Boolean = false, + val isPlaying: Boolean = false, + val positionMs: Long = 0, + /** null 表示未知时长,例如部分直播。 */ + val durationMs: Long? = null, + val bufferedPositionMs: Long = 0, + val tracks: List = emptyList(), + val error: PlaybackError? = null, + /** 当前文本字幕快照,保留到下一次字幕更新,便于界面重建后恢复显示。 */ + val subtitleLines: List = emptyList(), +) +data class PlaybackError(val code: String, val message: String, val recoverable: Boolean = false) +data class PlayerCapabilities( + val engineName: String, + /** 是策略能力,不是每一种编码均能解码的承诺。 */ + val videoDecodeModes: Set, + val audioDecodeModes: Set, + val externalSubtitles: Boolean = true, + val trackSelection: Boolean = true, + val sourceTypes: Set = emptySet(), +) +sealed interface CommandResult { + data object Accepted : CommandResult + data object Released : CommandResult + data class Unsupported(val reason: String) : CommandResult + data class InvalidArgument(val reason: String) : CommandResult + data class Failed(val error: PlaybackError) : CommandResult +} +/** 不携带 URL、请求头或异常对象,避免诊断接口意外泄漏凭证。 */ +sealed interface PlaybackEvent { + data object FirstFrame : PlaybackEvent + data object Ended : PlaybackEvent + data class Error(val error: PlaybackError) : PlaybackEvent + /** isHardware=null 表示无法可靠分类,不猜测厂商解码器。 */ + data class DecoderChanged(val type: TrackType, val name: String, val isHardware: Boolean?) : PlaybackEvent + data class DroppedFrames(val count: Int, val elapsedMs: Long) : PlaybackEvent + data class VideoSize(val width: Int, val height: Int, val pixelRatio: Float) : PlaybackEvent + /** 相对 prepare 的耗时;使用单调时钟。 */ + data class StartupTime(val elapsedMs: Long) : PlaybackEvent +} diff --git a/player-cast-api/build.gradle.kts b/player-cast-api/build.gradle.kts new file mode 100644 index 0000000..030ed3e --- /dev/null +++ b/player-cast-api/build.gradle.kts @@ -0,0 +1,6 @@ +plugins { kotlin("jvm"); `java-library` } +kotlin { jvmToolchain(17) } +dependencies { +api(project(":player-api")) +testImplementation("junit:junit:4.13.2") +} diff --git a/player-cast-api/src/main/kotlin/com/ttstd/player/cast/Casting.kt b/player-cast-api/src/main/kotlin/com/ttstd/player/cast/Casting.kt new file mode 100644 index 0000000..7a5a169 --- /dev/null +++ b/player-cast-api/src/main/kotlin/com/ttstd/player/cast/Casting.kt @@ -0,0 +1,66 @@ +package com.ttstd.player.cast + +import com.ttstd.player.api.* +import java.net.URI + +enum class CastRoute { DIRECT, RELAY, UNSUPPORTED } +data class CastDecision(val route: CastRoute, val mimeType: String, val reason: String = "") + +/** 投屏是把媒体地址交给接收端,不是屏幕镜像。私有文件通过手机 HTTP relay 按 Range 提供。 */ +object CastPolicy { + fun assess(request: PlaybackRequest): CastDecision { + val uri = runCatching { URI(request.uri) }.getOrNull() + ?: return CastDecision(CastRoute.UNSUPPORTED, "", "媒体地址无效") + val scheme = uri.scheme?.lowercase() + val path = uri.path.orEmpty().lowercase() + val adaptive = request.sourceType in setOf(MediaSourceType.HLS, MediaSourceType.DASH, MediaSourceType.SMOOTH_STREAMING) || + (request.sourceType == MediaSourceType.AUTO && (path.endsWith(".m3u8") || path.endsWith(".mpd") || path.contains(".ism/"))) + val mime = when { + request.sourceType == MediaSourceType.HLS || path.endsWith(".m3u8") -> "application/x-mpegURL" + request.sourceType == MediaSourceType.DASH || path.endsWith(".mpd") -> "application/dash+xml" + path.endsWith(".webm") -> "video/webm" + path.endsWith(".mkv") -> "video/x-matroska" + else -> "video/mp4" + } + if (request.sourceType in setOf(MediaSourceType.RTSP, MediaSourceType.RTMP, MediaSourceType.FLV, MediaSourceType.SMOOTH_STREAMING) || scheme in setOf("rtsp", "rtmp") || path.endsWith(".flv")) + return CastDecision(CastRoute.UNSUPPORTED, mime, "该来源需由媒体服务器转换为接收端支持的 HTTP 视频") + if (scheme in setOf("http", "https") && request.headers.isEmpty() && uri.userInfo == null) + return CastDecision(CastRoute.DIRECT, mime) + if (adaptive) return CastDecision(CastRoute.UNSUPPORTED, mime, "带认证的自适应流需要服务端提供可投屏地址,当前不代理清单与分片") + if (scheme in setOf("http", "https", "tt-source", "file", "content")) return CastDecision(CastRoute.RELAY, mime) + return CastDecision(CastRoute.UNSUPPORTED, mime, "该来源尚不能投屏") + } +} + +/** 单段字节范围。多 Range 请求明确拒绝,不把错误范围当成整文件发送。 */ +data class ByteRange(val start: Long, val endInclusive: Long) { + val length: Long get() = endInclusive - start + 1 + companion object { + fun parse(header: String, total: Long): ByteRange { + require(total > 0 && header.startsWith("bytes=") && !header.contains(',')) + val parts = header.removePrefix("bytes=").split('-', limit = 2) + require(parts.size == 2) + val start: Long + val end: Long + if (parts[0].isEmpty()) { + val suffix = parts[1].toLong(); require(suffix > 0) + start = (total - suffix).coerceAtLeast(0); end = total - 1 + } else { + start = parts[0].toLong() + end = parts[1].takeIf(String::isNotEmpty)?.toLong()?.coerceAtMost(total - 1) ?: (total - 1) + } + require(start >= 0 && start < total && end >= start) + return ByteRange(start, end) + } + } +} + +data class RemotePlaybackState(val positionMs: Long = 0, val durationMs: Long? = null, val playing: Boolean = false) +interface CastProgressObserver { + suspend fun started(positionMs: Long) + suspend fun progress(state: RemotePlaybackState) + suspend fun stopped(positionMs: Long) +} +data class CastMedia(val uri: String, val title: String, val mimeType: String, val startPositionMs: Long = 0) { + override fun toString() = "CastMedia(uri=REDACTED, mimeType=$mimeType)" +} diff --git a/player-cast-api/src/test/kotlin/com/ttstd/player/cast/CastPolicyTest.kt b/player-cast-api/src/test/kotlin/com/ttstd/player/cast/CastPolicyTest.kt new file mode 100644 index 0000000..7a7d4e3 --- /dev/null +++ b/player-cast-api/src/test/kotlin/com/ttstd/player/cast/CastPolicyTest.kt @@ -0,0 +1,21 @@ +package com.ttstd.player.cast +import com.ttstd.player.api.* +import org.junit.Assert.* +import org.junit.Test + +class CastPolicyTest { + @Test fun choosesRelayForCredentialsAndRejectsPrivateAdaptiveStreams() { + assertEquals(CastRoute.DIRECT, CastPolicy.assess(PlaybackRequest("https://host/a.mp4")).route) + assertEquals(CastRoute.RELAY, CastPolicy.assess(PlaybackRequest("https://host/a.mp4", mapOf("Authorization" to "secret"))).route) + assertEquals(CastRoute.RELAY, CastPolicy.assess(PlaybackRequest("tt-source://id/movie.mkv")).route) + assertEquals(CastRoute.UNSUPPORTED, CastPolicy.assess(PlaybackRequest("https://host/play", mapOf("Authorization" to "secret"), sourceType = MediaSourceType.HLS)).route) + assertEquals(CastRoute.UNSUPPORTED, CastPolicy.assess(PlaybackRequest("rtsp://host/live")).route) + } + @Test fun rangeParsingSupportsOpenAndSuffixRangesAndRejectsInvalidRanges() { + assertEquals(ByteRange(2, 5), ByteRange.parse("bytes=2-5", 10)) + assertEquals(ByteRange(2, 9), ByteRange.parse("bytes=2-", 10)) + assertEquals(ByteRange(7, 9), ByteRange.parse("bytes=-3", 10)) + assertEquals(ByteRange(0, 9), ByteRange.parse("bytes=-30", 10)) + listOf("bytes=10-", "bytes=5-2", "bytes=0-1,3-4", "bytes=-0").forEach { assertTrue(runCatching { ByteRange.parse(it, 10) }.isFailure) } + } +} diff --git a/player-cast-dlna/build.gradle.kts b/player-cast-dlna/build.gradle.kts new file mode 100644 index 0000000..4120229 --- /dev/null +++ b/player-cast-dlna/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { id("com.android.library"); kotlin("android") } +android { + namespace = "com.ttstd.player.playercastdlna" + compileSdk = 37 + defaultConfig { minSdk = 23 } + testOptions { unitTests.isIncludeAndroidResources = true } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } +} +kotlin { jvmToolchain(17) } +dependencies { +api(project(":player-cast-api")) +implementation(project(":library-http")) +implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +testImplementation("org.robolectric:robolectric:4.14.1") +testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") +testImplementation("junit:junit:4.13.2") +} diff --git a/player-cast-dlna/src/main/AndroidManifest.xml b/player-cast-dlna/src/main/AndroidManifest.xml new file mode 100644 index 0000000..6975988 --- /dev/null +++ b/player-cast-dlna/src/main/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/player-cast-dlna/src/main/kotlin/com/ttstd/player/cast/dlna/DlnaController.kt b/player-cast-dlna/src/main/kotlin/com/ttstd/player/cast/dlna/DlnaController.kt new file mode 100644 index 0000000..c9df9c6 --- /dev/null +++ b/player-cast-dlna/src/main/kotlin/com/ttstd/player/cast/dlna/DlnaController.kt @@ -0,0 +1,86 @@ +package com.ttstd.player.cast.dlna + +import android.content.Context +import android.net.wifi.WifiManager +import com.ttstd.player.cast.* +import com.ttstd.player.library.http.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody +import java.net.* + +data class DlnaDevice(val id: String, val name: String, val serviceType: String, val controlUrl: String) + +/** 前台按需 SSDP M-SEARCH,不常驻监听。SOAP 操作由调用方串行调用。 */ +class DlnaController(context: Context) { + private val context = context.applicationContext + suspend fun discover(durationMs: Long = 3500): List = withContext(Dispatchers.IO) { + val wifi = context.getSystemService(Context.WIFI_SERVICE) as? WifiManager + val lock = wifi?.createMulticastLock("TTVideoPlayer-dlna")?.apply { setReferenceCounted(false); acquire() } + try { + DatagramSocket().use { socket -> + socket.soTimeout = 350 + val message = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 2\r\nST: urn:schemas-upnp-org:device:MediaRenderer:1\r\n\r\n".toByteArray() + repeat(2) { socket.send(DatagramPacket(message, message.size, InetAddress.getByName("239.255.255.250"), 1900)) } + val locations = linkedSetOf() + val until = System.nanoTime() + durationMs.coerceIn(500, 10000) * 1_000_000 + while (System.nanoTime() < until) { + val packet = DatagramPacket(ByteArray(16384), 16384) + try { + socket.receive(packet) + String(packet.data, 0, packet.length).lineSequence().firstOrNull { it.startsWith("location:", true) } + ?.substringAfter(':')?.trim()?.let(locations::add) + } catch (_: SocketTimeoutException) { } + } + locations.mapNotNull { location -> runCatching { describe(location) }.getOrNull() }.distinctBy { it.id } + } + } finally { if (lock?.isHeld == true) lock.release() } + } + internal suspend fun describe(location: String): DlnaDevice { + val url = location.toHttpUrl() + val xml = LibraryHttp.execute(Request.Builder().url(url).build()).use { SafeXml.parse(LibraryHttp.checkedBody(it, 1024 * 1024)) } + val service = SafeXml.elements(xml, "service").firstOrNull { SafeXml.text(it, "serviceType").contains(":AVTransport:") } + ?: throw IllegalArgumentException("设备没有 AVTransport") + val base = SafeXml.text(xml, "URLBase").takeIf { it.isNotBlank() }?.toHttpUrl() ?: url + val control = base.resolve(SafeXml.text(service, "controlURL")) ?: throw IllegalArgumentException("控制地址无效") + require(control.host == url.host) { "设备控制地址跨主机" } + return DlnaDevice(SafeXml.text(xml, "UDN").ifBlank { location }, SafeXml.text(xml, "friendlyName").ifBlank { "DLNA 设备" }, + SafeXml.text(service, "serviceType"), control.toString()) + } + suspend fun load(device: DlnaDevice, media: CastMedia) { + val metadata = """${SafeXml.escape(media.title)}object.item.videoItem${SafeXml.escape(media.uri)}""" + soap(device, "SetAVTransportURI", mapOf("CurrentURI" to media.uri, "CurrentURIMetaData" to metadata)) + play(device) + if (media.startPositionMs > 0) seek(device, media.startPositionMs) + } + suspend fun play(device: DlnaDevice) { soap(device, "Play", mapOf("Speed" to "1")) } + suspend fun pause(device: DlnaDevice) { soap(device, "Pause") } + suspend fun stop(device: DlnaDevice) { soap(device, "Stop") } + suspend fun seek(device: DlnaDevice, positionMs: Long) { + val seconds = positionMs.coerceAtLeast(0) / 1000 + val time = "%02d:%02d:%02d".format(java.util.Locale.ROOT, seconds / 3600, seconds / 60 % 60, seconds % 60) + soap(device, "Seek", mapOf("Unit" to "REL_TIME", "Target" to time)) + } + suspend fun state(device: DlnaDevice): RemotePlaybackState { + val position = SafeXml.parse(soap(device, "GetPositionInfo")) + val transport = SafeXml.parse(soap(device, "GetTransportInfo")) + return RemotePlaybackState(parseTime(SafeXml.text(position, "RelTime")), parseTime(SafeXml.text(position, "TrackDuration")).takeIf { it > 0 }, + SafeXml.text(transport, "CurrentTransportState") == "PLAYING") + } + private suspend fun soap(device: DlnaDevice, action: String, args: Map = emptyMap()): String { + val body = """0${args.entries.joinToString("") { "<${it.key}>${SafeXml.escape(it.value)}" }}""" + return LibraryHttp.execute(Request.Builder().url(device.controlUrl).header("SOAPAction", "\"${device.serviceType}#$action\"") + .post(body.toRequestBody("text/xml; charset=utf-8".toMediaType())).build()).use { + LibraryHttp.checkedBody(it, 1024 * 1024) + } + } + companion object { + fun parseTime(text: String): Long { + val parts = text.substringBefore('.').split(':').mapNotNull(String::toLongOrNull) + return if (parts.size == 3) (parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000 else 0 + } + } +} diff --git a/player-cast-dlna/src/test/kotlin/com/ttstd/player/cast/dlna/DlnaControllerTest.kt b/player-cast-dlna/src/test/kotlin/com/ttstd/player/cast/dlna/DlnaControllerTest.kt new file mode 100644 index 0000000..76cf7f9 --- /dev/null +++ b/player-cast-dlna/src/test/kotlin/com/ttstd/player/cast/dlna/DlnaControllerTest.kt @@ -0,0 +1,42 @@ +package com.ttstd.player.cast.dlna + +import com.ttstd.player.cast.CastMedia +import com.ttstd.player.library.http.SafeXml +import kotlinx.coroutines.runBlocking +import okhttp3.mockwebserver.* +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class DlnaControllerTest { + @Test fun resolvesDeviceAndSendsEscapedTransportCommands() = runBlocking { + MockWebServer().use { server -> + server.enqueue(MockResponse().setBody("""Test TVuuid:testurn:schemas-upnp-org:service:AVTransport:1/control""")) + repeat(3) { server.enqueue(MockResponse().setBody("")) } + server.enqueue(MockResponse().setBody("00:02:0301:00:00")) + server.enqueue(MockResponse().setBody("PLAYING")) + server.start() + val controller = DlnaController(RuntimeEnvironment.getApplication()) + val device = controller.describe(server.url("/description.xml").toString()) + assertEquals("Test TV", device.name) + val media = CastMedia("http://host/movie?a=1&b=2", "Movie <1>", "video/mp4", 5000) + controller.load(device, media) + val state = controller.state(device) + assertEquals(123000L, state.positionMs) + assertTrue(state.playing) + server.takeRequest() + val setUri = server.takeRequest() + assertTrue(setUri.getHeader("SOAPAction")!!.contains("#SetAVTransportURI")) + val xml = SafeXml.parse(setUri.body.readUtf8()) + assertEquals(media.uri, SafeXml.text(xml, "CurrentURI")) + assertTrue(SafeXml.text(xml, "CurrentURIMetaData").contains("Movie <1>")) + server.takeRequest() + assertTrue(server.takeRequest().body.readUtf8().contains("00:00:05")) + } + } +} diff --git a/player-cast-google/build.gradle.kts b/player-cast-google/build.gradle.kts new file mode 100644 index 0000000..0048c34 --- /dev/null +++ b/player-cast-google/build.gradle.kts @@ -0,0 +1,23 @@ +plugins { id("com.android.library"); kotlin("android") } +android { + namespace = "com.ttstd.player.playercastgoogle" + compileSdk = 37 + defaultConfig { minSdk = 23 } + testOptions { unitTests.isIncludeAndroidResources = true } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } +} +kotlin { jvmToolchain(17) } +dependencies { +api(project(":player-cast-api")) +implementation("androidx.media3:media3-cast:1.11.1") +implementation("androidx.media3:media3-exoplayer:1.11.1") +implementation("androidx.media3:media3-exoplayer-hls:1.11.1") +implementation("androidx.media3:media3-exoplayer-dash:1.11.1") +implementation("androidx.media3:media3-session:1.11.1") +implementation("androidx.media3:media3-ui:1.11.1") +implementation("androidx.appcompat:appcompat:1.7.1") +implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +testImplementation("org.robolectric:robolectric:4.14.1") +testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") +testImplementation("junit:junit:4.13.2") +} diff --git a/player-cast-google/src/main/AndroidManifest.xml b/player-cast-google/src/main/AndroidManifest.xml new file mode 100644 index 0000000..c055b57 --- /dev/null +++ b/player-cast-google/src/main/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastActivity.kt b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastActivity.kt new file mode 100644 index 0000000..dcda206 --- /dev/null +++ b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastActivity.kt @@ -0,0 +1,107 @@ +@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +package com.ttstd.player.cast.google + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.widget.* +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.media3.cast.MediaRouteButtonFactory +import androidx.media3.common.* +import androidx.media3.session.MediaController +import androidx.media3.session.SessionToken +import androidx.media3.ui.PlayerView +import androidx.mediarouter.app.MediaRouteButton +import androidx.mediarouter.media.MediaRouter +import com.google.common.util.concurrent.* +import com.ttstd.player.cast.CastMedia + +/** 投屏验证页。手机与接收端均使用服务的同一个 CastPlayer,支持媒体通知和回切。 + * 只接收宿主已解析为无需自定义 HTTP header 的链接(或手机 relay 链接)。 + */ +class GoogleCastActivity : AppCompatActivity() { + private var controller: MediaController? = null + private var future: ListenableFuture? = null + private lateinit var playerView: PlayerView + private lateinit var status: TextView + private var returning = false + private val listener = object : Player.Listener { + override fun onDeviceInfoChanged(deviceInfo: DeviceInfo) { + playerView.player = null + playerView.player = controller + status.text = if (deviceInfo.playbackType == DeviceInfo.PLAYBACK_TYPE_REMOTE) "正在 Google Cast 设备播放" else "本机播放,点击投屏图标选择设备" + } + override fun onPlayerError(error: PlaybackException) { status.text = "投屏播放失败:${error.errorCodeName}" } + } + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } + ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets -> + val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) + view.setPadding(16 + bars.left, bars.top, 16 + bars.right, bars.bottom); insets + } + status = TextView(this).apply { text = "正在连接 Google Cast 服务…" } + root.addView(status) + val route = MediaRouteButton(this) + root.addView(route) + val setup = runCatching { MediaRouteButtonFactory.setUpMediaRouteButton(this, route) }.getOrNull() + if (setup == null) status.text = "Google Cast 不可用,请检查 Google Play 服务与网络" + else Futures.addCallback(setup, object : FutureCallback { + override fun onSuccess(result: Void?) = Unit + override fun onFailure(t: Throwable) { status.text = "Google Cast 不可用,请检查 Google Play 服务与网络" } + }, ContextCompat.getMainExecutor(this)) + playerView = PlayerView(this) + root.addView(playerView, LinearLayout.LayoutParams(-1, 0, 1f)) + root.addView(Button(this).apply { text = "结束投屏并返回本机"; setOnClickListener { returnToLocal() } }) + setContentView(root) + onBackPressedDispatcher.addCallback(this, object : androidx.activity.OnBackPressedCallback(true) { + override fun handleOnBackPressed() { returnToLocal() } + }) + val token = SessionToken(this, ComponentName(this, GoogleCastService::class.java)) + future = MediaController.Builder(this, token).buildAsync().also { connection -> + Futures.addCallback(connection, object : FutureCallback { + override fun onSuccess(result: MediaController?) { + if (isDestroyed || returning) { result?.release(); return } + controller = result + result ?: return + result.addListener(listener) + playerView.player = result + val uri = intent.getStringExtra("uri") ?: return + if (result.mediaItemCount == 0 || result.currentMediaItem?.localConfiguration?.uri.toString() != uri) { + result.setMediaItem(MediaItem.Builder().setUri(uri).setMimeType(intent.getStringExtra("mime")) + .setMediaMetadata(MediaMetadata.Builder().setTitle(intent.getStringExtra("title")).build()).build(), intent.getLongExtra("position", 0)) + result.prepare(); result.play() + } + listener.onDeviceInfoChanged(result.deviceInfo) + } + override fun onFailure(t: Throwable) { status.text = "Google Cast 服务连接失败;本地来源可返回继续播放" } + }, ContextCompat.getMainExecutor(this)) + } + } + private fun returnToLocal() { + if (returning) return + returning = true + val position = controller?.currentPosition?.coerceAtLeast(0) ?: intent.getLongExtra("position", 0) + val playing = controller?.playWhenReady ?: true + controller?.pause() + MediaRouter.getInstance(this).unselect(MediaRouter.UNSELECT_REASON_STOPPED) + controller?.stop() + setResult(RESULT_OK, Intent().putExtra("position", position).putExtra("playing", playing)) + stopService(Intent(this, GoogleCastService::class.java)) + finish() + } + override fun onDestroy() { + controller?.removeListener(listener); if (::playerView.isInitialized) playerView.player = null + future?.let(MediaController::releaseFuture) + controller = null + super.onDestroy() + } + companion object { + fun intent(context: Context, media: CastMedia) = Intent(context, GoogleCastActivity::class.java) + .putExtra("uri", media.uri).putExtra("mime", media.mimeType).putExtra("title", media.title).putExtra("position", media.startPositionMs) + } +} diff --git a/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastResources.kt b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastResources.kt new file mode 100644 index 0000000..df14c19 --- /dev/null +++ b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastResources.kt @@ -0,0 +1,15 @@ +package com.ttstd.player.cast.google + +import com.ttstd.player.cast.CastProgressObserver + +/** 进程内资源所有权交接。cleanup 只能捕获应用级 relay,不能捕获 Activity/View。 */ +object GoogleCastResources { + var observer: CastProgressObserver? = null + private set + private var cleanup: (() -> Unit)? = null + @Synchronized fun hold(observer: CastProgressObserver?, cleanup: () -> Unit) { + this.cleanup?.invoke() + this.observer = observer; this.cleanup = cleanup + } + @Synchronized fun release() { cleanup?.invoke(); cleanup = null; observer = null } +} diff --git a/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastService.kt b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastService.kt new file mode 100644 index 0000000..5a258f0 --- /dev/null +++ b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastService.kt @@ -0,0 +1,57 @@ +@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +package com.ttstd.player.cast.google + +import androidx.media3.cast.CastPlayer +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.session.MediaSession +import androidx.media3.session.MediaSessionService +import com.ttstd.player.cast.RemotePlaybackState +import kotlinx.coroutines.* + +/** Google Cast 的播放器与 MediaSession 位于服务中,退出 Activity 不会销毁接收端会话。 + * 使用 Media3 CastPlayer 管理本机/接收端转移;没有自行封装旧 RemoteMediaClient。 + */ +class GoogleCastService : MediaSessionService() { + private var mediaSession: MediaSession? = null + private var player: CastPlayer? = null + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private var lastPosition = 0L + override fun onCreate() { + super.onCreate() + val local = ExoPlayer.Builder(this).build() + local.setAudioAttributes(androidx.media3.common.AudioAttributes.DEFAULT, true) + local.setHandleAudioBecomingNoisy(true) + try { + val cast = CastPlayer.Builder(this).setLocalPlayer(local).build() + player = cast + mediaSession = MediaSession.Builder(this, cast).build() + scope.launch { + var started = false + while (isActive) { + if (cast.mediaItemCount > 0) { + lastPosition = cast.currentPosition.coerceAtLeast(0) + try { + if (!started && cast.isPlaying) { GoogleCastResources.observer?.started(lastPosition); started = true } + else if (started) GoogleCastResources.observer?.progress(RemotePlaybackState(lastPosition, cast.duration.takeIf { it >= 0 }, cast.playWhenReady)) + } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { } + } + delay(10_000) + } + } + } catch (_: Exception) { + local.release() + stopSelf() // 无 Google 服务时由控制器连接失败提示,不影响本地播放器。 + } + } + override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = + mediaSession.takeIf { controllerInfo.isTrusted || controllerInfo.packageName == packageName } + override fun onDestroy() { + lastPosition = player?.currentPosition?.coerceAtLeast(0) ?: lastPosition + scope.cancel() + val observer = GoogleCastResources.observer + CoroutineScope(Dispatchers.IO).launch { withTimeoutOrNull(5000) { runCatching { observer?.stopped(lastPosition) } } } + GoogleCastResources.release() + mediaSession?.release(); player?.release(); mediaSession = null; player = null + super.onDestroy() + } +} diff --git a/player-cast-relay/build.gradle.kts b/player-cast-relay/build.gradle.kts new file mode 100644 index 0000000..a8aff25 --- /dev/null +++ b/player-cast-relay/build.gradle.kts @@ -0,0 +1,18 @@ +plugins { id("com.android.library"); kotlin("android") } +android { + namespace = "com.ttstd.player.playercastrelay" + compileSdk = 37 + defaultConfig { minSdk = 23 } + testOptions { unitTests.isIncludeAndroidResources = true } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } +} +kotlin { jvmToolchain(17) } +dependencies { +api(project(":player-cast-api")) +implementation(project(":player-media3-source")) +implementation("org.nanohttpd:nanohttpd:2.3.1") +implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +testImplementation("org.robolectric:robolectric:4.14.1") +testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") +testImplementation("junit:junit:4.13.2") +} diff --git a/player-cast-relay/src/main/AndroidManifest.xml b/player-cast-relay/src/main/AndroidManifest.xml new file mode 100644 index 0000000..fdfe51a --- /dev/null +++ b/player-cast-relay/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/player-cast-relay/src/main/kotlin/com/ttstd/player/cast/relay/CastRelay.kt b/player-cast-relay/src/main/kotlin/com/ttstd/player/cast/relay/CastRelay.kt new file mode 100644 index 0000000..c8e0668 --- /dev/null +++ b/player-cast-relay/src/main/kotlin/com/ttstd/player/cast/relay/CastRelay.kt @@ -0,0 +1,91 @@ +@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +package com.ttstd.player.cast.relay + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.net.Uri +import androidx.media3.common.C +import androidx.media3.datasource.DataSpec +import com.ttstd.player.api.PlaybackRequest +import com.ttstd.player.cast.* +import com.ttstd.player.media3.source.Media3Sources +import fi.iki.elonen.NanoHTTPD +import java.io.InputStream +import java.net.Inet4Address +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + +/** 手机局域网 HTTP 文件代理。token 仅在本次投屏有效,停止后关闭监听并撤销所有链接。 + * 不开放目录,不转发任意 URL 参数;上游地址与凭证只来自宿主注册的请求。 + */ +class CastRelay internal constructor(private val context: Context, private val addressProvider: () -> String?) : AutoCloseable { + constructor(context: Context) : this(context.applicationContext, { lanAddress(context.applicationContext) }) + private data class Entry(val request: PlaybackRequest, val mime: String, val length: Long?) + private val entries = ConcurrentHashMap() + private var server: NanoHTTPD? = null + private var address: String? = null + + @Synchronized fun publish(request: PlaybackRequest, mime: String, contentLength: Long? = null): String { + if (server == null) { + address = addressProvider() ?: throw IllegalStateException("请先连接与电视相同的 Wi-Fi 或以太网") + server = object : NanoHTTPD(0) { + override fun serve(session: IHTTPSession): Response = serveMedia(session) + }.also { it.start(10_000, true) } + } + val token = UUID.randomUUID().toString() + UUID.randomUUID().toString() + entries["/$token"] = Entry(request, mime, contentLength) + return "http://$address:${server!!.listeningPort}/$token" + } + private fun serveMedia(session: NanoHTTPD.IHTTPSession): NanoHTTPD.Response { + val entry = entries[session.uri] ?: return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.NOT_FOUND, "text/plain", "Not found") + if (session.method !in setOf(NanoHTTPD.Method.GET, NanoHTTPD.Method.HEAD)) + return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.METHOD_NOT_ALLOWED, "text/plain", "Method not allowed") + val factory = Media3Sources(context).dataSourceFactory(entry.request) + var length = entry.length + if (length == null) { + val probe = factory.createDataSource() + try { length = probe.open(DataSpec.Builder().setUri(entry.request.uri).setKey(entry.request.cacheKey).build()).takeIf { it >= 0 } } + catch (_: Exception) { return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.SERVICE_UNAVAILABLE, "text/plain", "Upstream unavailable") } + finally { runCatching { probe.close() } } + } + val rangeHeader = session.headers["range"] + val range = if (rangeHeader != null) runCatching { ByteRange.parse(rangeHeader, length ?: -1) }.getOrNull() else null + if (rangeHeader != null && range == null) return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.RANGE_NOT_SATISFIABLE, "text/plain", "Invalid range") + .apply { addHeader("Content-Range", "bytes */${length ?: "*"}") } + val start = range?.start ?: 0 + val count = range?.length ?: length + val status = if (range != null) NanoHTTPD.Response.Status.PARTIAL_CONTENT else NanoHTTPD.Response.Status.OK + val input: InputStream = if (session.method == NanoHTTPD.Method.HEAD) java.io.ByteArrayInputStream(byteArrayOf()) else { + val source = factory.createDataSource() + try { source.open(DataSpec.Builder().setUri(Uri.parse(entry.request.uri)).setPosition(start).setLength(count ?: C.LENGTH_UNSET.toLong()).setKey(entry.request.cacheKey).build()) } + catch (_: Exception) { source.close(); return NanoHTTPD.newFixedLengthResponse(NanoHTTPD.Response.Status.SERVICE_UNAVAILABLE, "text/plain", "Upstream unavailable") } + object : InputStream() { + override fun read(): Int { val b = ByteArray(1); return if (read(b, 0, 1) < 0) -1 else b[0].toInt() and 255 } + override fun read(buffer: ByteArray, offset: Int, size: Int): Int = source.read(buffer, offset, size) + override fun close() { source.close() } + } + } + return (if (count != null) NanoHTTPD.newFixedLengthResponse(status, entry.mime, input, count) + else NanoHTTPD.newChunkedResponse(status, entry.mime, input)).apply { + addHeader("Accept-Ranges", "bytes") + addHeader("Access-Control-Allow-Origin", "*") + addHeader("Cache-Control", "no-store") + if (range != null) addHeader("Content-Range", "bytes ${range.start}-${range.endInclusive}/$length") + } + } + @Synchronized override fun close() { entries.clear(); server?.stop(); server = null; address = null } + + companion object { + /** 只公布 Wi-Fi/以太网地址,不把手机蜂窝地址当作电视可访问地址。 */ + fun lanAddress(context: Context): String? { + val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + return manager.allNetworks.firstNotNullOfOrNull { network -> + val caps = manager.getNetworkCapabilities(network) + if (caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) != true && caps?.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) != true) null + else manager.getLinkProperties(network)?.linkAddresses?.map { it.address } + ?.filterIsInstance()?.firstOrNull { !it.isLoopbackAddress && !it.isLinkLocalAddress }?.hostAddress + } + } + } +} diff --git a/player-cast-relay/src/test/kotlin/com/ttstd/player/cast/relay/CastRelayTest.kt b/player-cast-relay/src/test/kotlin/com/ttstd/player/cast/relay/CastRelayTest.kt new file mode 100644 index 0000000..ff8dbb3 --- /dev/null +++ b/player-cast-relay/src/test/kotlin/com/ttstd/player/cast/relay/CastRelayTest.kt @@ -0,0 +1,33 @@ +@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +package com.ttstd.player.cast.relay + +import androidx.media3.datasource.ByteArrayDataSource +import androidx.media3.datasource.DataSource +import com.ttstd.player.api.PlaybackRequest +import com.ttstd.player.media3.source.Media3TransportRegistry +import okhttp3.OkHttpClient +import okhttp3.Request +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class CastRelayTest { + @Test fun servesRangeAndHeadAndDoesNotExposeUnregisteredPaths() { + Media3TransportRegistry.register("tt-source") { DataSource.Factory { ByteArrayDataSource("0123456789".toByteArray()) } } + CastRelay(RuntimeEnvironment.getApplication()) { "127.0.0.1" }.use { relay -> + val url = relay.publish(PlaybackRequest("tt-source://id/file"), "video/mp4", 10) + val client = OkHttpClient() + client.newCall(Request.Builder().url(url).header("Range", "bytes=2-5").build()).execute().use { + assertEquals(206, it.code); assertEquals("2345", it.body!!.string()); assertEquals("bytes 2-5/10", it.header("Content-Range")) + } + client.newCall(Request.Builder().url(url).head().build()).execute().use { assertEquals("10", it.header("Content-Length")) } + client.newCall(Request.Builder().url(url).header("Range", "bytes=50-").build()).execute().use { assertEquals(416, it.code) } + client.newCall(Request.Builder().url(url.substringBeforeLast('/') + "/wrong-token").build()).execute().use { assertEquals(404, it.code) } + } + } +} diff --git a/player-core/build.gradle.kts b/player-core/build.gradle.kts new file mode 100644 index 0000000..9a21543 --- /dev/null +++ b/player-core/build.gradle.kts @@ -0,0 +1,11 @@ +plugins { + kotlin("jvm") + `java-library` +} + +kotlin { jvmToolchain(17) } + +dependencies { + api(project(":player-api")) + testImplementation("junit:junit:4.13.2") +} diff --git a/player-core/src/main/kotlin/com/ttstd/player/core/HttpHeaders.kt b/player-core/src/main/kotlin/com/ttstd/player/core/HttpHeaders.kt new file mode 100644 index 0000000..0a2fe68 --- /dev/null +++ b/player-core/src/main/kotlin/com/ttstd/player/core/HttpHeaders.kt @@ -0,0 +1,23 @@ +package com.ttstd.player.core + +/** Demo 和框架共用的 HTTP header 规则。错误信息不能包含用户输入的凭证。 */ +object HttpHeaders { + private val fieldName = Regex("[!#$%&'*+.^_`|~0-9A-Za-z-]+") + fun isValid(headers: Map): Boolean = + headers.keys.map { it.lowercase(java.util.Locale.ROOT) }.distinct().size == headers.size && + headers.all { (key, value) -> fieldName.matches(key) && value.none { it == '\r' || it == '\n' || it == '\u0000' } } + + /** 每行 Name: value;在第一个冒号处分隔,允许值内含冒号,拒绝重复字段。 */ + fun parseLines(text: String): Map { + val result = linkedMapOf() + text.lineSequence().filter { it.isNotBlank() }.forEach { line -> + val colon = line.indexOf(':') + require(colon > 0) { "请求头格式应为每行 Name: value" } + val key = line.substring(0, colon).trim() + require(result.keys.none { it.equals(key, ignoreCase = true) }) { "请求头字段不能重复" } + result[key] = line.substring(colon + 1).trim() + } + require(isValid(result)) { "请求头包含非法字段" } + return result + } +} diff --git a/player-core/src/main/kotlin/com/ttstd/player/core/PlaybackValidation.kt b/player-core/src/main/kotlin/com/ttstd/player/core/PlaybackValidation.kt new file mode 100644 index 0000000..a7725f6 --- /dev/null +++ b/player-core/src/main/kotlin/com/ttstd/player/core/PlaybackValidation.kt @@ -0,0 +1,24 @@ +package com.ttstd.player.core + +import com.ttstd.player.api.* +import java.net.URI + +/** 所有内核共用的输入边界;不限制 scheme,content/file/http 等交给平台处理。 */ +object PlaybackValidation { + fun request(request: PlaybackRequest): CommandResult.InvalidArgument? = when { + !absoluteUri(request.uri) -> CommandResult.InvalidArgument("媒体地址必须是绝对 URI") + request.startPositionMs < 0 -> CommandResult.InvalidArgument("起播位置不能为负") + !HttpHeaders.isValid(request.headers) -> + CommandResult.InvalidArgument("请求头包含非法字段") + request.network.connectTimeoutMs !in 1..120_000 || request.network.readTimeoutMs !in 1..120_000 || request.network.rtspTimeoutMs !in 1..120_000 -> + CommandResult.InvalidArgument("网络超时必须在 1–120000 毫秒之间") + request.subtitles.any { !absoluteUri(it.uri) || it.mimeType.isBlank() } -> + CommandResult.InvalidArgument("字幕必须提供绝对 URI 和 MIME 类型") + else -> null + } + fun policy(policy: DecodePolicy, capabilities: PlayerCapabilities): CommandResult.Unsupported? = + if (policy.video !in capabilities.videoDecodeModes || policy.audio !in capabilities.audioDecodeModes) + CommandResult.Unsupported("当前内核不支持该解码策略") else null + + private fun absoluteUri(value: String) = runCatching { URI(value).isAbsolute }.getOrDefault(false) +} diff --git a/player-core/src/main/kotlin/com/ttstd/player/core/SourceRouting.kt b/player-core/src/main/kotlin/com/ttstd/player/core/SourceRouting.kt new file mode 100644 index 0000000..ef18237 --- /dev/null +++ b/player-core/src/main/kotlin/com/ttstd/player/core/SourceRouting.kt @@ -0,0 +1,39 @@ +package com.ttstd.player.core + +import com.ttstd.player.api.* +import java.net.URI +import java.util.Locale + +/** 纯逻辑路由,便于测试。显式类型优先;AUTO 依据 scheme/path,忽略查询参数。 */ +object SourceRouting { + fun resolve(request: PlaybackRequest): MediaSourceType { + if (request.sourceType != MediaSourceType.AUTO) return request.sourceType + val uri = URI(request.uri) + val path = uri.path.orEmpty().lowercase(Locale.ROOT) + return when { + uri.scheme.equals("rtsp", true) -> MediaSourceType.RTSP + uri.scheme.equals("rtmp", true) -> MediaSourceType.RTMP + path.endsWith(".m3u8") -> MediaSourceType.HLS + path.endsWith(".mpd") -> MediaSourceType.DASH + Regex(".*\\.ism[l]?(/manifest.*)?$").matches(path) -> MediaSourceType.SMOOTH_STREAMING + path.endsWith(".flv") -> MediaSourceType.FLV + else -> MediaSourceType.PROGRESSIVE + } + } + + /** 在替换当前媒体之前拒绝未实现的协议,避免误走 HTTP 数据源。 */ + fun validate(request: PlaybackRequest, extraSchemes: Set = emptySet()): CommandResult? { + PlaybackValidation.request(request)?.let { return it } + val scheme = URI(request.uri).scheme.lowercase(Locale.ROOT) + val type = resolve(request) + if (scheme !in setOf("http", "https", "file", "content", "asset", "rawresource", "android.resource", "rtmp", "rtsp") + extraSchemes) + return CommandResult.Unsupported("当前内核未接入该 URI 协议") + if ((type == MediaSourceType.RTSP) != (scheme == "rtsp") || (type == MediaSourceType.RTMP) != (scheme == "rtmp")) + return CommandResult.InvalidArgument("媒体类型与 URI 协议不匹配") + if ((scheme == "rtsp" || scheme == "rtmp") && request.headers.isNotEmpty()) + return CommandResult.Unsupported("HTTP 请求头不能应用到 RTSP/RTMP") + if ((scheme == "rtsp" || scheme == "rtmp") && request.subtitles.isNotEmpty()) + return CommandResult.Unsupported("当前 RTSP/RTMP 适配尚未接入外挂字幕") + return null + } +} diff --git a/player-core/src/test/kotlin/com/ttstd/player/core/PlaybackValidationTest.kt b/player-core/src/test/kotlin/com/ttstd/player/core/PlaybackValidationTest.kt new file mode 100644 index 0000000..9129c5c --- /dev/null +++ b/player-core/src/test/kotlin/com/ttstd/player/core/PlaybackValidationTest.kt @@ -0,0 +1,24 @@ +package com.ttstd.player.core + +import com.ttstd.player.api.* +import org.junit.Assert.* +import org.junit.Test + +class PlaybackValidationTest { + @Test fun rejectsInvalidInputsBeforeLoading() { + assertNotNull(PlaybackValidation.request(PlaybackRequest("relative.mp4"))) + assertNotNull(PlaybackValidation.request(PlaybackRequest("https://example.com/a", startPositionMs = -1))) + assertNotNull(PlaybackValidation.request(PlaybackRequest("https://example.com/a", headers = mapOf("X-Test" to "a\r\nAuthorization: secret")))) + assertNotNull(PlaybackValidation.request(PlaybackRequest("https://example.com/a", subtitles = listOf(ExternalSubtitle("file:///a.srt", ""))))) + } + @Test fun acceptsLocalContentAndNetworkSources() { + listOf("file:///sdcard/a.mp4", "content://media/external/video/1", "https://example.com/a.m3u8").forEach { + assertNull(PlaybackValidation.request(PlaybackRequest(it))) + } + } + @Test fun doesNotSilentlyAcceptUnsupportedDecoderPolicy() { + val capabilities = PlayerCapabilities("fake", setOf(DecodeMode.AUTO), setOf(DecodeMode.AUTO)) + assertNull(PlaybackValidation.policy(DecodePolicy(), capabilities)) + assertNotNull(PlaybackValidation.policy(DecodePolicy(video = DecodeMode.SOFTWARE_ONLY), capabilities)) + } +} diff --git a/player-core/src/test/kotlin/com/ttstd/player/core/SourceRoutingTest.kt b/player-core/src/test/kotlin/com/ttstd/player/core/SourceRoutingTest.kt new file mode 100644 index 0000000..48796a8 --- /dev/null +++ b/player-core/src/test/kotlin/com/ttstd/player/core/SourceRoutingTest.kt @@ -0,0 +1,42 @@ +package com.ttstd.player.core + +import com.ttstd.player.api.* +import org.junit.Assert.* +import org.junit.Test + +class SourceRoutingTest { + @Test fun infersManifestTypeWithoutLookingAtQueryString() { + mapOf( + "https://host/live.M3U8?token=x" to MediaSourceType.HLS, + "https://host/live.mpd?a=.m3u8" to MediaSourceType.DASH, + "https://host/live.ism/Manifest" to MediaSourceType.SMOOTH_STREAMING, + "https://host/live.flv?token=x" to MediaSourceType.FLV, + "rtsp://host/live" to MediaSourceType.RTSP, + "rtmp://host/app/stream" to MediaSourceType.RTMP, + ).forEach { (uri, type) -> assertEquals(type, SourceRouting.resolve(PlaybackRequest(uri))) } + } + @Test fun explicitTypeHandlesGatewayAddressesAndOverridesExtension() { + assertEquals(MediaSourceType.HLS, SourceRouting.resolve(PlaybackRequest("https://host/play?id=1", sourceType = MediaSourceType.HLS))) + assertEquals(MediaSourceType.PROGRESSIVE, SourceRouting.resolve(PlaybackRequest("https://host/file.m3u8", sourceType = MediaSourceType.PROGRESSIVE))) + } + @Test fun rejectsUnimplementedProtocolsAndTypeMismatches() { + listOf("srt://host:9000", "rist://host:9000", "webrtc://host/live", "rtmps://host/live").forEach { + assertTrue(SourceRouting.validate(PlaybackRequest(it)) is CommandResult.Unsupported) + } + assertTrue(SourceRouting.validate(PlaybackRequest("rtsp://host/live", sourceType = MediaSourceType.HLS)) is CommandResult.InvalidArgument) + assertTrue(SourceRouting.validate(PlaybackRequest("https://host/live", sourceType = MediaSourceType.RTMP)) is CommandResult.InvalidArgument) + } + @Test fun rejectsIgnoredHeadersAndOutOfRangeTimeouts() { + assertTrue(SourceRouting.validate(PlaybackRequest("rtsp://host/live", headers = mapOf("Authorization" to "secret"))) is CommandResult.Unsupported) + assertTrue(SourceRouting.validate(PlaybackRequest("rtmp://host/live", subtitles = listOf(ExternalSubtitle("https://host/a.srt", "application/x-subrip")))) is CommandResult.Unsupported) + assertNotNull(PlaybackValidation.request(PlaybackRequest("https://host/live", network = NetworkOptions(connectTimeoutMs = 0)))) + assertNotNull(PlaybackValidation.request(PlaybackRequest("https://host/live", network = NetworkOptions(rtspTimeoutMs = 120_001)))) + } + @Test fun headerParserPreservesColonsAndRejectsDuplicates() { + assertEquals(mapOf("Referer" to "https://host:8443/a", "Authorization" to "Bearer abc"), HttpHeaders.parseLines("Referer: https://host:8443/a\nAuthorization: Bearer abc\n")) + listOf("Bad Name: x", "Authorization: a\nauthorization: b", "no-colon").forEach { + assertTrue(runCatching { HttpHeaders.parseLines(it) }.isFailure) + } + assertFalse(HttpHeaders.isValid(mapOf("X" to "a\r\nb"))) + } +} diff --git a/player-lifecycle/build.gradle.kts b/player-lifecycle/build.gradle.kts new file mode 100644 index 0000000..03108c5 --- /dev/null +++ b/player-lifecycle/build.gradle.kts @@ -0,0 +1,30 @@ +plugins { + id("com.android.library") + kotlin("android") +} + +android { + namespace = "com.ttstd.player.lifecycle" + compileSdk = 37 + + defaultConfig { + minSdk = 23 + } + + testOptions { unitTests.isIncludeAndroidResources = true } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} + +kotlin { jvmToolchain(17) } + +dependencies { + testImplementation("junit:junit:4.13.2") + testImplementation("org.robolectric:robolectric:4.14.1") + testImplementation(project(":player-media3")) + api(project(":player-api")) + api("androidx.lifecycle:lifecycle-runtime-ktx:2.9.1") +} diff --git a/player-lifecycle/src/main/AndroidManifest.xml b/player-lifecycle/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/player-lifecycle/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/player-lifecycle/src/main/kotlin/com/ttstd/player/lifecycle/PlaybackLifecycleBinding.kt b/player-lifecycle/src/main/kotlin/com/ttstd/player/lifecycle/PlaybackLifecycleBinding.kt new file mode 100644 index 0000000..1f2a648 --- /dev/null +++ b/player-lifecycle/src/main/kotlin/com/ttstd/player/lifecycle/PlaybackLifecycleBinding.kt @@ -0,0 +1,48 @@ +package com.ttstd.player.lifecycle + +import androidx.lifecycle.DefaultLifecycleObserver +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.lifecycleScope +import com.ttstd.player.api.PlayerEngine +import kotlinx.coroutines.launch + +/** 页面播放策略:STOP 时暂停,START 时仅恢复本绑定暂停的播放。 + * 必须主线程创建/关闭,owner 不能已销毁。用户操作应经 playByUser/pauseByUser, + * 使后台手动暂停能够撤销自动恢复。后台播放服务不应使用此绑定。 + * release 在 ON_DESTROY 使用独立、短生命周期协程,避免 lifecycleScope 已取消导致泄漏。 + */ +class PlaybackLifecycleBinding( + private val owner: LifecycleOwner, + private val engine: PlayerEngine, + private val releaseOnDestroy: Boolean = true, +) : DefaultLifecycleObserver, AutoCloseable { + private var resumeOnStart = false + init { + require(owner.lifecycle.currentState != androidx.lifecycle.Lifecycle.State.DESTROYED) + owner.lifecycle.addObserver(this) + } + override fun onStop(owner: LifecycleOwner) { + resumeOnStart = engine.state.value.playWhenReady + owner.lifecycleScope.launch { engine.pause() } + } + override fun onStart(owner: LifecycleOwner) { + if (resumeOnStart) { + resumeOnStart = false + owner.lifecycleScope.launch { engine.play() } + } + } + /** 前台调用;后台播放意图延迟到下一次 START。 */ + suspend fun playByUser() = if (owner.lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) engine.play() + else { resumeOnStart = true; com.ttstd.player.api.CommandResult.Accepted } + suspend fun pauseByUser(): com.ttstd.player.api.CommandResult { + resumeOnStart = false + return engine.pause() + } + override fun onDestroy(owner: LifecycleOwner) { + close() + if (releaseOnDestroy) kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main.immediate) + .launch(start = kotlinx.coroutines.CoroutineStart.UNDISPATCHED) { engine.release() } + } + /** 只解除生命周期绑定,不转移或释放播放器所有权。 */ + override fun close() { owner.lifecycle.removeObserver(this); resumeOnStart = false } +} diff --git a/player-lifecycle/src/test/kotlin/com/ttstd/player/lifecycle/PlaybackLifecycleBindingTest.kt b/player-lifecycle/src/test/kotlin/com/ttstd/player/lifecycle/PlaybackLifecycleBindingTest.kt new file mode 100644 index 0000000..00c1c87 --- /dev/null +++ b/player-lifecycle/src/test/kotlin/com/ttstd/player/lifecycle/PlaybackLifecycleBindingTest.kt @@ -0,0 +1,55 @@ +package com.ttstd.player.lifecycle + +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import com.ttstd.player.api.PlaybackPhase +import com.ttstd.player.media3.Media3Engine +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class PlaybackLifecycleBindingTest { + private class Owner : LifecycleOwner { + val registry = LifecycleRegistry(this) + override val lifecycle: Lifecycle get() = registry + } + @Test fun stopAndStartRestoresOnlyLifecyclePause() = runBlocking { + val owner = Owner() + val engine = Media3Engine(RuntimeEnvironment.getApplication()) + val binding = PlaybackLifecycleBinding(owner, engine) + owner.registry.currentState = Lifecycle.State.STARTED + binding.playByUser() + owner.registry.currentState = Lifecycle.State.CREATED + assertFalse(engine.state.value.playWhenReady) + owner.registry.currentState = Lifecycle.State.STARTED + assertTrue(engine.state.value.playWhenReady) + binding.pauseByUser() + owner.registry.currentState = Lifecycle.State.CREATED + owner.registry.currentState = Lifecycle.State.STARTED + assertFalse(engine.state.value.playWhenReady) + owner.registry.currentState = Lifecycle.State.DESTROYED + assertEquals(PlaybackPhase.RELEASED, engine.state.value.phase) + } + @Test fun manualBackgroundPauseCancelsResumeAndExternalOwnershipSurvivesDestroy() = runBlocking { + val owner = Owner() + val engine = Media3Engine(RuntimeEnvironment.getApplication()) + val binding = PlaybackLifecycleBinding(owner, engine, releaseOnDestroy = false) + try { + owner.registry.currentState = Lifecycle.State.STARTED + binding.playByUser() + owner.registry.currentState = Lifecycle.State.CREATED + binding.pauseByUser() + owner.registry.currentState = Lifecycle.State.STARTED + assertFalse(engine.state.value.playWhenReady) + owner.registry.currentState = Lifecycle.State.DESTROYED + assertNotEquals(PlaybackPhase.RELEASED, engine.state.value.phase) + } finally { binding.close(); engine.release() } + } +} diff --git a/player-media3-source/build.gradle.kts b/player-media3-source/build.gradle.kts new file mode 100644 index 0000000..3f03bef --- /dev/null +++ b/player-media3-source/build.gradle.kts @@ -0,0 +1,32 @@ +plugins { + id("com.android.library") + kotlin("android") +} + +android { + namespace = "com.ttstd.player.media3.source" + compileSdk = 37 + defaultConfig { minSdk = 23 } + testOptions { unitTests.isIncludeAndroidResources = true } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} +kotlin { jvmToolchain(17) } + +dependencies { + implementation(project(":player-core")) + api("androidx.media3:media3-exoplayer:1.11.1") + implementation("androidx.media3:media3-exoplayer-hls:1.11.1") + implementation("androidx.media3:media3-exoplayer-dash:1.11.1") + implementation("androidx.media3:media3-exoplayer-rtsp:1.11.1") + implementation("androidx.media3:media3-exoplayer-smoothstreaming:1.11.1") + implementation("androidx.media3:media3-datasource-rtmp:1.11.1") { + exclude(group = "io.antmedia", module = "rtmp-client") + } + implementation(project(":player-rtmp-native")) + testImplementation("junit:junit:4.13.2") + testImplementation("org.robolectric:robolectric:4.14.1") + testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") +} diff --git a/player-media3-source/src/main/AndroidManifest.xml b/player-media3-source/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/player-media3-source/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/player-media3-source/src/main/kotlin/com/ttstd/player/media3/source/Media3Sources.kt b/player-media3-source/src/main/kotlin/com/ttstd/player/media3/source/Media3Sources.kt new file mode 100644 index 0000000..8ea374d --- /dev/null +++ b/player-media3-source/src/main/kotlin/com/ttstd/player/media3/source/Media3Sources.kt @@ -0,0 +1,91 @@ +@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) + +package com.ttstd.player.media3.source + +import android.content.Context +import android.net.Uri +import androidx.media3.common.MediaItem +import androidx.media3.common.MimeTypes +import androidx.media3.datasource.DataSource +import androidx.media3.datasource.DefaultDataSource +import androidx.media3.datasource.DefaultHttpDataSource +import androidx.media3.datasource.cache.CacheDataSource +import androidx.media3.datasource.rtmp.RtmpDataSource +import androidx.media3.exoplayer.rtsp.RtspMediaSource +import androidx.media3.exoplayer.source.DefaultMediaSourceFactory +import androidx.media3.exoplayer.source.MediaSource +import androidx.media3.exoplayer.source.ProgressiveMediaSource +import androidx.media3.extractor.flv.FlvExtractor +import com.ttstd.player.api.* +import com.ttstd.player.core.SourceRouting + +/** 协议适配集中在本 module,内核只消费 MediaSource。 + * 每次构造独立 HTTP 工厂,防止不同媒体间串用 Authorization/Cookie。 + * 不启用跨协议重定向,不打印 RTSP 报文和 URI 凭证。 + */ +class Media3Sources(context: Context) { + private val context = context.applicationContext + + fun create(request: PlaybackRequest): MediaSource { + require(SourceRouting.validate(request, Media3TransportRegistry.schemes()) == null) { "无效或不支持的媒体请求" } + val type = SourceRouting.resolve(request) + val mime = when (type) { + MediaSourceType.HLS -> MimeTypes.APPLICATION_M3U8 + MediaSourceType.DASH -> MimeTypes.APPLICATION_MPD + MediaSourceType.SMOOTH_STREAMING -> MimeTypes.APPLICATION_SS + MediaSourceType.FLV, MediaSourceType.RTMP -> MimeTypes.VIDEO_FLV + else -> null + } + val item = MediaItem.Builder().setUri(request.uri).setMimeType(mime) + .setCustomCacheKey(request.cacheKey.takeIf { type == MediaSourceType.PROGRESSIVE }) + .setSubtitleConfigurations(request.subtitles.map { + MediaItem.SubtitleConfiguration.Builder(Uri.parse(it.uri)) + .setMimeType(it.mimeType).setLanguage(it.language) + .setSelectionFlags(if (it.isDefault) androidx.media3.common.C.SELECTION_FLAG_DEFAULT else 0).build() + }).build() + return when (type) { + MediaSourceType.RTSP -> RtspMediaSource.Factory() + .setForceUseRtpTcp(request.network.rtspTransport == RtspTransport.TCP) + .setTimeoutMs(request.network.rtspTimeoutMs) + .createMediaSource(item) + MediaSourceType.RTMP -> ProgressiveMediaSource.Factory(RtmpDataSource.Factory(), FlvExtractor.FACTORY) + .createMediaSource(item) + // FLV 指定 MIME 后走 progressive,保留 DefaultMediaSourceFactory 的外挂字幕处理。 + else -> DefaultMediaSourceFactory(dataSourceFactory(request)).createMediaSource(item) + } + } + + /** 仅 HTTP(S) 使用请求头和连接/读取超时;RTSP 使用独立配置,RTMP 由 native 库管理。 */ + fun dataSourceFactory(request: PlaybackRequest): DataSource.Factory { + val http = DefaultHttpDataSource.Factory() + .setConnectTimeoutMs(request.network.connectTimeoutMs) + .setReadTimeoutMs(request.network.readTimeoutMs) + .setDefaultRequestProperties(request.headers.toMap()) + val defaultFactory = DefaultDataSource.Factory(context, http) + val upstream = DataSource.Factory { + // 外挂字幕也按它自身 URI 路由,不能复用主文件的 SMB handle。 + object : DataSource { + private var delegate: DataSource? = null + private val listeners = mutableListOf() + override fun addTransferListener(listener: androidx.media3.datasource.TransferListener) { listeners += listener; delegate?.addTransferListener(listener) } + override fun open(spec: androidx.media3.datasource.DataSpec): Long { + val factory = Media3TransportRegistry.factory(spec.uri.scheme, request) ?: defaultFactory + val source = factory.createDataSource() + delegate = source + listeners.forEach(source::addTransferListener) + return source.open(spec) + } + override fun read(buffer: ByteArray, offset: Int, length: Int) = delegate!!.read(buffer, offset, length) + override fun getUri() = delegate?.uri + override fun getResponseHeaders(): Map> = delegate?.responseHeaders ?: emptyMap() + override fun close() { try { delegate?.close() } finally { delegate = null } } + } + } + val type = SourceRouting.resolve(request) + val cache = Media3FileCache.current() + return if (request.cacheKey != null && type == MediaSourceType.PROGRESSIVE && cache != null) + CacheDataSource.Factory().setCache(cache).setUpstreamDataSourceFactory(upstream) + .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR) + else upstream + } +} diff --git a/player-media3-source/src/main/kotlin/com/ttstd/player/media3/source/Media3TransportRegistry.kt b/player-media3-source/src/main/kotlin/com/ttstd/player/media3/source/Media3TransportRegistry.kt new file mode 100644 index 0000000..ec31160 --- /dev/null +++ b/player-media3-source/src/main/kotlin/com/ttstd/player/media3/source/Media3TransportRegistry.kt @@ -0,0 +1,32 @@ +@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +package com.ttstd.player.media3.source + +import android.content.Context +import androidx.media3.datasource.DataSource +import androidx.media3.datasource.cache.* +import androidx.media3.database.StandaloneDatabaseProvider +import com.ttstd.player.api.PlaybackRequest +import java.util.concurrent.ConcurrentHashMap + +/** 进程内传输插件注册。只由宿主初始化,不能根据不受信任的媒体内容自动注册。 */ +object Media3TransportRegistry { + private val factories = ConcurrentHashMap DataSource.Factory>() + fun register(scheme: String, factory: (PlaybackRequest) -> DataSource.Factory) { factories[scheme.lowercase()] = factory } + fun schemes(): Set = factories.keys.toSet() + internal fun factory(scheme: String?, request: PlaybackRequest) = factories[scheme?.lowercase()]?.invoke(request) +} + +/** 整个进程只允许一个 SimpleCache 持有目录锁;LRU 上限默认 256 MB。 + * 生命周期为应用进程,不跟随 Activity 释放。仅普通文件使用,HLS/DASH 不共享一个文件 key。 + */ +object Media3FileCache { + private var cache: SimpleCache? = null + @Synchronized fun get(context: Context): SimpleCache = cache ?: SimpleCache( + java.io.File(context.applicationContext.cacheDir, "video-blocks"), + LeastRecentlyUsedCacheEvictor(256L * 1024 * 1024), StandaloneDatabaseProvider(context.applicationContext) + ).also { cache = it } + @Synchronized fun bytes(): Long = cache?.cacheSpace ?: 0 + @Synchronized fun current(): SimpleCache? = cache + /** 先停止所有播放/投屏,再清理,避免与正在写入的 span 竞争。 */ + @Synchronized fun clear() { cache?.keys?.toList()?.forEach { cache?.removeResource(it) } } +} diff --git a/player-media3-source/src/test/kotlin/com/ttstd/player/media3/source/Media3FileCacheTest.kt b/player-media3-source/src/test/kotlin/com/ttstd/player/media3/source/Media3FileCacheTest.kt new file mode 100644 index 0000000..6fdae90 --- /dev/null +++ b/player-media3-source/src/test/kotlin/com/ttstd/player/media3/source/Media3FileCacheTest.kt @@ -0,0 +1,43 @@ +@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +package com.ttstd.player.media3.source + +import android.net.Uri +import androidx.media3.datasource.DataSpec +import com.ttstd.player.api.PlaybackRequest +import okhttp3.mockwebserver.* +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.SQLiteMode + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +@SQLiteMode(SQLiteMode.Mode.LEGACY) +class Media3FileCacheTest { + @Test fun readsPreviouslyCachedByteRangeWithoutNetwork() { + val context = RuntimeEnvironment.getApplication() + Media3FileCache.get(context) + val server = MockWebServer() + server.enqueue(MockResponse().setBody("0123456789")); server.start() + val request = PlaybackRequest(server.url("/movie.mp4").toString(), cacheKey = "source:movie:v1") + val factory = Media3Sources(context).dataSourceFactory(request) + fun read(position: Long, length: Long): String { + val source = factory.createDataSource() + try { + source.open(DataSpec.Builder().setUri(Uri.parse(request.uri)).setPosition(position).setLength(length).setKey(request.cacheKey).build()) + val output = java.io.ByteArrayOutputStream() + val buffer = ByteArray(32) + while (true) { val count = source.read(buffer, 0, buffer.size); if (count < 0) break; output.write(buffer, 0, count) } + return output.toString("UTF-8") + } finally { source.close() } + } + assertEquals("0123456789", read(0, 10)) + assertEquals(1, server.requestCount) + server.shutdown() + assertEquals("3456", read(3, 4)) + assertTrue(Media3FileCache.bytes() >= 10) + } +} diff --git a/player-media3-source/src/test/kotlin/com/ttstd/player/media3/source/Media3SourcesTest.kt b/player-media3-source/src/test/kotlin/com/ttstd/player/media3/source/Media3SourcesTest.kt new file mode 100644 index 0000000..8b73a0e --- /dev/null +++ b/player-media3-source/src/test/kotlin/com/ttstd/player/media3/source/Media3SourcesTest.kt @@ -0,0 +1,94 @@ +@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) + +package com.ttstd.player.media3.source + +import android.net.Uri +import androidx.media3.common.MimeTypes +import androidx.media3.common.C +import androidx.media3.datasource.DataSpec +import androidx.media3.extractor.DefaultExtractorInput +import androidx.media3.extractor.flv.FlvExtractor +import com.ttstd.player.api.* +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okio.Buffer +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.util.concurrent.TimeUnit + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class Media3SourcesTest { + private fun sources() = Media3Sources(RuntimeEnvironment.getApplication()) + + @Test fun automaticHlsNeverReceivesProgressiveCacheKey() { + val source = sources().create(PlaybackRequest("https://host/live.m3u8", cacheKey = "stable-id")) + assertEquals("HlsMediaSource", source.javaClass.simpleName) + assertNull(source.mediaItem.localConfiguration!!.customCacheKey) + val file = sources().create(PlaybackRequest("https://host/movie.mp4", cacheKey = "stable-id", + subtitles = listOf(ExternalSubtitle("https://host/movie.srt", "application/x-subrip", isDefault = true)))) + assertEquals("stable-id", file.mediaItem.localConfiguration!!.customCacheKey) + assertEquals(C.SELECTION_FLAG_DEFAULT, file.mediaItem.localConfiguration!!.subtitleConfigurations.single().selectionFlags) + } + + @Test fun createsManifestSourcesForExtensionlessAddresses() { + listOf( + Triple(MediaSourceType.HLS, "HlsMediaSource", MimeTypes.APPLICATION_M3U8), + Triple(MediaSourceType.DASH, "DashMediaSource", MimeTypes.APPLICATION_MPD), + Triple(MediaSourceType.SMOOTH_STREAMING, "SsMediaSource", MimeTypes.APPLICATION_SS), + Triple(MediaSourceType.FLV, "ProgressiveMediaSource", MimeTypes.VIDEO_FLV), + ).forEach { (type, className, mime) -> + val source = sources().create(PlaybackRequest("https://host/gateway?id=1", sourceType = type)) + assertEquals(className, source.javaClass.simpleName) + assertEquals(mime, source.mediaItem.localConfiguration!!.mimeType) + } + } + @Test fun createsRtspAndRtmpSourcesWithoutOpeningNetwork() { + val rtsp = sources().create(PlaybackRequest("rtsp://host/live", network = NetworkOptions(rtspTransport = RtspTransport.TCP))) + assertEquals("RtspMediaSource", rtsp.javaClass.simpleName) + val rtmp = sources().create(PlaybackRequest("rtmp://host/app/live")) + assertEquals("ProgressiveMediaSource", rtmp.javaClass.simpleName) + assertEquals(MimeTypes.VIDEO_FLV, rtmp.mediaItem.localConfiguration!!.mimeType) + } + @Test fun httpHeadersReachServerAndDoNotLeakIntoNextRequest() { + MockWebServer().use { server -> + server.enqueue(MockResponse().setBody("abc")) + server.enqueue(MockResponse().setBody("xyz")) + server.start() + val factory = sources() + listOf(mapOf("Authorization" to "Bearer test", "Referer" to "https://example.test"), emptyMap()).forEach { headers -> + val uri = server.url("/stream").toString() + val source = factory.dataSourceFactory(PlaybackRequest(uri, headers = headers)).createDataSource() + try { + source.open(DataSpec(Uri.parse(uri))) + val bytes = ByteArray(3) + assertTrue(source.read(bytes, 0, bytes.size) > 0) + } finally { source.close() } + } + val first = server.takeRequest(3, TimeUnit.SECONDS)!! + assertEquals("Bearer test", first.getHeader("Authorization")) + assertEquals("https://example.test", first.getHeader("Referer")) + val second = server.takeRequest(3, TimeUnit.SECONDS)!! + assertNull(second.getHeader("Authorization")) + assertNull(second.getHeader("Referer")) + } + } + @Test fun recognizesChunkedHttpFlvWithoutContentLength() { + val fixture = javaClass.getResourceAsStream("/sample.flv")!!.use { it.readBytes() } + MockWebServer().use { server -> + server.enqueue(MockResponse().setHeader("Content-Type", "video/x-flv") + .setChunkedBody(Buffer().write(fixture), 32)) + server.start() + val uri = server.url("/live.flv").toString() + val source = sources().dataSourceFactory(PlaybackRequest(uri)).createDataSource() + try { + assertEquals(C.LENGTH_UNSET.toLong(), source.open(DataSpec(Uri.parse(uri)))) + assertTrue(FlvExtractor().sniff(DefaultExtractorInput(source, 0, C.LENGTH_UNSET.toLong()))) + } finally { source.close() } + } + } +} diff --git a/player-media3-source/src/test/resources/sample.flv b/player-media3-source/src/test/resources/sample.flv new file mode 100644 index 0000000..c0cdafe Binary files /dev/null and b/player-media3-source/src/test/resources/sample.flv differ diff --git a/player-media3/build.gradle.kts b/player-media3/build.gradle.kts new file mode 100644 index 0000000..9af1ba9 --- /dev/null +++ b/player-media3/build.gradle.kts @@ -0,0 +1,32 @@ +plugins { + id("com.android.library") + kotlin("android") +} + +android { + namespace = "com.ttstd.player.media3" + compileSdk = 37 + + defaultConfig { + minSdk = 23 + } + + testOptions { unitTests.isIncludeAndroidResources = true } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} + +kotlin { jvmToolchain(17) } + +dependencies { + testImplementation("junit:junit:4.13.2") + testImplementation("org.robolectric:robolectric:4.14.1") + api(project(":player-android-api")) + implementation(project(":player-core")) + implementation(project(":player-media3-source")) + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") + implementation("androidx.media3:media3-exoplayer:1.11.1") +} diff --git a/player-media3/src/main/AndroidManifest.xml b/player-media3/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/player-media3/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/player-media3/src/main/kotlin/com/ttstd/player/media3/Media3Engine.kt b/player-media3/src/main/kotlin/com/ttstd/player/media3/Media3Engine.kt new file mode 100644 index 0000000..1c59e99 --- /dev/null +++ b/player-media3/src/main/kotlin/com/ttstd/player/media3/Media3Engine.kt @@ -0,0 +1,265 @@ +@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) + +package com.ttstd.player.media3 + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.view.Surface +import androidx.media3.common.* +import androidx.media3.exoplayer.DefaultRenderersFactory +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.exoplayer.analytics.AnalyticsListener +import androidx.media3.exoplayer.mediacodec.MediaCodecSelector +import com.ttstd.player.api.* +import com.ttstd.player.android.AndroidVideoOutput +import com.ttstd.player.core.PlaybackValidation +import com.ttstd.player.core.SourceRouting +import com.ttstd.player.media3.source.Media3Sources +import com.ttstd.player.media3.source.Media3TransportRegistry +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.flow.* +import kotlinx.coroutines.withContext + +/** Android 主线程创建;命令自动切回主线程串行执行。 + * 仅持有 Application Context。位置每秒采样,避免低端机频繁唤醒。 + * 不集成通用 FFmpeg 视频软解;强制软解仅筛选系统已提供的软件 MediaCodec。 + */ +class Media3Engine(context: Context) : PlayerEngine, AndroidVideoOutput { + private val context = context.applicationContext + private val mutableState = MutableStateFlow(PlaybackState()) + private val mutableEvents = MutableSharedFlow(extraBufferCapacity = 64, onBufferOverflow = BufferOverflow.DROP_OLDEST) + override val state = mutableState.asStateFlow() + override val events = mutableEvents.asSharedFlow() + override val capabilities = PlayerCapabilities("Media3", DecodeMode.entries.toSet(), DecodeMode.entries.toSet(), sourceTypes = MediaSourceType.entries.toSet()) + private val handler = Handler(Looper.getMainLooper()) + private var released = false + private var request: PlaybackRequest? = null + private var policy = DecodePolicy() + private var surface: Surface? = null + private var startedAt = 0L + private var firstFrame = false + private var lastError: PlaybackError? = null + private var subtitleLines: List = emptyList() + private var player: ExoPlayer + + private val listener = object : Player.Listener { + override fun onEvents(player: Player, events: Player.Events) { + publish() + handler.removeCallbacks(ticker) + if (player.isPlaying) handler.postDelayed(ticker, 1000) + } + override fun onPlaybackStateChanged(playbackState: Int) { + if (playbackState == Player.STATE_ENDED) emit(PlaybackEvent.Ended) + } + override fun onPlayerError(error: PlaybackException) { + // 不透传内核 message/cause:其中可能包含带 token 的媒体地址。 + val message = when (error.errorCode) { + PlaybackException.ERROR_CODE_DECODER_INIT_FAILED, PlaybackException.ERROR_CODE_DECODING_FAILED, + PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED, PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES -> + "设备无法解码此视频,可更换解码方式或使用媒体服务转码" + PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS, PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED, + PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT -> "媒体连接失败,请检查网络或重新打开来源" + else -> "播放失败,请检查媒体、来源和设备解码能力" + } + lastError = PlaybackError(error.errorCodeName, message) + emit(PlaybackEvent.Error(lastError!!)) + publish() + } + override fun onVideoSizeChanged(size: VideoSize) { + emit(PlaybackEvent.VideoSize(size.width, size.height, size.pixelWidthHeightRatio)) + } + override fun onCues(cueGroup: androidx.media3.common.text.CueGroup) { + subtitleLines = cueGroup.cues.mapNotNull { it.text?.toString() } + publish() + } + } + private val analytics = object : AnalyticsListener { + override fun onRenderedFirstFrame(eventTime: AnalyticsListener.EventTime, output: Any, renderTimeMs: Long) { + if (!firstFrame) { + firstFrame = true + emit(PlaybackEvent.FirstFrame) + emit(PlaybackEvent.StartupTime(SystemClock.elapsedRealtime() - startedAt)) + } + } + override fun onVideoDecoderInitialized(eventTime: AnalyticsListener.EventTime, decoderName: String, initializedTimestampMs: Long, initializationDurationMs: Long) { + decoder(TrackType.VIDEO, decoderName) + } + override fun onAudioDecoderInitialized(eventTime: AnalyticsListener.EventTime, decoderName: String, initializedTimestampMs: Long, initializationDurationMs: Long) { + decoder(TrackType.AUDIO, decoderName) + } + override fun onDroppedVideoFrames(eventTime: AnalyticsListener.EventTime, droppedFrames: Int, elapsedMs: Long) { + emit(PlaybackEvent.DroppedFrames(droppedFrames, elapsedMs)) + } + } + + private val ticker: Runnable = object : Runnable { + override fun run() { + if (!released && player.isPlaying) { publish(); handler.postDelayed(this, 1000) } + } + } + + init { + checkMain() + player = buildPlayer() + } + + private fun buildPlayer(): ExoPlayer { + val selector = MediaCodecSelector { mime, secure, tunneling -> + val mode = if (mime.startsWith("video/")) policy.video else policy.audio + val codecs = MediaCodecSelector.DEFAULT.getDecoderInfos(mime, secure, tunneling) + when (mode) { + DecodeMode.AUTO -> codecs + DecodeMode.PREFER_HARDWARE -> codecs.sortedByDescending { it.hardwareAccelerated } + DecodeMode.HARDWARE_ONLY -> codecs.filter { it.hardwareAccelerated } + DecodeMode.SOFTWARE_ONLY -> codecs.filter { it.softwareOnly } + } + } + // fallback 仅处理可用解码器初始化回退,不承诺运行中错误自动软解。 + val renderers = DefaultRenderersFactory(context).setMediaCodecSelector(selector).setEnableDecoderFallback(true) + return ExoPlayer.Builder(context, renderers).build().also { + it.setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(), true) + it.setHandleAudioBecomingNoisy(true) + it.addListener(listener) + it.addAnalyticsListener(analytics) + } + } + + override suspend fun prepare(request: PlaybackRequest) = command { + SourceRouting.validate(request, Media3TransportRegistry.schemes())?.let { return@command it } + this.request = request.copy(headers = request.headers.toMap(), subtitles = request.subtitles.toList()) + load(this.request!!) + CommandResult.Accepted + } + + private fun load(request: PlaybackRequest) { + subtitleLines = emptyList() + lastError = null + firstFrame = false + startedAt = SystemClock.elapsedRealtime() + player.setMediaSource(Media3Sources(context).create(request), request.startPositionMs) + player.playWhenReady = request.autoplay + player.prepare() + } + + override suspend fun play() = command { player.play(); CommandResult.Accepted } + override suspend fun pause() = command { player.pause(); CommandResult.Accepted } + override suspend fun seekTo(positionMs: Long) = command { + if (positionMs < 0) CommandResult.InvalidArgument("位置不能为负") + else if (!player.isCurrentMediaItemSeekable) CommandResult.Unsupported("当前媒体不可 seek") + else { player.seekTo(positionMs); CommandResult.Accepted } + } + override suspend fun setSpeed(speed: Float) = command { + if (!speed.isFinite() || speed !in 0.25f..4f) CommandResult.InvalidArgument("倍速范围为 0.25–4") + else { player.setPlaybackSpeed(speed); CommandResult.Accepted } + } + override suspend fun setVolume(volume: Float) = command { + if (!volume.isFinite() || volume !in 0f..1f) CommandResult.InvalidArgument("音量范围为 0–1") + else { player.volume = volume; CommandResult.Accepted } + } + override suspend fun selectTrack(selection: TrackSelection) = command { + val type = selection.type.media3Type() + val builder = player.trackSelectionParameters.buildUpon().clearOverridesOfType(type).setTrackTypeDisabled(type, selection.disabled) + if (!selection.disabled && selection.id != null) { + val target = player.currentTracks.groups.withIndex().firstNotNullOfOrNull { (groupIndex, group) -> + (0 until group.length).firstOrNull { "$groupIndex:$it" == selection.id && group.type == type && group.isTrackSupported(it) } + ?.let { TrackSelectionOverride(group.mediaTrackGroup, listOf(it)) } + } ?: return@command CommandResult.InvalidArgument("轨道不存在或设备不支持") + builder.setOverrideForType(target) + } + player.trackSelectionParameters = builder.build() + CommandResult.Accepted + } + override suspend fun setDecodePolicy(policy: DecodePolicy) = command { + PlaybackValidation.policy(policy, capabilities)?.let { return@command it } + if (this.policy == policy) return@command CommandResult.Accepted + val saved = request?.copy(startPositionMs = player.currentPosition.coerceAtLeast(0), autoplay = player.playWhenReady) + val speed = player.playbackParameters.speed + val playWhenReady = player.playWhenReady + val volume = player.volume + val tracks = player.trackSelectionParameters + this.policy = policy + player.removeListener(listener) + player.removeAnalyticsListener(analytics) + player.release() + player = buildPlayer() + player.setPlaybackSpeed(speed) + player.volume = volume + player.playWhenReady = playWhenReady + player.trackSelectionParameters = tracks + surface?.takeIf { it.isValid }?.let { player.setVideoSurface(it) } + saved?.let { load(it) } + CommandResult.Accepted + } + + override fun attachSurface(surface: Surface): CommandResult { + checkMain() + if (released) return CommandResult.Released + if (!surface.isValid) return CommandResult.InvalidArgument("Surface 已失效") + this.surface = surface + player.setVideoSurface(surface) + return CommandResult.Accepted + } + override fun detachSurface(surface: Surface) { + checkMain() + if (!released && this.surface === surface) { player.clearVideoSurface(surface); this.surface = null } + } + // 清理不能因调用方 lifecycleScope 取消而被跳过。 + override suspend fun release() = withContext(Dispatchers.Main.immediate + kotlinx.coroutines.NonCancellable) { + if (!released) { + released = true + handler.removeCallbacks(ticker) + player.removeListener(listener) + player.removeAnalyticsListener(analytics) + player.release() + surface = null + mutableState.value = PlaybackState(phase = PlaybackPhase.RELEASED) + } + } + private suspend fun command(block: () -> CommandResult): CommandResult = withContext(Dispatchers.Main.immediate) { + if (released) return@withContext CommandResult.Released + try { block().also { publish() } } + catch (_: Exception) { + val error = PlaybackError("COMMAND_FAILED", "播放命令执行失败") + emit(PlaybackEvent.Error(error)) + CommandResult.Failed(error) + } + } + private fun publish() { + if (released) return + val phase = if (lastError != null) PlaybackPhase.ERROR else when (player.playbackState) { + Player.STATE_BUFFERING -> if (!firstFrame) PlaybackPhase.PREPARING else PlaybackPhase.BUFFERING + Player.STATE_READY -> PlaybackPhase.READY + Player.STATE_ENDED -> PlaybackPhase.ENDED + else -> PlaybackPhase.IDLE + } + val tracks = player.currentTracks.groups.flatMapIndexed { g, group -> + val type = when (group.type) { C.TRACK_TYPE_VIDEO -> TrackType.VIDEO; C.TRACK_TYPE_AUDIO -> TrackType.AUDIO; C.TRACK_TYPE_TEXT -> TrackType.TEXT; else -> null } + if (type == null) emptyList() else (0 until group.length).map { t -> + val f = group.getTrackFormat(t) + MediaTrack("$g:$t", type, f.label, f.language, group.isTrackSelected(t)) + } + } + mutableState.value = PlaybackState(phase, player.playWhenReady, player.isPlaying, player.currentPosition.coerceAtLeast(0), + player.duration.takeIf { it != C.TIME_UNSET && it >= 0 }, player.bufferedPosition.coerceAtLeast(0), tracks, lastError, subtitleLines) + } + private fun decoder(type: TrackType, name: String) { + // API 29 起使用平台分类;旧系统不能可靠从名字推断,保留 unknown。 + val hardware = if (android.os.Build.VERSION.SDK_INT >= 29) runCatching { + android.media.MediaCodecList(android.media.MediaCodecList.ALL_CODECS) + .codecInfos.firstOrNull { it.name == name }?.isHardwareAccelerated + }.getOrNull() else null + emit(PlaybackEvent.DecoderChanged(type, name, hardware)) + } + private fun emit(event: PlaybackEvent) { mutableEvents.tryEmit(event) } + private fun checkMain() { check(Looper.myLooper() == Looper.getMainLooper()) { "必须在主线程创建或绑定输出" } } + private fun TrackType.media3Type() = when (this) { TrackType.VIDEO -> C.TRACK_TYPE_VIDEO; TrackType.AUDIO -> C.TRACK_TYPE_AUDIO; TrackType.TEXT -> C.TRACK_TYPE_TEXT } +} + +/** 应在主线程调用 create;工厂不会复用播放器实例。 */ +class Media3EngineFactory(context: Context) : PlayerEngineFactory { + private val applicationContext = context.applicationContext + override fun create(): PlayerEngine = Media3Engine(applicationContext) +} diff --git a/player-media3/src/test/kotlin/com/ttstd/player/media3/Media3EngineTest.kt b/player-media3/src/test/kotlin/com/ttstd/player/media3/Media3EngineTest.kt new file mode 100644 index 0000000..43586c4 --- /dev/null +++ b/player-media3/src/test/kotlin/com/ttstd/player/media3/Media3EngineTest.kt @@ -0,0 +1,46 @@ +package com.ttstd.player.media3 + +import com.ttstd.player.api.* +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +/** 不加载网络或媒体,验证真实适配器命令边界与资源释放;解码能力仍需真机。 */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class Media3EngineTest { + @Test fun invalidRequestDoesNotStartPlayback() = runBlocking { + val engine = Media3Engine(RuntimeEnvironment.getApplication()) + try { + assertTrue(engine.prepare(PlaybackRequest("relative.mp4")) is CommandResult.InvalidArgument) + assertEquals(PlaybackPhase.IDLE, engine.state.value.phase) + assertTrue(engine.setSpeed(Float.NaN) is CommandResult.InvalidArgument) + assertTrue(engine.setVolume(2f) is CommandResult.InvalidArgument) + assertTrue(engine.prepare(PlaybackRequest("srt://host:9000")) is CommandResult.Unsupported) + assertEquals(PlaybackPhase.IDLE, engine.state.value.phase) + } finally { engine.release() } + } + @Test fun rebuildPreservesPlaybackIntent() = runBlocking { + val engine = Media3Engine(RuntimeEnvironment.getApplication()) + try { + engine.play() + assertTrue(engine.state.value.playWhenReady) + assertEquals(CommandResult.Accepted, engine.setDecodePolicy(DecodePolicy(video = DecodeMode.SOFTWARE_ONLY))) + assertTrue(engine.state.value.playWhenReady) + engine.pause() + assertFalse(engine.state.value.playWhenReady) + } finally { engine.release() } + } + @Test fun releaseIsIdempotentAndRejectsFurtherCommands() = runBlocking { + val engine = Media3Engine(RuntimeEnvironment.getApplication()) + engine.release() + engine.release() + assertEquals(PlaybackPhase.RELEASED, engine.state.value.phase) + assertEquals(CommandResult.Released, engine.play()) + assertEquals(CommandResult.Released, engine.prepare(PlaybackRequest("https://example.com/a.mp4"))) + } +} diff --git a/player-render-android/build.gradle.kts b/player-render-android/build.gradle.kts new file mode 100644 index 0000000..e0181e6 --- /dev/null +++ b/player-render-android/build.gradle.kts @@ -0,0 +1,24 @@ +plugins { + id("com.android.library") + kotlin("android") +} + +android { + namespace = "com.ttstd.player.renderandroid" + compileSdk = 37 + + defaultConfig { + minSdk = 23 + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} + +kotlin { jvmToolchain(17) } + +dependencies { + api(project(":player-android-api")) +} diff --git a/player-render-android/src/main/AndroidManifest.xml b/player-render-android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/player-render-android/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/player-render-android/src/main/kotlin/com/ttstd/player/render/VideoSurfaceBinding.kt b/player-render-android/src/main/kotlin/com/ttstd/player/render/VideoSurfaceBinding.kt new file mode 100644 index 0000000..5c2ae81 --- /dev/null +++ b/player-render-android/src/main/kotlin/com/ttstd/player/render/VideoSurfaceBinding.kt @@ -0,0 +1,50 @@ +package com.ttstd.player.render + +import android.graphics.SurfaceTexture +import android.view.Surface +import android.view.SurfaceHolder +import android.view.SurfaceView +import android.view.TextureView +import com.ttstd.player.android.AndroidVideoOutput + +/** 主线程使用。close 解除回调和输出绑定;SurfaceView 的 Surface 所有权属于系统。 */ +class SurfaceViewBinding(private val view: SurfaceView, private val output: AndroidVideoOutput) : AutoCloseable, SurfaceHolder.Callback { + private var surface: Surface? = null + init { + view.holder.addCallback(this) + if (view.holder.surface.isValid) surfaceCreated(view.holder) + } + override fun surfaceCreated(holder: SurfaceHolder) { + surface = holder.surface + output.attachSurface(holder.surface) + } + override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit + override fun surfaceDestroyed(holder: SurfaceHolder) { detach() } + private fun detach() { surface?.let(output::detachSurface); surface = null } + override fun close() { view.holder.removeCallback(this); detach() } +} + +/** 独占 TextureView listener。仅释放自己创建的 Surface,SurfaceTexture 交回 View 管理。 */ +class TextureViewBinding(private val view: TextureView, private val output: AndroidVideoOutput) : AutoCloseable, TextureView.SurfaceTextureListener { + private var surface: Surface? = null + init { + require(view.surfaceTextureListener == null) { "TextureView 已绑定其他 listener" } + view.surfaceTextureListener = this + if (view.isAvailable) view.surfaceTexture?.let { onSurfaceTextureAvailable(it, view.width, view.height) } + } + override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) { + detach() + surface = Surface(texture).also { output.attachSurface(it) } + } + override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) = Unit + override fun onSurfaceTextureUpdated(texture: SurfaceTexture) = Unit + override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean { detach(); return true } + private fun detach() { + surface?.let { output.detachSurface(it); it.release() } + surface = null + } + override fun close() { + if (view.surfaceTextureListener === this) view.surfaceTextureListener = null + detach() + } +} diff --git a/player-rtmp-native/CMakeLists.txt b/player-rtmp-native/CMakeLists.txt new file mode 100644 index 0000000..65469ce --- /dev/null +++ b/player-rtmp-native/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.22.1) +project(tt_rtmp_client C) + +set(RTMP_SOURCE third_party/rtmp-client/src/main/cpp) +add_library(rtmp-jni SHARED + ${RTMP_SOURCE}/librtmp-jni.c + ${RTMP_SOURCE}/librtmp/amf.c + ${RTMP_SOURCE}/librtmp/hashswf.c + ${RTMP_SOURCE}/librtmp/log.c + ${RTMP_SOURCE}/librtmp/parseurl.c + ${RTMP_SOURCE}/librtmp/rtmp.c) +target_include_directories(rtmp-jni PRIVATE ${RTMP_SOURCE}/librtmp) +target_compile_definitions(rtmp-jni PRIVATE NO_CRYPTO TT_RTMP_PLAYBACK_ONLY) +# ELF 段和 RELRO 均按 16 KB 对齐;API 23/4 KB 设备仍可加载。 +target_link_options(rtmp-jni PRIVATE -Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=16384) +target_link_libraries(rtmp-jni PRIVATE log) diff --git a/player-rtmp-native/LOCAL-CHANGES.md b/player-rtmp-native/LOCAL-CHANGES.md new file mode 100644 index 0000000..0972dca --- /dev/null +++ b/player-rtmp-native/LOCAL-CHANGES.md @@ -0,0 +1,8 @@ +# 本地构建与修改 + +上游固定提交见 third_party/UPSTREAM.md。只构建播放 JNI,排除 RTMPMuxer Java 类和推流 C 文件。 +JNI 头文件中的三个推流/文件导出函数定义由 TT_RTMP_PLAYBACK_ONLY 宏排除,避免引入对应 muxer 实现。 +NDK 28.2.13676358 / CMake 3.22.1,四 ABI,max-page-size/common-page-size 为 16384。 +JNI 本地修改:指针经 intptr_t 转换;失败路径释放 JNI UTF 字符串、关闭 RTMP 连接;读取缓冲分配失败返回错误码;关闭可能含凭证的底层报文日志。 +使用 NO_CRYPTO,不提供 RTMPS。其余协议实现沿用上游;这不是完整 native 安全审计。 +Apache/LGPL 许可和提交信息作为 assets 打包。发行时应同时保留对应源代码、修改和可重建脚本。 diff --git a/player-rtmp-native/build.gradle.kts b/player-rtmp-native/build.gradle.kts new file mode 100644 index 0000000..e647bd1 --- /dev/null +++ b/player-rtmp-native/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { id("com.android.library") } + +android { + namespace = "com.ttstd.player.rtmp.nativeclient" + compileSdk = 37 + ndkVersion = "28.2.13676358" + defaultConfig { + minSdk = 23 + ndk { abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86", "x86_64") } + consumerProguardFiles("consumer-rules.pro") + } + sourceSets.getByName("main") { + java.srcDir("third_party/rtmp-client/src/main/java") + java.exclude("**/RTMPMuxer.java") // 仅提供播放 JNI,不打包推流入口。 + assets.srcDir("src/main/assets") + } + externalNativeBuild { cmake { path = file("CMakeLists.txt"); version = "3.22.1" } } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} diff --git a/player-rtmp-native/consumer-rules.pro b/player-rtmp-native/consumer-rules.pro new file mode 100644 index 0000000..2dc0b0a --- /dev/null +++ b/player-rtmp-native/consumer-rules.pro @@ -0,0 +1,3 @@ +# JNI 通过固定类名与方法名绑定,宿主启用 R8 时也必须保留。 +-keep class io.antmedia.rtmp_client.RtmpClient { *; } +-keep class io.antmedia.rtmp_client.RtmpClient$RtmpIOException { *; } diff --git a/player-rtmp-native/src/main/AndroidManifest.xml b/player-rtmp-native/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cc947c5 --- /dev/null +++ b/player-rtmp-native/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/player-rtmp-native/src/main/assets/third-party/rtmp/Apache-2.0.txt b/player-rtmp-native/src/main/assets/third-party/rtmp/Apache-2.0.txt new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/player-rtmp-native/src/main/assets/third-party/rtmp/Apache-2.0.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/player-rtmp-native/src/main/assets/third-party/rtmp/LGPL-2.1.txt b/player-rtmp-native/src/main/assets/third-party/rtmp/LGPL-2.1.txt new file mode 100644 index 0000000..00b4fed --- /dev/null +++ b/player-rtmp-native/src/main/assets/third-party/rtmp/LGPL-2.1.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/player-rtmp-native/src/main/assets/third-party/rtmp/UPSTREAM.md b/player-rtmp-native/src/main/assets/third-party/rtmp/UPSTREAM.md new file mode 100644 index 0000000..bcdf45a --- /dev/null +++ b/player-rtmp-native/src/main/assets/third-party/rtmp/UPSTREAM.md @@ -0,0 +1,7 @@ +# Vendored RTMP client + +Upstream: https://github.com/ant-media/LibRtmp-Client-for-Android +Commit: 3af67842f517f9c6bbd22b961878624d0c44b713 +Archive SHA-256: 2dc71ded3ac2eceeab74625471095abe4afe4f335236a3edd0465bb1cdc94552 + +Only upstream Java/C sources and license/readme files are included. No upstream build scripts are executed. Local CMake rebuilds playback JNI with NDK 28 and 16 KB ELF page alignment. Source headers and licenses are retained; librtmp components are LGPL. diff --git a/player-rtmp-native/third_party/LICENSE b/player-rtmp-native/third_party/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/player-rtmp-native/third_party/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/player-rtmp-native/third_party/README.md b/player-rtmp-native/third_party/README.md new file mode 100644 index 0000000..8ed35ed --- /dev/null +++ b/player-rtmp-native/third_party/README.md @@ -0,0 +1,78 @@ +## CHANGE-FOR-FORK + +[![](https://jitpack.io/v/mcxinyu/LibRtmp-Client-for-Android.svg)](https://jitpack.io/#mcxinyu/LibRtmp-Client-for-Android) + + +The configuration of target_link_libraries in [CMakeLists.txt](rtmp-client/CMakeLists.txt) has been modified to support the requirements of [Support 16 KB page sizes](https://developer.android.com/guide/practices/page-sizes). + +### about androidx.media3:media3-datasource-rtmp + +androidx.media3 [RTMP DataSource module](https://github.com/androidx/media/tree/release/libraries/datasource_rtmp) uses [the rtmp-client library](https://github.com/ant-media/LibRtmp-Client-for-Android), but the upstream developers have not updated it in time to support 16k, if you encounter [the same problem](https://github.com/androidx/media/issues/1918), you can try use this library first to solve the problem. + +![Image](https://github.com/user-attachments/assets/f6b76cc5-e2b4-4157-83f7-f0f84e0a80b4) + +```kts + implementation("androidx.media3:media3-datasource-rtmp:1.6.1") { + exclude("io.antmedia", "rtmp-client") + } + implementation("com.github.mcxinyu:LibRtmp-Client-for-Android:v3.2.0.m2") +``` + +--- + +# Librtmp Client for Android +It is probably the smallest(~60KB) rtmp client for android. It calls librtmp functions over JNI interface. +With all cpu architectures(arm, arm7, arm8, x86, x86-64, mips) its size is getting about 300KB + +It compiles librtmp library without ssl. + +In version 0.2, it supports FLV muxing and sending stream via RTMP. FLV muxing is based on this repo https://github.com/rainfly123/flvmuxer + + +##### To read streams, you can call below functions of **RtmpClient** from Java ##### + +For live streams add **" live=1"** at the end of the url when calling the **_open_** function + +* *public native int open(String url, boolean isPublishMode);* +* *public native int read(byte[] data, int offset, int size);* +* *public native int write(byte[] data);* +* *public native int seek(int seekTime);* +* *public native int pause(int pause);* +* *public native int close();* +* *public native int isConnected();*: Call this function to query the connection status. Returns 1 if connected, returns 0 if not connected + +Don't forget calling the **_close_** function after you are done. If you don't, there will be memory leakage + + +##### To publish streams, you can call below functions of **RtmpMuxer** from Java ##### +* *public native int open(String url, int width, int height);* : First, call this function with the url you plan to publish. Width and height are the width and height of the video. These two parameters are not mandatory. They are optional. They put width and height values into the metadata tag. +* *public native int writeVideo(byte[] data, int offset, int length, int timestamp);*: Write h264 nal units with this function +* *public native int writeAudio(byte[] data, int offset, int length, int timestamp);*: Write aac frames with this function +* *public native int close();*: Call this function to close the publishing. +* *public native int isConnected();*: Call this function to query the connection status. Returns 1 if connected, returns 0 if not connected + +To save flv file locally as well, you can use below functions +* *public native void file_open(String filename);* : call this function with full file path +* *public native void write_flv_header(boolean is_have_audio, boolean is_have_video);*: After opening file call this function +* *public native void file_close();*: Call this function to close the file. + +if any local file is opened, library will write the audio and video frames to local file as well. + +## Install ## + +- Add dependency to your build gradle +```sh +dependencies { + ... + compile 'net.butterflytv.utils:rtmp-client:3.1.0' + ... +} +``` + +- That's all. You can use RtmpClient class + + +
+ +[Ant Media](http://antmedia.io) + diff --git a/player-rtmp-native/third_party/UPSTREAM.md b/player-rtmp-native/third_party/UPSTREAM.md new file mode 100644 index 0000000..bcdf45a --- /dev/null +++ b/player-rtmp-native/third_party/UPSTREAM.md @@ -0,0 +1,7 @@ +# Vendored RTMP client + +Upstream: https://github.com/ant-media/LibRtmp-Client-for-Android +Commit: 3af67842f517f9c6bbd22b961878624d0c44b713 +Archive SHA-256: 2dc71ded3ac2eceeab74625471095abe4afe4f335236a3edd0465bb1cdc94552 + +Only upstream Java/C sources and license/readme files are included. No upstream build scripts are executed. Local CMake rebuilds playback JNI with NDK 28 and 16 KB ELF page alignment. Source headers and licenses are retained; librtmp components are LGPL. diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/flvmuxer/xiecc_rtmp.c b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/flvmuxer/xiecc_rtmp.c new file mode 100644 index 0000000..efb0ca3 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/flvmuxer/xiecc_rtmp.c @@ -0,0 +1,747 @@ +#include +#include +#include +#include "rtmp.h" +#include "log.h" +#include "xiecc_rtmp.h" +#include + +#define AAC_ADTS_HEADER_SIZE 7 +#define FLV_TAG_HEAD_LEN 11 +#define FLV_PRE_TAG_LEN 4 + +#define LOG_TAG "rtmp-muxer" + +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) + +static const AVal av_onMetaData = AVC("onMetaData"); +static const AVal av_duration = AVC("duration"); +static const AVal av_width = AVC("width"); +static const AVal av_height = AVC("height"); +static const AVal av_videocodecid = AVC("videocodecid"); +static const AVal av_avcprofile = AVC("avcprofile"); +static const AVal av_avclevel = AVC("avclevel"); +static const AVal av_videoframerate = AVC("videoframerate"); +static const AVal av_audiocodecid = AVC("audiocodecid"); +static const AVal av_audiosamplerate = AVC("audiosamplerate"); +static const AVal av_audiochannels = AVC("audiochannels"); +static const AVal av_avc1 = AVC("avc1"); +static const AVal av_mp4a = AVC("mp4a"); +static const AVal av_onPrivateData = AVC("onPrivateData"); +static const AVal av_record = AVC("record"); + + + +RTMP *rtmp; + +static FILE *g_file_handle = NULL; +static uint64_t g_time_begin; + +bool video_config_ok = false; +bool audio_config_ok = false; + +void flv_file_open(const char *filename) { + if (NULL == filename) { + return; + } + + g_file_handle = fopen(filename, "wb"); + + return; +} + +void flv_file_close() { + if (g_file_handle) { + fclose(g_file_handle); + } +} + +void write_flv_header(bool is_have_audio, bool is_have_video) { + char flv_file_header[] = "FLV\x1\x5\0\0\0\x9\0\0\0\0"; // have audio and have video + + if (is_have_audio && is_have_video) { + flv_file_header[4] = 0x05; + } else if (is_have_audio && !is_have_video) { + flv_file_header[4] = 0x04; + } else if (!is_have_audio && is_have_video) { + flv_file_header[4] = 0x01; + } else { + flv_file_header[4] = 0x00; + } + + fwrite(flv_file_header, 13, 1, g_file_handle); + + return; +} + +static uint8_t gen_audio_tag_header() +{ + /* + + UB [4] Format of SoundData. The following values are defined: + 0 = Linear PCM, platform endian + 1 = ADPCM + 2 = MP3 + 3 = Linear PCM, little endian + 4 = Nellymoser 16 kHz mono + 5 = Nellymoser 8 kHz mono + 6 = Nellymoser + 7 = G.711 A-law logarithmic PCM + 8 = G.711 mu-law logarithmic PCM + 9 = reserved + 10 = AAC ***************** + 11 = Speex + 14 = MP3 8 kHz + 15 = Device-specific sound + + SoundRate UB [2] Sampling rate. The following values are defined: + 0 = 5.5 kHz + 1 = 11 kHz + 2 = 22 kHz + 3 = 44 kHz ************* specification says mark it always 44khz + + SoundSize UB [1] + + to 16 bits internally. + 0 = 8-bit samples + 1 = 16-bit samples ************* + + SoundType UB [1] Mono or stereo sound + 0 = Mono sound + 1 = Stereo sound *********** specification says: even if sound is not stereo, mark as stereo + + + */ + uint8_t soundType = 1; // should be always 1 - stereo --- config.channel_configuration - 1; //0 mono, 1 stero + uint8_t soundRate = 3; //44Khz it should be always 44Khx + uint8_t val = 0; + + /* + switch (config.sample_frequency_index) { + case 10: { //11.025k + soundRate = 1; + break; + } + case 7: { //22k + soundRate = 2; + break; + } + case 4: { //44k + soundRate = 3; + break; + } + default: + { + return val; + } + } + */ + // 0xA0 means this is AAC + //soundrate << 2 44khz + // 0x02 means there are 16 bit samples + val = 0xA0 | (soundRate << 2) | 0x02 | soundType; + return val; +} + + +int rtmp_open_for_write(const char *url, uint32_t video_width, uint32_t video_height) { + rtmp = RTMP_Alloc(); + if (rtmp == NULL) { + return RTMP_ERROR_OPEN_ALLOC; + } + + RTMP_Init(rtmp); + RTMPResult ret = RTMP_SetupURL(rtmp, url); + + if (ret != RTMP_SUCCESS) { + RTMP_Free(rtmp); + return ret; + } + + RTMP_EnableWrite(rtmp); + + + ret = RTMP_Connect(rtmp, NULL); + if (ret != RTMP_SUCCESS) { + RTMP_Free(rtmp); + return ret; + } + ret = RTMP_ConnectStream(rtmp, 0); + + if (ret != RTMP_SUCCESS) { + return RTMP_ERROR_OPEN_CONNECT_STREAM; + } + + video_config_ok = false; + audio_config_ok = false; + + if (RTMP_IsConnected(rtmp)) { + + uint32_t offset = 0; + char buffer[512]; + char *output = buffer; + char *outend = buffer + sizeof(buffer); + char send_buffer[512]; + + output = AMF_EncodeString(output, outend, &av_onMetaData); + *output++ = AMF_ECMA_ARRAY; + + output = AMF_EncodeInt32(output, outend, 5); + output = AMF_EncodeNamedNumber(output, outend, &av_width, video_width); + output = AMF_EncodeNamedNumber(output, outend, &av_height, video_height); + output = AMF_EncodeNamedNumber(output, outend, &av_duration, 0.0); + output = AMF_EncodeNamedNumber(output, outend, &av_videocodecid, 7); + output = AMF_EncodeNamedNumber(output, outend, &av_audiocodecid, 10); + output = AMF_EncodeInt24(output, outend, AMF_OBJECT_END); + + int body_len = output - buffer; + int output_len = body_len + FLV_TAG_HEAD_LEN + FLV_PRE_TAG_LEN; + + send_buffer[offset++] = 0x12; //tagtype scripte + send_buffer[offset++] = (uint8_t) (body_len >> 16); //data len + send_buffer[offset++] = (uint8_t) (body_len >> 8); //data len + send_buffer[offset++] = (uint8_t) (body_len); //data len + send_buffer[offset++] = 0; //time stamp + send_buffer[offset++] = 0; //time stamp + send_buffer[offset++] = 0; //time stamp + send_buffer[offset++] = 0; //time stamp + send_buffer[offset++] = 0x00; //stream id 0 + send_buffer[offset++] = 0x00; //stream id 0 + send_buffer[offset++] = 0x00; //stream id 0 + + memcpy(send_buffer + offset, buffer, body_len); + + return RTMP_Write(rtmp, send_buffer, output_len); + } + return RTMP_ERROR_CONNECTION_LOST; +} + +int rtmp_close() { + if (rtmp) { + RTMP_Close(rtmp); + RTMP_Free(rtmp); + rtmp = NULL; + } +} + +int rtmp_is_connected() +{ + if (rtmp) { + if (RTMP_IsConnected(rtmp)) { + return 1; + } + } + return 0; +} + +int rtmp_read_date(uint8_t* data, int size) { + if (rtmp) { + RTMP_Read(rtmp, data, size); + } + return 0; +} + +// @brief send audio frame +// @param [in] data : AACAUDIODATA +// @param [in] size : AACAUDIODATA size +// @param [in] dts_us : decode timestamp of frame +// @param [in] abs_ts : indicate whether you'd like to use absolute time stamp +int rtmp_sender_write_audio_frame(uint8_t *data, + int size, + uint64_t dts_us, + uint32_t abs_ts) +{ + + int val = RTMP_SUCCESS; + uint32_t audio_ts = (uint32_t)dts_us; + uint32_t offset; + uint32_t body_len; + uint32_t output_len; + char *output ; + + //Audio OUTPUT + offset = 0; + + if (audio_config_ok == false) { + // first packet is two bytes AudioSpecificConfig + + //rtmp_xiecc->config = gen_config(audio_frame); + body_len = 2 + 2; //AudioTagHeader + AudioSpecificConfig + output_len = body_len + FLV_TAG_HEAD_LEN + FLV_PRE_TAG_LEN; + output = malloc(output_len); + // flv tag header + output[offset++] = 0x08; //tagtype audio + output[offset++] = (uint8_t)(body_len >> 16); //data len + output[offset++] = (uint8_t)(body_len >> 8); //data len + output[offset++] = (uint8_t)(body_len); //data len + output[offset++] = (uint8_t)(audio_ts >> 16); //time stamp + output[offset++] = (uint8_t)(audio_ts >> 8); //time stamp + output[offset++] = (uint8_t)(audio_ts); //time stamp + output[offset++] = (uint8_t)(audio_ts >> 24); //time stamp + output[offset++] = abs_ts; //stream id 0 + output[offset++] = 0x00; //stream id 0 + output[offset++] = 0x00; //stream id 0 + + //flv AudioTagHeader + output[offset++] = gen_audio_tag_header(); // sound format aac + output[offset++] = 0x00; //aac sequence header + + //flv VideoTagBody --AudioSpecificConfig + // uint8_t audio_object_type = rtmp_xiecc->config.audio_object_type; + output[offset++] = data[0]; //(audio_object_type << 3)|(rtmp_xiecc->config.sample_frequency_index >> 1); + output[offset++] = data[1]; //((rtmp_xiecc->config.sample_frequency_index & 0x01) << 7) \ + //| (rtmp_xiecc->config.channel_configuration << 3) ; + //no need to set pre_tag_size + + uint32_t fff = body_len + FLV_TAG_HEAD_LEN; + output[offset++] = (uint8_t)(fff >> 24); //data len + output[offset++] = (uint8_t)(fff >> 16); //data len + output[offset++] = (uint8_t)(fff >> 8); //data len + output[offset++] = (uint8_t)(fff); //data len + + if (g_file_handle) { + fwrite(output, output_len, 1, g_file_handle); + } + val = RTMP_Write(rtmp, output, output_len); + free(output); + //rtmp_xiecc->audio_config_ok = 1; + audio_config_ok = true; + } + else { + + body_len = 2 + + size; //aac header + raw data size // adts_len - AAC_ADTS_HEADER_SIZE; // audito tag header + adts_len - remove adts header + AudioTagHeader + output_len = body_len + FLV_TAG_HEAD_LEN + FLV_PRE_TAG_LEN; + output = malloc(output_len); + // flv tag header + output[offset++] = 0x08; //tagtype audio + output[offset++] = (uint8_t) (body_len >> 16); //data len + output[offset++] = (uint8_t) (body_len >> 8); //data len + output[offset++] = (uint8_t) (body_len); //data len + output[offset++] = (uint8_t) (audio_ts >> 16); //time stamp + output[offset++] = (uint8_t) (audio_ts >> 8); //time stamp + output[offset++] = (uint8_t) (audio_ts); //time stamp + output[offset++] = (uint8_t) (audio_ts >> 24); //time stamp + output[offset++] = abs_ts; //stream id 0 + output[offset++] = 0x00; //stream id 0 + output[offset++] = 0x00; //stream id 0 + + //flv AudioTagHeader + output[offset++] = gen_audio_tag_header(); // sound format aac + output[offset++] = 0x01; //aac raw data + + //flv VideoTagBody --raw aac data + memcpy(output + offset, data, size); // data + AAC_ADTS_HEADER_SIZE -> data, + // (adts_len - AAC_ADTS_HEADER_SIZE) -> size + + + //previous tag size + uint32_t fff = body_len + FLV_TAG_HEAD_LEN; + offset += size; // (adts_len - AAC_ADTS_HEADER_SIZE); + output[offset++] = (uint8_t) (fff >> 24); //data len + output[offset++] = (uint8_t) (fff >> 16); //data len + output[offset++] = (uint8_t) (fff >> 8); //data len + output[offset++] = (uint8_t) (fff); //data len + + if (g_file_handle) { + fwrite(output, output_len, 1, g_file_handle); + } + val = RTMP_Write(rtmp, output, output_len); + free(output); + } + return val; +} + +static uint32_t find_start_code(uint8_t *buf, uint32_t zeros_in_startcode) +{ + uint32_t info; + uint32_t i; + + info = 1; + if ((info = (buf[zeros_in_startcode] != 1)? 0: 1) == 0) + return 0; + + for (i = 0; i < zeros_in_startcode; i++) { + if (buf[i] != 0) { + info = 0; + break; + }; + } + return info; +} +/** + * + * len: parameter will be filled the length of the nal unit + * offset: is the pointer of the start of the nal unit. At the end, it will point to the start of the found NAL unit + * start: is the starting pointer + * total: total size of the packet + * + * return nal unit start byte pointer or NULL if there is no nal unit + */ +static uint8_t * get_nal(uint32_t *len, uint8_t **offset, uint8_t *start, uint32_t total) +{ + uint32_t info; + uint8_t *q ; + uint8_t *p = *offset; + *len = 0; + + while(1) { + //p=offset + // p - start >= total means reach of the end of the packet + // HINT "-3": Do not access not allowed memory + if ((p - start) >= total-3) + return NULL; + + info = find_start_code(p, 3); + //if info equals to 1, it means it find the start code + if (info == 1) + break; + p++; + } + q = p + 4; // add 4 for first bytes 0 0 0 1 + p = q; + // find a second start code in the data, there may be second code in data or there may not + while(1) { + // HINT "-3": Do not access not allowed memory + if ((p - start) >= total-3) { + p = start + total; + break; + } + + info = find_start_code(p, 3); + + if (info == 1) + break; + p++; + } + + // length of the nal unit + *len = (p - q); + //offset is the second nal unit start or the end of the data + *offset = p; + //return the first nal unit pointer + return q; +} + +int send_key_frame(int nal_len, uint32_t ts, uint32_t abs_ts, uint8_t *nal, int totalLength, uint8_t **buf_offset, uint8_t *buf) { + int offset = 0; + //int body_len = nal_len + 5 + 4; //flv VideoTagHeader + NALU length + int body_len = totalLength + 5; + int output_len = body_len + FLV_TAG_HEAD_LEN + FLV_PRE_TAG_LEN; + char *output = malloc(output_len); + if (!output) { + LOGD("Memory is not allocated..."); + } + // flv tag header + output[offset++] = 0x09; //tagtype video + output[offset++] = (uint8_t)(body_len >> 16); //data len + output[offset++] = (uint8_t)(body_len >> 8); //data len + output[offset++] = (uint8_t)(body_len); //data len + output[offset++] = (uint8_t)(ts >> 16); //time stamp + output[offset++] = (uint8_t)(ts >> 8); //time stamp + output[offset++] = (uint8_t)(ts); //time stamp + output[offset++] = (uint8_t)(ts >> 24); //time stamp + output[offset++] = abs_ts; //stream id 0 + output[offset++] = 0x00; //stream id 0 + output[offset++] = 0x00; //stream id 0 + + //flv VideoTagHeader + output[offset++] = 0x17; //key frame, AVC + output[offset++] = 0x01; //avc NALU unit + output[offset++] = 0x00; //composit time ?????????? + output[offset++] = 0x00; // composit time + output[offset++] = 0x00; //composit time + + output[offset++] = (uint8_t)(nal_len >> 24); //nal length + output[offset++] = (uint8_t)(nal_len >> 16); //nal length + output[offset++] = (uint8_t)(nal_len >> 8); //nal length + output[offset++] = (uint8_t)(nal_len); //nal length + memcpy(output + offset, nal, nal_len); + offset += nal_len; + + + //no need set pre_tag_size ,RTMP NO NEED + + + uint32_t fff = body_len + FLV_TAG_HEAD_LEN; + output[offset++] = (uint8_t)(fff >> 24); //data len + output[offset++] = (uint8_t)(fff >> 16); //data len + output[offset++] = (uint8_t)(fff >> 8); //data len + output[offset++] = (uint8_t)(fff); //data len + + if (g_file_handle) { + fwrite(output, output_len, 1, g_file_handle); + } + int val = RTMP_Write(rtmp, output, output_len); + //RTMP Send out + free(output); + return val; +} + + +// @brief send video frame, now only H264 supported +// @param [in] rtmp_sender handler +// @param [in] size : video data size +// @param [in] dts_us : decode timestamp of frame +// @param [in] key : key frame indicate, [0: non key] [1: key] +// @param [in] abs_ts : indicate whether you'd like to use absolute time stamp +int rtmp_sender_write_video_frame(uint8_t *data, + int total, + uint64_t dts_us, + int key, + uint32_t abs_ts) +{ + uint8_t * buf; + uint8_t * buf_offset; + int val = 0; + //int total; + uint32_t ts; + uint32_t nal_len; + uint32_t nal_len_n; + uint8_t *nal; + uint8_t *nal_n; + char *output ; + uint32_t offset = 0; + uint32_t body_len; + uint32_t output_len; + + buf = data; + buf_offset = data; + //total = size; + ts = (uint32_t)dts_us; + + //ts = RTMP_GetTime() - start_time; + offset = 0; + + nal = get_nal(&nal_len, &buf_offset, buf, total); + + if (nal == NULL) { + return -1; + } + + while (nal != NULL) { + + if ((nal[0] & 0x1f) == 0x07) { // it can be 27,47,67 + if (video_config_ok == true) { + LOGD("video config is already set"); + //only send video seq set once; + // return 0; + } + + nal_n = get_nal(&nal_len_n, &buf_offset, buf, total); //get pps + if (nal_n == NULL) { + LOGD("No Nal after SPS\n"); + return -1; + } + + body_len = nal_len + nal_len_n + 16; + output_len = body_len + FLV_TAG_HEAD_LEN + FLV_PRE_TAG_LEN; + output = malloc(output_len); + if (!output) { + LOGD("Memory is not allocated..."); + } + + offset = 0; + // flv tag header + output[offset++] = 0x09; //tagtype video + output[offset++] = (uint8_t)(body_len >> 16); //data len + output[offset++] = (uint8_t)(body_len >> 8); //data len + output[offset++] = (uint8_t)(body_len); //data len + output[offset++] = (uint8_t)(ts >> 16); //time stamp + output[offset++] = (uint8_t)(ts >> 8); //time stamp + output[offset++] = (uint8_t)(ts); //time stamp + output[offset++] = (uint8_t)(ts >> 24); //time stamp + output[offset++] = abs_ts; //stream id 0 + output[offset++] = 0x00; //stream id 0 + output[offset++] = 0x00; //stream id 0 + + //flv VideoTagHeader + output[offset++] = 0x17; //key frame, AVC + output[offset++] = 0x00; //avc sequence header + output[offset++] = 0x00; //composit time ?????????? + output[offset++] = 0x00; // composit time + output[offset++] = 0x00; //composit time + + //flv VideoTagBody --AVCDecoderCOnfigurationRecord + output[offset++] = 0x01; //configurationversion + output[offset++] = nal[1]; //avcprofileindication + output[offset++] = nal[2]; //profilecompatibilty + output[offset++] = nal[3]; //avclevelindication + output[offset++] = 0xff; //reserved + lengthsizeminusone + output[offset++] = 0xe1; //numofsequenceset + output[offset++] = (uint8_t)(nal_len >> 8); //sequence parameter set length high 8 bits + output[offset++] = (uint8_t)(nal_len); //sequence parameter set length low 8 bits + memcpy(output + offset, nal, nal_len); //H264 sequence parameter set + offset += nal_len; + output[offset++] = 0x01; //numofpictureset + output[offset++] = (uint8_t)(nal_len_n >> 8); //picture parameter set length high 8 bits + output[offset++] = (uint8_t)(nal_len_n); //picture parameter set length low 8 bits + memcpy(output + offset, nal_n, nal_len_n); //H264 picture parameter set + + //no need set pre_tag_size ,RTMP NO NEED + // flv test + + offset += nal_len_n; + uint32_t fff = body_len + FLV_TAG_HEAD_LEN; + output[offset++] = (uint8_t)(fff >> 24); //data len + output[offset++] = (uint8_t)(fff >> 16); //data len + output[offset++] = (uint8_t)(fff >> 8); //data len + output[offset++] = (uint8_t)(fff); //data len + + if (g_file_handle) { + fwrite(output, output_len, 1, g_file_handle); + } + val = RTMP_Write(rtmp, output, output_len); + //RTMP Send out + free(output); + if (val < RTMP_SUCCESS) { + return val; + } + video_config_ok = true; + + } + else if ((nal[0] & 0x1f) == 0x05) // it can be 25,45,65 + { + offset = 0; + //int body_len = nal_len + 5 + 4; //flv VideoTagHeader + NALU length + body_len = total + 5; + output_len = body_len + FLV_TAG_HEAD_LEN + FLV_PRE_TAG_LEN; + char *output = malloc(output_len); + if (!output) { + LOGD("Memory is not allocated..."); + } + // flv tag header + output[offset++] = 0x09; //tagtype video + output[offset++] = (uint8_t)(body_len >> 16); //data len + output[offset++] = (uint8_t)(body_len >> 8); //data len + output[offset++] = (uint8_t)(body_len); //data len + output[offset++] = (uint8_t)(ts >> 16); //time stamp + output[offset++] = (uint8_t)(ts >> 8); //time stamp + output[offset++] = (uint8_t)(ts); //time stamp + output[offset++] = (uint8_t)(ts >> 24); //time stamp + output[offset++] = abs_ts; //stream id 0 + output[offset++] = 0x00; //stream id 0 + output[offset++] = 0x00; //stream id 0 + + //flv VideoTagHeader + output[offset++] = 0x17; //key frame, AVC + output[offset++] = 0x01; //avc NALU unit + output[offset++] = 0x00; //composit time ?????????? + output[offset++] = 0x00; // composit time + output[offset++] = 0x00; //composit time + + output[offset++] = (uint8_t)(nal_len >> 24); //nal length + output[offset++] = (uint8_t)(nal_len >> 16); //nal length + output[offset++] = (uint8_t)(nal_len >> 8); //nal length + output[offset++] = (uint8_t)(nal_len); //nal length + memcpy(output + offset, nal, nal_len); + offset += nal_len; + + while ((nal = get_nal(&nal_len, &buf_offset, buf, total)) != NULL) + { + output[offset++] = (uint8_t)(nal_len >> 24); //nal length + output[offset++] = (uint8_t)(nal_len >> 16); //nal length + output[offset++] = (uint8_t)(nal_len >> 8); //nal length + output[offset++] = (uint8_t)(nal_len); //nal length + memcpy(output + offset, nal, nal_len); + offset += nal_len; + } + + //no need set pre_tag_size ,RTMP NO NEED + + uint32_t fff = body_len + FLV_TAG_HEAD_LEN; + output[offset++] = (uint8_t)(fff >> 24); //data len + output[offset++] = (uint8_t)(fff >> 16); //data len + output[offset++] = (uint8_t)(fff >> 8); //data len + output[offset++] = (uint8_t)(fff); //data len + + if (g_file_handle) { + fwrite(output, output_len, 1, g_file_handle); + } + int val = RTMP_Write(rtmp, output, output_len); + //RTMP Send out + free(output); + return val; + + + + } + else if ((nal[0] & 0x1f) == 0x01) // itcan be 21,41,61 + { + //body_len = nal_len + 5 + 4; //flv VideoTagHeader + NALU length + body_len = total + 5; + output_len = body_len + FLV_TAG_HEAD_LEN + FLV_PRE_TAG_LEN; + output = malloc(output_len); + if (!output) { + LOGD("Memory is not allocated..."); + } + offset = 0; + // flv tag header + output[offset++] = 0x09; //tagtype video + output[offset++] = (uint8_t)(body_len >> 16); //data len + output[offset++] = (uint8_t)(body_len >> 8); //data len + output[offset++] = (uint8_t)(body_len); //data len + output[offset++] = (uint8_t)(ts >> 16); //time stamp + output[offset++] = (uint8_t)(ts >> 8); //time stamp + output[offset++] = (uint8_t)(ts); //time stamp + output[offset++] = (uint8_t)(ts >> 24); //time stamp + output[offset++] = abs_ts; //stream id 0 + output[offset++] = 0x00; //stream id 0 + output[offset++] = 0x00; //stream id 0 + + //flv VideoTagHeader + output[offset++] = 0x27; //not key frame, AVC + output[offset++] = 0x01; //avc NALU unit + output[offset++] = 0x00; //composit time ?????????? + output[offset++] = 0x00; // composit time + output[offset++] = 0x00; //composit time + + output[offset++] = (uint8_t)(nal_len >> 24); //nal length + output[offset++] = (uint8_t)(nal_len >> 16); //nal length + output[offset++] = (uint8_t)(nal_len >> 8); //nal length + output[offset++] = (uint8_t)(nal_len); //nal length + memcpy(output + offset, nal, nal_len); + offset += nal_len; + + while ((nal = get_nal(&nal_len, &buf_offset, buf, total)) != NULL) + { + output[offset++] = (uint8_t)(nal_len >> 24); //nal length + output[offset++] = (uint8_t)(nal_len >> 16); //nal length + output[offset++] = (uint8_t)(nal_len >> 8); //nal length + output[offset++] = (uint8_t)(nal_len); //nal length + memcpy(output + offset, nal, nal_len); + offset += nal_len; + } + + //no need set pre_tag_size ,RTMP NO NEED + + //offset += nal_len; + uint32_t fff = body_len + FLV_TAG_HEAD_LEN; + output[offset++] = (uint8_t)(fff >> 24); //data len + output[offset++] = (uint8_t)(fff >> 16); //data len + output[offset++] = (uint8_t)(fff >> 8); //data len + output[offset++] = (uint8_t)(fff); //data len + + + if (g_file_handle) { + fwrite(output, output_len, 1, g_file_handle); + } + int result = RTMP_Write(rtmp, output, output_len); + + //RTMP Send out + free(output); + + if (result < RTMP_SUCCESS) { + return result; + } + val += result; + } + else { + LOGD("unexpected nal type %d" , (nal[0] & 0x1f)); + } + + nal = get_nal(&nal_len, &buf_offset, buf, total); + } + + return val; +} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/flvmuxer/xiecc_rtmp.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/flvmuxer/xiecc_rtmp.h new file mode 100644 index 0000000..b6336ea --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/flvmuxer/xiecc_rtmp.h @@ -0,0 +1,58 @@ +// +// Created by faraklit on 08.02.2016. +// + +#ifndef _XIECC_RTMP_H_ +#define _XIECC_RTMP_H_ +#include +#include + +#ifdef __cplusplus +extern "C"{ +#endif + +#define RTMP_STREAM_PROPERTY_PUBLIC 0x00000001 +#define RTMP_STREAM_PROPERTY_ALARM 0x00000002 +#define RTMP_STREAM_PROPERTY_RECORD 0x00000004 + + +int rtmp_open_for_write(const char *url, uint32_t video_width, uint32_t video_height); + +int rtmp_close(); + +int rtmp_is_connected(); + +// @brief send audio frame +// @param [in] rtmp_sender handler +// @param [in] data : AACAUDIODATA +// @param [in] size : AACAUDIODATA size +// @param [in] dts_us : decode timestamp of frame +int rtmp_sender_write_audio_frame(uint8_t *data, + int size, + uint64_t dts_us, + uint32_t abs_ts); + +// @brief send video frame, now only H264 supported +// @param [in] rtmp_sender handler +// @param [in] data : video data, (Full frames are required) +// @param [in] size : video data size +// @param [in] dts_us : decode timestamp of frame +// @param [in] key : key frame indicate, [0: non key] [1: key] +int rtmp_sender_write_video_frame(uint8_t *data, + int size, + uint64_t dts_us, + int key, + uint32_t abs_ts); + +int rtmp_read_date(uint8_t* data, int size); + +void flv_file_open(const char *filename); + +void flv_file_close(); + +void write_flv_header(bool is_have_audio, bool is_have_video); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp-jni.c b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp-jni.c new file mode 100644 index 0000000..e4908ec --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp-jni.c @@ -0,0 +1,198 @@ +#include +#include "librtmp-jni.h" +#include "rtmp.h" +#include +#include +#include "log.h" +// +// Created by faraklit on 01.01.2016. +// + + +#define LOG_TAG "rtmp-jni" + +#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) + +/* TTVideoPlayer: 底层报文可能包含 URI 凭证,日志由上层结构化错误替代。 */ +static void tt_discard_log(int level, const char *format, va_list args) { } + +//RTMP *rtmp = NULL; + +JNIEXPORT jlong JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeAlloc(JNIEnv* env, jobject thiz) { + RTMP_LogSetCallback(tt_discard_log); + RTMP *rtmp = RTMP_Alloc(); + return (jlong)(intptr_t)rtmp; +} + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: open + * Signature: (Ljava/lang/String;)I + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeOpen(JNIEnv* env, jobject thiz, jstring url_, + jboolean isPublishMode, jlong rtmpPointer, + jint sendTimeoutInMs, jint receiveTimeoutInMs) { + + const char *url = (*env)->GetStringUTFChars(env, url_, NULL); + RTMP *rtmp = (RTMP *) rtmpPointer; + // rtmp = RTMP_Alloc(); + if (rtmp == NULL) { + (*env)->ReleaseStringUTFChars(env, url_, url); + throwIllegalStateException(env, "RTMP open called without allocating rtmp object"); + return RTMP_ERROR_IGNORED; + } + + RTMP_Init(rtmp); + rtmp->Link.receiveTimeoutInMs = receiveTimeoutInMs; + rtmp->Link.sendTimeoutInMs = sendTimeoutInMs; + RTMPResult ret = RTMP_SetupURL(rtmp, url); + + if (ret != RTMP_SUCCESS) { + (*env)->ReleaseStringUTFChars(env, url_, url); + RTMP_Close(rtmp); + RTMP_Free(rtmp); + return ret; + } + if (isPublishMode) { + RTMP_EnableWrite(rtmp); + } + + ret = RTMP_Connect(rtmp, NULL); + if (ret != RTMP_SUCCESS) { + (*env)->ReleaseStringUTFChars(env, url_, url); + RTMP_Close(rtmp); + RTMP_Free(rtmp); + return ret; + } + ret = RTMP_ConnectStream(rtmp, 0); + + if (ret != RTMP_SUCCESS) { + (*env)->ReleaseStringUTFChars(env, url_, url); + RTMP_Close(rtmp); + RTMP_Free(rtmp); + return ret; + } + (*env)->ReleaseStringUTFChars(env, url_, url); + return RTMP_SUCCESS; +} + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: read + * Signature: ([CI)I + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeRead(JNIEnv* env, jobject thiz, jbyteArray data_, + jint offset, jint size, jlong rtmpPointer) { + + RTMP *rtmp = (RTMP *) rtmpPointer; + if (rtmp == NULL) { + throwIllegalStateException(env, "RTMP open function has to be called before read"); + return RTMP_ERROR_IGNORED; + } + + int connected = RTMP_IsConnected(rtmp); + if (!connected) { + return RTMP_ERROR_CONNECTION_LOST; + } + + char* data = malloc(size); + if (data == NULL) return RTMP_ERROR_MEM_ALLOC_FAIL; + + int readCount = RTMP_Read(rtmp, data, size); + + if (readCount > 0) { + (*env)->SetByteArrayRegion(env, data_, offset, readCount, data); // copy + } + free(data); + return readCount; +} + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: write + * Signature: ([CI)I + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeWrite(JNIEnv* env, jobject thiz, jbyteArray data, + jint offset, jint size, jlong rtmpPointer) { + + RTMP *rtmp = (RTMP *) rtmpPointer; + if (rtmp == NULL) { + throwIllegalStateException(env, "RTMP open function has to be called before write"); + return RTMP_ERROR_IGNORED; + } + + int connected = RTMP_IsConnected(rtmp); + if (!connected) { + return RTMP_ERROR_CONNECTION_LOST; + } + + jbyte* buf = malloc(size); + (*env)->GetByteArrayRegion(env, data, offset, size, buf); + int result = RTMP_Write(rtmp, buf, size); + free(buf); + return result; +} + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: seek + * Signature: (I)I + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_seek(JNIEnv* env, jobject thiz, jint seekTime) { + return 0; +} + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: pause + * Signature: (I)I + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativePause(JNIEnv* env, jobject thiz, jboolean pause, + jlong rtmpPointer) { + + RTMP *rtmp = (RTMP *) rtmpPointer; + if (rtmp == NULL) { + throwIllegalStateException(env, "RTMP open function has to be called before pause"); + return RTMP_ERROR_IGNORED; + } + + return RTMP_Pause(rtmp, pause); +} + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: close + * Signature: ()I + */ +JNIEXPORT void JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeClose(JNIEnv* env, jobject thiz, jlong rtmpPointer) { + + RTMP *rtmp = (RTMP *) rtmpPointer; + if (rtmp != NULL) { + RTMP_Close(rtmp); + RTMP_Free(rtmp); + } +} + + +JNIEXPORT jboolean JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeIsConnected(JNIEnv* env, jobject thiz, jlong rtmpPointer) { + RTMP *rtmp = (RTMP *) rtmpPointer; + if (rtmp == NULL) { + return false; + } + int connected = RTMP_IsConnected(rtmp); + return connected ? true : false; +} + +jint throwIllegalStateException (JNIEnv* env, char* message) +{ + jclass exception = (*env)->FindClass(env, "java/lang/IllegalStateException"); + return (*env)->ThrowNew(env, exception, message); +} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp-jni.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp-jni.h new file mode 100644 index 0000000..7ce1b38 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp-jni.h @@ -0,0 +1,111 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +#include +#include "flvmuxer/xiecc_rtmp.h" +/* Header for class net_butterflytv_rtmp_client_RtmpClient */ + +#ifndef _Included_io_antmedia_rtmp_client_RtmpClient +#define _Included_io_antmedia_rtmp_client_RtmpClient +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: open + * Signature: (Ljava/lang/String;)I + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeOpen(JNIEnv* env, jobject thiz, + jstring url, jboolean isPublishMode, + jlong rtmpPointer, jint sendTimeoutInMs, + jint receiveTimeoutInMs); + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: read + * Signature: ([CI)I + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeRead(JNIEnv* env, jobject thiz, + jbyteArray data, jint offset, jint size, + jlong rtmpPointer); + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: write + * Signature: ([CI)I + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeWrite(JNIEnv* env, jobject thiz, jbyteArray data, + jint offset, jint size, jlong rtmpPointer); + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: seek + * Signature: (I)I + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_seek(JNIEnv* env, jobject thiz, jint seekTime); + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: pause + * Signature: (I)I + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativePause(JNIEnv* env, jobject thiz, jboolean pause, + jlong rtmpPointer); + +/* + * Class: net_butterflytv_rtmp_client_RtmpClient + * Method: close + * Signature: ()I + */ +JNIEXPORT void JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeClose(JNIEnv* env, jobject thiz, jlong rtmpPointer); + +JNIEXPORT jboolean JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeIsConnected(JNIEnv* env, jobject thiz, jlong rtmpPointer); + +/* TTVideoPlayer: 推流/文件导出入口不属于播放构建。 */ +#ifndef TT_RTMP_PLAYBACK_ONLY +JNIEXPORT void JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_write_1flv_1header(JNIEnv* env, jobject thiz, + jboolean is_have_audio, jboolean is_have_video) { + write_flv_header(is_have_audio, is_have_video); +} + +JNIEXPORT void JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_file_1open(JNIEnv* env, jobject thiz, jstring filename) { + const char *cfilename = (*env)->GetStringUTFChars(env, filename, NULL); + + flv_file_open(cfilename); + + (*env)->ReleaseStringUTFChars(env, filename, cfilename); +} + +JNIEXPORT void JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_file_1close(JNIEnv* env, jobject thiz) { + + flv_file_close(); + +} +#endif + +JNIEXPORT jlong JNICALL +Java_io_antmedia_rtmp_1client_RtmpClient_nativeAlloc(JNIEnv* env, jobject thiz); + +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_read(JNIEnv* env, jobject thiz, jbyteArray data, + jint offset, jint size); + +JNIEXPORT jboolean JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_isConnected(JNIEnv* env, jobject thiz); + +jint throwIllegalStateException (JNIEnv* env, char* message); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/COPYING b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/COPYING new file mode 100644 index 0000000..00b4fed --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/COPYING @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/Makefile b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/Makefile new file mode 100644 index 0000000..96c076b --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/Makefile @@ -0,0 +1,118 @@ +VERSION=v2.4 + +prefix=/usr/local + +incdir=$(prefix)/include/librtmp +bindir=$(prefix)/bin +libdir=$(prefix)/lib +mandir=$(prefix)/man +BINDIR=$(DESTDIR)$(bindir) +INCDIR=$(DESTDIR)$(incdir) +LIBDIR=$(DESTDIR)$(libdir) +MANDIR=$(DESTDIR)$(mandir) + +CC=$(CROSS_COMPILE)gcc +LD=$(CROSS_COMPILE)ld +AR=$(CROSS_COMPILE)ar + +SYS=posix +CRYPTO=OPENSSL +#CRYPTO=GNUTLS +DEF_POLARSSL=-DUSE_POLARSSL +DEF_OPENSSL=-DUSE_OPENSSL +DEF_GNUTLS=-DUSE_GNUTLS +DEF_=-DNO_CRYPTO +REQ_GNUTLS=gnutls +REQ_OPENSSL=libssl,libcrypto +LIBZ=-lz +LIBS_posix= +LIBS_darwin= +LIBS_mingw=-lws2_32 -lwinmm -lgdi32 +LIB_GNUTLS=-lgnutls -lhogweed -lnettle -lgmp $(LIBZ) +LIB_OPENSSL=-lssl -lcrypto $(LIBZ) +LIB_POLARSSL=-lpolarssl $(LIBZ) +PRIVATE_LIBS=$(LIBS_$(SYS)) +CRYPTO_LIB=$(LIB_$(CRYPTO)) $(PRIVATE_LIBS) +CRYPTO_REQ=$(REQ_$(CRYPTO)) +CRYPTO_DEF=$(DEF_$(CRYPTO)) + +SO_VERSION=0 +SOX_posix=so +SOX_darwin=dylib +SOX_mingw=dll +SOX=$(SOX_$(SYS)) +SO_posix=.$(SOX).$(SO_VERSION) +SO_darwin=.$(SO_VERSION).$(SOX) +SO_mingw=-$(SO_VERSION).$(SOX) +SO_EXT=$(SO_$(SYS)) + +SODIR_posix=$(LIBDIR) +SODIR_darwin=$(LIBDIR) +SODIR_mingw=$(BINDIR) +SODIR=$(SODIR_$(SYS)) + +SO_LDFLAGS_posix=-shared -Wl,-soname,$@ +SO_LDFLAGS_darwin=-dynamiclib -twolevel_namespace -undefined dynamic_lookup \ + -fno-common -headerpad_max_install_names -install_name $(libdir)/$@ +SO_LDFLAGS_mingw=-shared -Wl,--out-implib,librtmp.dll.a +SO_LDFLAGS=$(SO_LDFLAGS_$(SYS)) + +INSTALL_IMPLIB_posix= +INSTALL_IMPLIB_darwin= +INSTALL_IMPLIB_mingw=cp librtmp.dll.a $(LIBDIR) +INSTALL_IMPLIB=$(INSTALL_IMPLIB_$(SYS)) + +SHARED=yes +SODEF_yes=-fPIC +SOLIB_yes=librtmp$(SO_EXT) +SOINST_yes=install_so +SO_DEF=$(SODEF_$(SHARED)) +SO_LIB=$(SOLIB_$(SHARED)) +SO_INST=$(SOINST_$(SHARED)) + +DEF=-DRTMPDUMP_VERSION=\"$(VERSION)\" $(CRYPTO_DEF) $(XDEF) +OPT=-O2 +CFLAGS=-Wall $(XCFLAGS) $(INC) $(DEF) $(OPT) $(SO_DEF) +LDFLAGS=$(XLDFLAGS) + + +OBJS=rtmp.o log.o amf.o hashswf.o parseurl.o + +all: librtmp.a $(SO_LIB) + +clean: + rm -f *.o *.a *.$(SOX) *$(SO_EXT) librtmp.pc + +librtmp.a: $(OBJS) + $(AR) rs $@ $? + +librtmp$(SO_EXT): $(OBJS) + $(CC) $(SO_LDFLAGS) $(LDFLAGS) -o $@ $^ $> $(CRYPTO_LIB) + ln -sf $@ librtmp.$(SOX) + +log.o: log.c log.h Makefile +rtmp.o: rtmp.c rtmp.h rtmp_sys.h handshake.h dh.h log.h amf.h Makefile +amf.o: amf.c amf.h bytes.h log.h Makefile +hashswf.o: hashswf.c http.h rtmp.h rtmp_sys.h Makefile +parseurl.o: parseurl.c rtmp.h rtmp_sys.h log.h Makefile + +librtmp.pc: librtmp.pc.in Makefile + sed -e "s;@prefix@;$(prefix);" -e "s;@libdir@;$(libdir);" \ + -e "s;@VERSION@;$(VERSION);" \ + -e "s;@CRYPTO_REQ@;$(CRYPTO_REQ);" \ + -e "s;@PRIVATE_LIBS@;$(PRIVATE_LIBS);" librtmp.pc.in > $@ + +install: install_base $(SO_INST) + +install_base: librtmp.a librtmp.pc + -mkdir -p $(INCDIR) $(LIBDIR)/pkgconfig $(MANDIR)/man3 $(SODIR) + cp amf.h http.h log.h rtmp.h $(INCDIR) + cp librtmp.a $(LIBDIR) + cp librtmp.pc $(LIBDIR)/pkgconfig + cp librtmp.3 $(MANDIR)/man3 + +install_so: librtmp$(SO_EXT) + cp librtmp$(SO_EXT) $(SODIR) + $(INSTALL_IMPLIB) + cd $(SODIR); ln -sf librtmp$(SO_EXT) librtmp.$(SOX) + diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/amf.c b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/amf.c new file mode 100644 index 0000000..563486c --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/amf.c @@ -0,0 +1,1270 @@ +/* + * Copyright (C) 2005-2008 Team XBMC + * http://www.xbmc.org + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include +#include + +#include "rtmp_sys.h" +#include "amf.h" +#include "log.h" +#include "bytes.h" + +static const AMFObjectProperty AMFProp_Invalid = { {0, 0}, AMF_INVALID }; +static const AVal AV_empty = { 0, 0 }; + +/* Data is Big-Endian */ +unsigned short +AMF_DecodeInt16(const char *data) +{ + unsigned char *c = (unsigned char *) data; + unsigned short val; + val = (c[0] << 8) | c[1]; + return val; +} + +unsigned int +AMF_DecodeInt24(const char *data) +{ + unsigned char *c = (unsigned char *) data; + unsigned int val; + val = (c[0] << 16) | (c[1] << 8) | c[2]; + return val; +} + +unsigned int +AMF_DecodeInt32(const char *data) +{ + unsigned char *c = (unsigned char *)data; + unsigned int val; + val = (c[0] << 24) | (c[1] << 16) | (c[2] << 8) | c[3]; + return val; +} + +void +AMF_DecodeString(const char *data, AVal *bv) +{ + bv->av_len = AMF_DecodeInt16(data); + bv->av_val = (bv->av_len > 0) ? (char *)data + 2 : NULL; +} + +void +AMF_DecodeLongString(const char *data, AVal *bv) +{ + bv->av_len = AMF_DecodeInt32(data); + bv->av_val = (bv->av_len > 0) ? (char *)data + 4 : NULL; +} + +double +AMF_DecodeNumber(const char *data) +{ + double dVal; +#if __FLOAT_WORD_ORDER == __BYTE_ORDER +#if __BYTE_ORDER == __BIG_ENDIAN + memcpy(&dVal, data, 8); +#elif __BYTE_ORDER == __LITTLE_ENDIAN + unsigned char *ci, *co; + ci = (unsigned char *)data; + co = (unsigned char *)&dVal; + co[0] = ci[7]; + co[1] = ci[6]; + co[2] = ci[5]; + co[3] = ci[4]; + co[4] = ci[3]; + co[5] = ci[2]; + co[6] = ci[1]; + co[7] = ci[0]; +#endif +#else +#if __BYTE_ORDER == __LITTLE_ENDIAN /* __FLOAT_WORD_ORER == __BIG_ENDIAN */ + unsigned char *ci, *co; + ci = (unsigned char *)data; + co = (unsigned char *)&dVal; + co[0] = ci[3]; + co[1] = ci[2]; + co[2] = ci[1]; + co[3] = ci[0]; + co[4] = ci[7]; + co[5] = ci[6]; + co[6] = ci[5]; + co[7] = ci[4]; +#else /* __BYTE_ORDER == __BIG_ENDIAN && __FLOAT_WORD_ORER == __LITTLE_ENDIAN */ + unsigned char *ci, *co; + ci = (unsigned char *)data; + co = (unsigned char *)&dVal; + co[0] = ci[4]; + co[1] = ci[5]; + co[2] = ci[6]; + co[3] = ci[7]; + co[4] = ci[0]; + co[5] = ci[1]; + co[6] = ci[2]; + co[7] = ci[3]; +#endif +#endif + return dVal; +} + +int +AMF_DecodeBoolean(const char *data) +{ + return *data != 0; +} + +char * +AMF_EncodeInt16(char *output, char *outend, short nVal) +{ + if (output+2 > outend) + return NULL; + + output[1] = nVal & 0xff; + output[0] = nVal >> 8; + return output+2; +} + +char * +AMF_EncodeInt24(char *output, char *outend, int nVal) +{ + if (output+3 > outend) + return NULL; + + output[2] = nVal & 0xff; + output[1] = nVal >> 8; + output[0] = nVal >> 16; + return output+3; +} + +char * +AMF_EncodeInt32(char *output, char *outend, int nVal) +{ + if (output+4 > outend) + return NULL; + + output[3] = nVal & 0xff; + output[2] = nVal >> 8; + output[1] = nVal >> 16; + output[0] = nVal >> 24; + return output+4; +} + +char * +AMF_EncodeString(char *output, char *outend, const AVal *bv) +{ + if ((bv->av_len < 65536 && output + 1 + 2 + bv->av_len > outend) || + output + 1 + 4 + bv->av_len > outend) + return NULL; + + if (bv->av_len < 65536) + { + *output++ = AMF_STRING; + + output = AMF_EncodeInt16(output, outend, bv->av_len); + } + else + { + *output++ = AMF_LONG_STRING; + + output = AMF_EncodeInt32(output, outend, bv->av_len); + } + memcpy(output, bv->av_val, bv->av_len); + output += bv->av_len; + + return output; +} + +char * +AMF_EncodeNumber(char *output, char *outend, double dVal) +{ + if (output+1+8 > outend) + return NULL; + + *output++ = AMF_NUMBER; /* type: Number */ + +#if __FLOAT_WORD_ORDER == __BYTE_ORDER +#if __BYTE_ORDER == __BIG_ENDIAN + memcpy(output, &dVal, 8); +#elif __BYTE_ORDER == __LITTLE_ENDIAN + { + unsigned char *ci, *co; + ci = (unsigned char *)&dVal; + co = (unsigned char *)output; + co[0] = ci[7]; + co[1] = ci[6]; + co[2] = ci[5]; + co[3] = ci[4]; + co[4] = ci[3]; + co[5] = ci[2]; + co[6] = ci[1]; + co[7] = ci[0]; + } +#endif +#else +#if __BYTE_ORDER == __LITTLE_ENDIAN /* __FLOAT_WORD_ORER == __BIG_ENDIAN */ + { + unsigned char *ci, *co; + ci = (unsigned char *)&dVal; + co = (unsigned char *)output; + co[0] = ci[3]; + co[1] = ci[2]; + co[2] = ci[1]; + co[3] = ci[0]; + co[4] = ci[7]; + co[5] = ci[6]; + co[6] = ci[5]; + co[7] = ci[4]; + } +#else /* __BYTE_ORDER == __BIG_ENDIAN && __FLOAT_WORD_ORER == __LITTLE_ENDIAN */ + { + unsigned char *ci, *co; + ci = (unsigned char *)&dVal; + co = (unsigned char *)output; + co[0] = ci[4]; + co[1] = ci[5]; + co[2] = ci[6]; + co[3] = ci[7]; + co[4] = ci[0]; + co[5] = ci[1]; + co[6] = ci[2]; + co[7] = ci[3]; + } +#endif +#endif + + return output+8; +} + +char * +AMF_EncodeBoolean(char *output, char *outend, int bVal) +{ + if (output+2 > outend) + return NULL; + + *output++ = AMF_BOOLEAN; + + *output++ = bVal ? 0x01 : 0x00; + + return output; +} + +char * +AMF_EncodeNamedString(char *output, char *outend, const AVal *strName, const AVal *strValue) +{ + if (output+2+strName->av_len > outend) + return NULL; + output = AMF_EncodeInt16(output, outend, strName->av_len); + + memcpy(output, strName->av_val, strName->av_len); + output += strName->av_len; + + return AMF_EncodeString(output, outend, strValue); +} + +char * +AMF_EncodeNamedNumber(char *output, char *outend, const AVal *strName, double dVal) +{ + if (output+2+strName->av_len > outend) + return NULL; + output = AMF_EncodeInt16(output, outend, strName->av_len); + + memcpy(output, strName->av_val, strName->av_len); + output += strName->av_len; + + return AMF_EncodeNumber(output, outend, dVal); +} + +char * +AMF_EncodeNamedBoolean(char *output, char *outend, const AVal *strName, int bVal) +{ + if (output+2+strName->av_len > outend) + return NULL; + output = AMF_EncodeInt16(output, outend, strName->av_len); + + memcpy(output, strName->av_val, strName->av_len); + output += strName->av_len; + + return AMF_EncodeBoolean(output, outend, bVal); +} + +void +AMFProp_GetName(AMFObjectProperty *prop, AVal *name) +{ + *name = prop->p_name; +} + +void +AMFProp_SetName(AMFObjectProperty *prop, AVal *name) +{ + prop->p_name = *name; +} + +AMFDataType +AMFProp_GetType(AMFObjectProperty *prop) +{ + return prop->p_type; +} + +double +AMFProp_GetNumber(AMFObjectProperty *prop) +{ + return prop->p_vu.p_number; +} + +int +AMFProp_GetBoolean(AMFObjectProperty *prop) +{ + return prop->p_vu.p_number != 0; +} + +void +AMFProp_GetString(AMFObjectProperty *prop, AVal *str) +{ + *str = prop->p_vu.p_aval; +} + +void +AMFProp_GetObject(AMFObjectProperty *prop, AMFObject *obj) +{ + *obj = prop->p_vu.p_object; +} + +int +AMFProp_IsValid(AMFObjectProperty *prop) +{ + return prop->p_type != AMF_INVALID; +} + +char * +AMFProp_Encode(AMFObjectProperty *prop, char *pBuffer, char *pBufEnd) +{ + if (prop->p_type == AMF_INVALID) + return NULL; + + if (prop->p_type != AMF_NULL && pBuffer + prop->p_name.av_len + 2 + 1 >= pBufEnd) + return NULL; + + if (prop->p_type != AMF_NULL && prop->p_name.av_len) + { + *pBuffer++ = prop->p_name.av_len >> 8; + *pBuffer++ = prop->p_name.av_len & 0xff; + memcpy(pBuffer, prop->p_name.av_val, prop->p_name.av_len); + pBuffer += prop->p_name.av_len; + } + + switch (prop->p_type) + { + case AMF_NUMBER: + pBuffer = AMF_EncodeNumber(pBuffer, pBufEnd, prop->p_vu.p_number); + break; + + case AMF_BOOLEAN: + pBuffer = AMF_EncodeBoolean(pBuffer, pBufEnd, prop->p_vu.p_number != 0); + break; + + case AMF_STRING: + pBuffer = AMF_EncodeString(pBuffer, pBufEnd, &prop->p_vu.p_aval); + break; + + case AMF_NULL: + if (pBuffer+1 >= pBufEnd) + return NULL; + *pBuffer++ = AMF_NULL; + break; + + case AMF_OBJECT: + pBuffer = AMF_Encode(&prop->p_vu.p_object, pBuffer, pBufEnd); + break; + + case AMF_ECMA_ARRAY: + pBuffer = AMF_EncodeEcmaArray(&prop->p_vu.p_object, pBuffer, pBufEnd); + break; + + case AMF_STRICT_ARRAY: + pBuffer = AMF_EncodeArray(&prop->p_vu.p_object, pBuffer, pBufEnd); + break; + + default: + RTMP_Log(RTMP_LOGERROR, "%s, invalid type. %d", __FUNCTION__, prop->p_type); + pBuffer = NULL; + }; + + return pBuffer; +} + +#define AMF3_INTEGER_MAX 268435455 +#define AMF3_INTEGER_MIN -268435456 + +int +AMF3ReadInteger(const char *data, int32_t *valp) +{ + int i = 0; + int32_t val = 0; + + while (i <= 2) + { /* handle first 3 bytes */ + if (data[i] & 0x80) + { /* byte used */ + val <<= 7; /* shift up */ + val |= (data[i] & 0x7f); /* add bits */ + i++; + } + else + { + break; + } + } + + if (i > 2) + { /* use 4th byte, all 8bits */ + val <<= 8; + val |= data[3]; + + /* range check */ + if (val > AMF3_INTEGER_MAX) + val -= (1 << 29); + } + else + { /* use 7bits of last unparsed byte (0xxxxxxx) */ + val <<= 7; + val |= data[i]; + } + + *valp = val; + + return i > 2 ? 4 : i + 1; +} + +int +AMF3ReadString(const char *data, AVal *str) +{ + int32_t ref = 0; + int len; + assert(str != 0); + + len = AMF3ReadInteger(data, &ref); + data += len; + + if ((ref & 0x1) == 0) + { /* reference: 0xxx */ + uint32_t refIndex = (ref >> 1); + RTMP_Log(RTMP_LOGDEBUG, + "%s, string reference, index: %d, not supported, ignoring!", + __FUNCTION__, refIndex); + return len; + } + else + { + uint32_t nSize = (ref >> 1); + + str->av_val = (char *)data; + str->av_len = nSize; + + return len + nSize; + } + return len; +} + +int +AMF3Prop_Decode(AMFObjectProperty *prop, const char *pBuffer, int nSize, + int bDecodeName) +{ + int nOriginalSize = nSize; + AMF3DataType type; + + prop->p_name.av_len = 0; + prop->p_name.av_val = NULL; + + if (nSize == 0 || !pBuffer) + { + RTMP_Log(RTMP_LOGDEBUG, "empty buffer/no buffer pointer!"); + return -1; + } + + /* decode name */ + if (bDecodeName) + { + AVal name; + int nRes = AMF3ReadString(pBuffer, &name); + + if (name.av_len <= 0) + return nRes; + + prop->p_name = name; + pBuffer += nRes; + nSize -= nRes; + } + + /* decode */ + type = *pBuffer++; + nSize--; + + switch (type) + { + case AMF3_UNDEFINED: + case AMF3_NULL: + prop->p_type = AMF_NULL; + break; + case AMF3_FALSE: + prop->p_type = AMF_BOOLEAN; + prop->p_vu.p_number = 0.0; + break; + case AMF3_TRUE: + prop->p_type = AMF_BOOLEAN; + prop->p_vu.p_number = 1.0; + break; + case AMF3_INTEGER: + { + int32_t res = 0; + int len = AMF3ReadInteger(pBuffer, &res); + prop->p_vu.p_number = (double)res; + prop->p_type = AMF_NUMBER; + nSize -= len; + break; + } + case AMF3_DOUBLE: + if (nSize < 8) + return -1; + prop->p_vu.p_number = AMF_DecodeNumber(pBuffer); + prop->p_type = AMF_NUMBER; + nSize -= 8; + break; + case AMF3_STRING: + case AMF3_XML_DOC: + case AMF3_XML: + { + int len = AMF3ReadString(pBuffer, &prop->p_vu.p_aval); + prop->p_type = AMF_STRING; + nSize -= len; + break; + } + case AMF3_DATE: + { + int32_t res = 0; + int len = AMF3ReadInteger(pBuffer, &res); + + nSize -= len; + pBuffer += len; + + if ((res & 0x1) == 0) + { /* reference */ + uint32_t nIndex = (res >> 1); + RTMP_Log(RTMP_LOGDEBUG, "AMF3_DATE reference: %d, not supported!", nIndex); + } + else + { + if (nSize < 8) + return -1; + + prop->p_vu.p_number = AMF_DecodeNumber(pBuffer); + nSize -= 8; + prop->p_type = AMF_NUMBER; + } + break; + } + case AMF3_OBJECT: + { + int nRes = AMF3_Decode(&prop->p_vu.p_object, pBuffer, nSize, TRUE); + if (nRes == -1) + return -1; + nSize -= nRes; + prop->p_type = AMF_OBJECT; + break; + } + case AMF3_ARRAY: + case AMF3_BYTE_ARRAY: + default: + RTMP_Log(RTMP_LOGDEBUG, "%s - AMF3 unknown/unsupported datatype 0x%02x, @%p", + __FUNCTION__, (unsigned char)(*pBuffer), pBuffer); + return -1; + } + + return nOriginalSize - nSize; +} + +int +AMFProp_Decode(AMFObjectProperty *prop, const char *pBuffer, int nSize, + int bDecodeName) +{ + int nOriginalSize = nSize; + int nRes; + + prop->p_name.av_len = 0; + prop->p_name.av_val = NULL; + + if (nSize == 0 || !pBuffer) + { + RTMP_Log(RTMP_LOGDEBUG, "%s: Empty buffer/no buffer pointer!", __FUNCTION__); + return -1; + } + + if (bDecodeName && nSize < 4) + { /* at least name (length + at least 1 byte) and 1 byte of data */ + RTMP_Log(RTMP_LOGDEBUG, + "%s: Not enough data for decoding with name, less than 4 bytes!", + __FUNCTION__); + return -1; + } + + if (bDecodeName) + { + unsigned short nNameSize = AMF_DecodeInt16(pBuffer); + if (nNameSize > nSize - 2) + { + RTMP_Log(RTMP_LOGDEBUG, + "%s: Name size out of range: namesize (%d) > len (%d) - 2", + __FUNCTION__, nNameSize, nSize); + return -1; + } + + AMF_DecodeString(pBuffer, &prop->p_name); + nSize -= 2 + nNameSize; + pBuffer += 2 + nNameSize; + } + + if (nSize == 0) + { + return -1; + } + + nSize--; + + prop->p_type = *pBuffer++; + switch (prop->p_type) + { + case AMF_NUMBER: + if (nSize < 8) + return -1; + prop->p_vu.p_number = AMF_DecodeNumber(pBuffer); + nSize -= 8; + break; + case AMF_BOOLEAN: + if (nSize < 1) + return -1; + prop->p_vu.p_number = (double)AMF_DecodeBoolean(pBuffer); + nSize--; + break; + case AMF_STRING: + { + unsigned short nStringSize = AMF_DecodeInt16(pBuffer); + + if (nSize < (long)nStringSize + 2) + return -1; + AMF_DecodeString(pBuffer, &prop->p_vu.p_aval); + nSize -= (2 + nStringSize); + break; + } + case AMF_OBJECT: + { + int nRes = AMF_Decode(&prop->p_vu.p_object, pBuffer, nSize, TRUE); + if (nRes == -1) + return -1; + nSize -= nRes; + break; + } + case AMF_MOVIECLIP: + { + RTMP_Log(RTMP_LOGERROR, "AMF_MOVIECLIP reserved!"); + return -1; + break; + } + case AMF_NULL: + case AMF_UNDEFINED: + case AMF_UNSUPPORTED: + prop->p_type = AMF_NULL; + break; + case AMF_REFERENCE: + { + RTMP_Log(RTMP_LOGERROR, "AMF_REFERENCE not supported!"); + return -1; + break; + } + case AMF_ECMA_ARRAY: + { + nSize -= 4; + + /* next comes the rest, mixed array has a final 0x000009 mark and names, so its an object */ + nRes = AMF_Decode(&prop->p_vu.p_object, pBuffer + 4, nSize, TRUE); + if (nRes == -1) + return -1; + nSize -= nRes; + break; + } + case AMF_OBJECT_END: + { + return -1; + break; + } + case AMF_STRICT_ARRAY: + { + unsigned int nArrayLen = AMF_DecodeInt32(pBuffer); + nSize -= 4; + + nRes = AMF_DecodeArray(&prop->p_vu.p_object, pBuffer + 4, nSize, + nArrayLen, FALSE); + if (nRes == -1) + return -1; + nSize -= nRes; + break; + } + case AMF_DATE: + { + RTMP_Log(RTMP_LOGDEBUG, "AMF_DATE"); + + if (nSize < 10) + return -1; + + prop->p_vu.p_number = AMF_DecodeNumber(pBuffer); + prop->p_UTCoffset = AMF_DecodeInt16(pBuffer + 8); + + nSize -= 10; + break; + } + case AMF_LONG_STRING: + case AMF_XML_DOC: + { + unsigned int nStringSize = AMF_DecodeInt32(pBuffer); + if (nSize < (long)nStringSize + 4) + return -1; + AMF_DecodeLongString(pBuffer, &prop->p_vu.p_aval); + nSize -= (4 + nStringSize); + if (prop->p_type == AMF_LONG_STRING) + prop->p_type = AMF_STRING; + break; + } + case AMF_RECORDSET: + { + RTMP_Log(RTMP_LOGERROR, "AMF_RECORDSET reserved!"); + return -1; + break; + } + case AMF_TYPED_OBJECT: + { + RTMP_Log(RTMP_LOGERROR, "AMF_TYPED_OBJECT not supported!"); + return -1; + break; + } + case AMF_AVMPLUS: + { + int nRes = AMF3_Decode(&prop->p_vu.p_object, pBuffer, nSize, TRUE); + if (nRes == -1) + return -1; + nSize -= nRes; + prop->p_type = AMF_OBJECT; + break; + } + default: + RTMP_Log(RTMP_LOGDEBUG, "%s - unknown datatype 0x%02x, @%p", __FUNCTION__, + prop->p_type, pBuffer - 1); + return -1; + } + + return nOriginalSize - nSize; +} + +void +AMFProp_Dump(AMFObjectProperty *prop) +{ + char strRes[256]; + char str[256]; + AVal name; + + if (prop->p_type == AMF_INVALID) + { + RTMP_Log(RTMP_LOGDEBUG, "Property: INVALID"); + return; + } + + if (prop->p_type == AMF_NULL) + { + RTMP_Log(RTMP_LOGDEBUG, "Property: NULL"); + return; + } + + if (prop->p_name.av_len) + { + name = prop->p_name; + } + else + { + name.av_val = "no-name."; + name.av_len = sizeof("no-name.") - 1; + } + if (name.av_len > 18) + name.av_len = 18; + + snprintf(strRes, 255, "Name: %18.*s, ", name.av_len, name.av_val); + + if (prop->p_type == AMF_OBJECT) + { + RTMP_Log(RTMP_LOGDEBUG, "Property: <%sOBJECT>", strRes); + AMF_Dump(&prop->p_vu.p_object); + return; + } + else if (prop->p_type == AMF_ECMA_ARRAY) + { + RTMP_Log(RTMP_LOGDEBUG, "Property: <%sECMA_ARRAY>", strRes); + AMF_Dump(&prop->p_vu.p_object); + return; + } + else if (prop->p_type == AMF_STRICT_ARRAY) + { + RTMP_Log(RTMP_LOGDEBUG, "Property: <%sSTRICT_ARRAY>", strRes); + AMF_Dump(&prop->p_vu.p_object); + return; + } + + switch (prop->p_type) + { + case AMF_NUMBER: + snprintf(str, 255, "NUMBER:\t%.2f", prop->p_vu.p_number); + break; + case AMF_BOOLEAN: + snprintf(str, 255, "BOOLEAN:\t%s", + prop->p_vu.p_number != 0.0 ? "TRUE" : "FALSE"); + break; + case AMF_STRING: + snprintf(str, 255, "STRING:\t%.*s", prop->p_vu.p_aval.av_len, + prop->p_vu.p_aval.av_val); + break; + case AMF_DATE: + snprintf(str, 255, "DATE:\ttimestamp: %.2f, UTC offset: %d", + prop->p_vu.p_number, prop->p_UTCoffset); + break; + default: + snprintf(str, 255, "INVALID TYPE 0x%02x", (unsigned char)prop->p_type); + } + + RTMP_Log(RTMP_LOGDEBUG, "Property: <%s%s>", strRes, str); +} + +void +AMFProp_Reset(AMFObjectProperty *prop) +{ + if (prop->p_type == AMF_OBJECT) + AMF_Reset(&prop->p_vu.p_object); + else + { + prop->p_vu.p_aval.av_len = 0; + prop->p_vu.p_aval.av_val = NULL; + } + prop->p_type = AMF_INVALID; +} + +/* AMFObject */ + +char * +AMF_Encode(AMFObject *obj, char *pBuffer, char *pBufEnd) +{ + int i; + + if (pBuffer+4 >= pBufEnd) + return NULL; + + *pBuffer++ = AMF_OBJECT; + + for (i = 0; i < obj->o_num; i++) + { + char *res = AMFProp_Encode(&obj->o_props[i], pBuffer, pBufEnd); + if (res == NULL) + { + RTMP_Log(RTMP_LOGERROR, "AMF_Encode - failed to encode property in index %d", + i); + break; + } + else + { + pBuffer = res; + } + } + + if (pBuffer + 3 >= pBufEnd) + return NULL; /* no room for the end marker */ + + pBuffer = AMF_EncodeInt24(pBuffer, pBufEnd, AMF_OBJECT_END); + + return pBuffer; +} + +char * +AMF_EncodeEcmaArray(AMFObject *obj, char *pBuffer, char *pBufEnd) +{ + int i; + + if (pBuffer+4 >= pBufEnd) + return NULL; + + *pBuffer++ = AMF_ECMA_ARRAY; + + pBuffer = AMF_EncodeInt32(pBuffer, pBufEnd, obj->o_num); + + for (i = 0; i < obj->o_num; i++) + { + char *res = AMFProp_Encode(&obj->o_props[i], pBuffer, pBufEnd); + if (res == NULL) + { + RTMP_Log(RTMP_LOGERROR, "AMF_Encode - failed to encode property in index %d", + i); + break; + } + else + { + pBuffer = res; + } + } + + if (pBuffer + 3 >= pBufEnd) + return NULL; /* no room for the end marker */ + + pBuffer = AMF_EncodeInt24(pBuffer, pBufEnd, AMF_OBJECT_END); + + return pBuffer; +} + +char * +AMF_EncodeArray(AMFObject *obj, char *pBuffer, char *pBufEnd) +{ + int i; + + if (pBuffer+4 >= pBufEnd) + return NULL; + + *pBuffer++ = AMF_STRICT_ARRAY; + + pBuffer = AMF_EncodeInt32(pBuffer, pBufEnd, obj->o_num); + + for (i = 0; i < obj->o_num; i++) + { + char *res = AMFProp_Encode(&obj->o_props[i], pBuffer, pBufEnd); + if (res == NULL) + { + RTMP_Log(RTMP_LOGERROR, "AMF_Encode - failed to encode property in index %d", + i); + break; + } + else + { + pBuffer = res; + } + } + + //if (pBuffer + 3 >= pBufEnd) + // return NULL; /* no room for the end marker */ + + //pBuffer = AMF_EncodeInt24(pBuffer, pBufEnd, AMF_OBJECT_END); + + return pBuffer; +} + +int +AMF_DecodeArray(AMFObject *obj, const char *pBuffer, int nSize, + int nArrayLen, int bDecodeName) +{ + int nOriginalSize = nSize; + int bError = FALSE; + + obj->o_num = 0; + obj->o_props = NULL; + while (nArrayLen > 0) + { + AMFObjectProperty prop; + int nRes; + nArrayLen--; + + nRes = AMFProp_Decode(&prop, pBuffer, nSize, bDecodeName); + if (nRes == -1) + bError = TRUE; + else + { + nSize -= nRes; + pBuffer += nRes; + AMF_AddProp(obj, &prop); + } + } + if (bError) + return -1; + + return nOriginalSize - nSize; +} + +int +AMF3_Decode(AMFObject *obj, const char *pBuffer, int nSize, int bAMFData) +{ + int nOriginalSize = nSize; + int32_t ref; + int len; + + obj->o_num = 0; + obj->o_props = NULL; + if (bAMFData) + { + if (*pBuffer != AMF3_OBJECT) + RTMP_Log(RTMP_LOGERROR, + "AMF3 Object encapsulated in AMF stream does not start with AMF3_OBJECT!"); + pBuffer++; + nSize--; + } + + ref = 0; + len = AMF3ReadInteger(pBuffer, &ref); + pBuffer += len; + nSize -= len; + + if ((ref & 1) == 0) + { /* object reference, 0xxx */ + uint32_t objectIndex = (ref >> 1); + + RTMP_Log(RTMP_LOGDEBUG, "Object reference, index: %d", objectIndex); + } + else /* object instance */ + { + int32_t classRef = (ref >> 1); + + AMF3ClassDef cd = { {0, 0} + }; + AMFObjectProperty prop; + + if ((classRef & 0x1) == 0) + { /* class reference */ + uint32_t classIndex = (classRef >> 1); + RTMP_Log(RTMP_LOGDEBUG, "Class reference: %d", classIndex); + } + else + { + int32_t classExtRef = (classRef >> 1); + int i; + + cd.cd_externalizable = (classExtRef & 0x1) == 1; + cd.cd_dynamic = ((classExtRef >> 1) & 0x1) == 1; + + cd.cd_num = classExtRef >> 2; + + /* class name */ + + len = AMF3ReadString(pBuffer, &cd.cd_name); + nSize -= len; + pBuffer += len; + + /*std::string str = className; */ + + RTMP_Log(RTMP_LOGDEBUG, + "Class name: %s, externalizable: %d, dynamic: %d, classMembers: %d", + cd.cd_name.av_val, cd.cd_externalizable, cd.cd_dynamic, + cd.cd_num); + + for (i = 0; i < cd.cd_num; i++) + { + AVal memberName; + len = AMF3ReadString(pBuffer, &memberName); + RTMP_Log(RTMP_LOGDEBUG, "Member: %s", memberName.av_val); + AMF3CD_AddProp(&cd, &memberName); + nSize -= len; + pBuffer += len; + } + } + + /* add as referencable object */ + + if (cd.cd_externalizable) + { + int nRes; + AVal name = AVC("DEFAULT_ATTRIBUTE"); + + RTMP_Log(RTMP_LOGDEBUG, "Externalizable, TODO check"); + + nRes = AMF3Prop_Decode(&prop, pBuffer, nSize, FALSE); + if (nRes == -1) + RTMP_Log(RTMP_LOGDEBUG, "%s, failed to decode AMF3 property!", + __FUNCTION__); + else + { + nSize -= nRes; + pBuffer += nRes; + } + + AMFProp_SetName(&prop, &name); + AMF_AddProp(obj, &prop); + } + else + { + int nRes, i; + for (i = 0; i < cd.cd_num; i++) /* non-dynamic */ + { + nRes = AMF3Prop_Decode(&prop, pBuffer, nSize, FALSE); + if (nRes == -1) + RTMP_Log(RTMP_LOGDEBUG, "%s, failed to decode AMF3 property!", + __FUNCTION__); + + AMFProp_SetName(&prop, AMF3CD_GetProp(&cd, i)); + AMF_AddProp(obj, &prop); + + pBuffer += nRes; + nSize -= nRes; + } + if (cd.cd_dynamic) + { + int len = 0; + + do + { + nRes = AMF3Prop_Decode(&prop, pBuffer, nSize, TRUE); + AMF_AddProp(obj, &prop); + + pBuffer += nRes; + nSize -= nRes; + + len = prop.p_name.av_len; + } + while (len > 0); + } + } + RTMP_Log(RTMP_LOGDEBUG, "class object!"); + } + return nOriginalSize - nSize; +} + +int +AMF_Decode(AMFObject *obj, const char *pBuffer, int nSize, int bDecodeName) +{ + int nOriginalSize = nSize; + int bError = FALSE; /* if there is an error while decoding - try to at least find the end mark AMF_OBJECT_END */ + + obj->o_num = 0; + obj->o_props = NULL; + while (nSize > 0) + { + AMFObjectProperty prop; + int nRes; + + if (nSize >=3 && AMF_DecodeInt24(pBuffer) == AMF_OBJECT_END) + { + nSize -= 3; + bError = FALSE; + break; + } + + if (bError) + { + RTMP_Log(RTMP_LOGERROR, + "DECODING ERROR, IGNORING BYTES UNTIL NEXT KNOWN PATTERN!"); + nSize--; + pBuffer++; + continue; + } + + nRes = AMFProp_Decode(&prop, pBuffer, nSize, bDecodeName); + if (nRes == -1) + bError = TRUE; + else + { + nSize -= nRes; + pBuffer += nRes; + AMF_AddProp(obj, &prop); + } + } + + if (bError) + return -1; + + return nOriginalSize - nSize; +} + +void +AMF_AddProp(AMFObject *obj, const AMFObjectProperty *prop) +{ + if (!(obj->o_num & 0x0f)) + obj->o_props = + realloc(obj->o_props, (obj->o_num + 16) * sizeof(AMFObjectProperty)); + memcpy(&obj->o_props[obj->o_num++], prop, sizeof(AMFObjectProperty)); +} + +int +AMF_CountProp(AMFObject *obj) +{ + return obj->o_num; +} + +AMFObjectProperty * +AMF_GetProp(AMFObject *obj, const AVal *name, int nIndex) +{ + if (nIndex >= 0) + { + if (nIndex < obj->o_num) + return &obj->o_props[nIndex]; + } + else + { + int n; + for (n = 0; n < obj->o_num; n++) + { + if (AVMATCH(&obj->o_props[n].p_name, name)) + return &obj->o_props[n]; + } + } + + return (AMFObjectProperty *)&AMFProp_Invalid; +} + +void +AMF_Dump(AMFObject *obj) +{ + int n; + RTMP_Log(RTMP_LOGDEBUG, "(object begin)"); + for (n = 0; n < obj->o_num; n++) + { + AMFProp_Dump(&obj->o_props[n]); + } + RTMP_Log(RTMP_LOGDEBUG, "(object end)"); +} + +void +AMF_Reset(AMFObject *obj) +{ + int n; + for (n = 0; n < obj->o_num; n++) + { + AMFProp_Reset(&obj->o_props[n]); + } + free(obj->o_props); + obj->o_props = NULL; + obj->o_num = 0; +} + + +/* AMF3ClassDefinition */ + +void +AMF3CD_AddProp(AMF3ClassDef *cd, AVal *prop) +{ + if (!(cd->cd_num & 0x0f)) + cd->cd_props = realloc(cd->cd_props, (cd->cd_num + 16) * sizeof(AVal)); + cd->cd_props[cd->cd_num++] = *prop; +} + +AVal * +AMF3CD_GetProp(AMF3ClassDef *cd, int nIndex) +{ + if (nIndex >= cd->cd_num) + return (AVal *)&AV_empty; + return &cd->cd_props[nIndex]; +} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/amf.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/amf.h new file mode 100644 index 0000000..5de414b --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/amf.h @@ -0,0 +1,164 @@ +#ifndef __AMF_H__ +#define __AMF_H__ +/* + * Copyright (C) 2005-2008 Team XBMC + * http://www.xbmc.org + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include + +#ifndef TRUE +#define TRUE 1 +#define FALSE 0 +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + + typedef enum + { AMF_NUMBER = 0, AMF_BOOLEAN, AMF_STRING, AMF_OBJECT, + AMF_MOVIECLIP, /* reserved, not used */ + AMF_NULL, AMF_UNDEFINED, AMF_REFERENCE, AMF_ECMA_ARRAY, AMF_OBJECT_END, + AMF_STRICT_ARRAY, AMF_DATE, AMF_LONG_STRING, AMF_UNSUPPORTED, + AMF_RECORDSET, /* reserved, not used */ + AMF_XML_DOC, AMF_TYPED_OBJECT, + AMF_AVMPLUS, /* switch to AMF3 */ + AMF_INVALID = 0xff + } AMFDataType; + + typedef enum + { AMF3_UNDEFINED = 0, AMF3_NULL, AMF3_FALSE, AMF3_TRUE, + AMF3_INTEGER, AMF3_DOUBLE, AMF3_STRING, AMF3_XML_DOC, AMF3_DATE, + AMF3_ARRAY, AMF3_OBJECT, AMF3_XML, AMF3_BYTE_ARRAY + } AMF3DataType; + + typedef struct AVal + { + char *av_val; + int av_len; + } AVal; +#define AVC(str) {str,sizeof(str)-1} +#define AVMATCH(a1,a2) ((a1)->av_len == (a2)->av_len && !memcmp((a1)->av_val,(a2)->av_val,(a1)->av_len)) + + struct AMFObjectProperty; + + typedef struct AMFObject + { + int o_num; + struct AMFObjectProperty *o_props; + } AMFObject; + + typedef struct AMFObjectProperty + { + AVal p_name; + AMFDataType p_type; + union + { + double p_number; + AVal p_aval; + AMFObject p_object; + } p_vu; + int16_t p_UTCoffset; + } AMFObjectProperty; + + char *AMF_EncodeString(char *output, char *outend, const AVal * str); + char *AMF_EncodeNumber(char *output, char *outend, double dVal); + char *AMF_EncodeInt16(char *output, char *outend, short nVal); + char *AMF_EncodeInt24(char *output, char *outend, int nVal); + char *AMF_EncodeInt32(char *output, char *outend, int nVal); + char *AMF_EncodeBoolean(char *output, char *outend, int bVal); + + /* Shortcuts for AMFProp_Encode */ + char *AMF_EncodeNamedString(char *output, char *outend, const AVal * name, const AVal * value); + char *AMF_EncodeNamedNumber(char *output, char *outend, const AVal * name, double dVal); + char *AMF_EncodeNamedBoolean(char *output, char *outend, const AVal * name, int bVal); + + unsigned short AMF_DecodeInt16(const char *data); + unsigned int AMF_DecodeInt24(const char *data); + unsigned int AMF_DecodeInt32(const char *data); + void AMF_DecodeString(const char *data, AVal * str); + void AMF_DecodeLongString(const char *data, AVal * str); + int AMF_DecodeBoolean(const char *data); + double AMF_DecodeNumber(const char *data); + + char *AMF_Encode(AMFObject * obj, char *pBuffer, char *pBufEnd); + char *AMF_EncodeEcmaArray(AMFObject *obj, char *pBuffer, char *pBufEnd); + char *AMF_EncodeArray(AMFObject *obj, char *pBuffer, char *pBufEnd); + + int AMF_Decode(AMFObject * obj, const char *pBuffer, int nSize, + int bDecodeName); + int AMF_DecodeArray(AMFObject * obj, const char *pBuffer, int nSize, + int nArrayLen, int bDecodeName); + int AMF3_Decode(AMFObject * obj, const char *pBuffer, int nSize, + int bDecodeName); + void AMF_Dump(AMFObject * obj); + void AMF_Reset(AMFObject * obj); + + void AMF_AddProp(AMFObject * obj, const AMFObjectProperty * prop); + int AMF_CountProp(AMFObject * obj); + AMFObjectProperty *AMF_GetProp(AMFObject * obj, const AVal * name, + int nIndex); + + AMFDataType AMFProp_GetType(AMFObjectProperty * prop); + void AMFProp_SetNumber(AMFObjectProperty * prop, double dval); + void AMFProp_SetBoolean(AMFObjectProperty * prop, int bflag); + void AMFProp_SetString(AMFObjectProperty * prop, AVal * str); + void AMFProp_SetObject(AMFObjectProperty * prop, AMFObject * obj); + + void AMFProp_GetName(AMFObjectProperty * prop, AVal * name); + void AMFProp_SetName(AMFObjectProperty * prop, AVal * name); + double AMFProp_GetNumber(AMFObjectProperty * prop); + int AMFProp_GetBoolean(AMFObjectProperty * prop); + void AMFProp_GetString(AMFObjectProperty * prop, AVal * str); + void AMFProp_GetObject(AMFObjectProperty * prop, AMFObject * obj); + + int AMFProp_IsValid(AMFObjectProperty * prop); + + char *AMFProp_Encode(AMFObjectProperty * prop, char *pBuffer, char *pBufEnd); + int AMF3Prop_Decode(AMFObjectProperty * prop, const char *pBuffer, + int nSize, int bDecodeName); + int AMFProp_Decode(AMFObjectProperty * prop, const char *pBuffer, + int nSize, int bDecodeName); + + void AMFProp_Dump(AMFObjectProperty * prop); + void AMFProp_Reset(AMFObjectProperty * prop); + + typedef struct AMF3ClassDef + { + AVal cd_name; + char cd_externalizable; + char cd_dynamic; + int cd_num; + AVal *cd_props; + } AMF3ClassDef; + + void AMF3CD_AddProp(AMF3ClassDef * cd, AVal * prop); + AVal *AMF3CD_GetProp(AMF3ClassDef * cd, int idx); + +#ifdef __cplusplus +} +#endif + +#endif /* __AMF_H__ */ diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/bytes.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/bytes.h new file mode 100644 index 0000000..8c6e80d --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/bytes.h @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2005-2008 Team XBMC + * http://www.xbmc.org + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#ifndef __BYTES_H__ +#define __BYTES_H__ + +#include + +#ifdef _WIN32 +/* Windows is little endian only */ +#define __LITTLE_ENDIAN 1234 +#define __BIG_ENDIAN 4321 +#define __BYTE_ORDER __LITTLE_ENDIAN +#define __FLOAT_WORD_ORDER __BYTE_ORDER + +typedef unsigned char uint8_t; + +#else /* !_WIN32 */ + +#include + +#if defined(BYTE_ORDER) && !defined(__BYTE_ORDER) +#define __BYTE_ORDER BYTE_ORDER +#endif + +#if defined(BIG_ENDIAN) && !defined(__BIG_ENDIAN) +#define __BIG_ENDIAN BIG_ENDIAN +#endif + +#if defined(LITTLE_ENDIAN) && !defined(__LITTLE_ENDIAN) +#define __LITTLE_ENDIAN LITTLE_ENDIAN +#endif + +#endif /* !_WIN32 */ + +/* define default endianness */ +#ifndef __LITTLE_ENDIAN +#define __LITTLE_ENDIAN 1234 +#endif + +#ifndef __BIG_ENDIAN +#define __BIG_ENDIAN 4321 +#endif + +#ifndef __BYTE_ORDER +#warning "Byte order not defined on your system, assuming little endian!" +#define __BYTE_ORDER __LITTLE_ENDIAN +#endif + +/* ok, we assume to have the same float word order and byte order if float word order is not defined */ +#ifndef __FLOAT_WORD_ORDER +#warning "Float word order not defined, assuming the same as byte order!" +#define __FLOAT_WORD_ORDER __BYTE_ORDER +#endif + +#if !defined(__BYTE_ORDER) || !defined(__FLOAT_WORD_ORDER) +#error "Undefined byte or float word order!" +#endif + +#if __FLOAT_WORD_ORDER != __BIG_ENDIAN && __FLOAT_WORD_ORDER != __LITTLE_ENDIAN +#error "Unknown/unsupported float word order!" +#endif + +#if __BYTE_ORDER != __BIG_ENDIAN && __BYTE_ORDER != __LITTLE_ENDIAN +#error "Unknown/unsupported byte order!" +#endif + +#endif + diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/dh.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/dh.h new file mode 100644 index 0000000..5fc3f32 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/dh.h @@ -0,0 +1,376 @@ +/* RTMPDump - Diffie-Hellmann Key Exchange + * Copyright (C) 2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include +#include +#include +#include + +#ifdef USE_POLARSSL +#include +typedef mpi * MP_t; +#define MP_new(m) m = malloc(sizeof(mpi)); mpi_init(m) +#define MP_set_w(mpi, w) mpi_lset(mpi, w) +#define MP_cmp(u, v) mpi_cmp_mpi(u, v) +#define MP_set(u, v) mpi_copy(u, v) +#define MP_sub_w(mpi, w) mpi_sub_int(mpi, mpi, w) +#define MP_cmp_1(mpi) mpi_cmp_int(mpi, 1) +#define MP_modexp(r, y, q, p) mpi_exp_mod(r, y, q, p, NULL) +#define MP_free(mpi) mpi_free(mpi); free(mpi) +#define MP_gethex(u, hex, res) MP_new(u); res = mpi_read_string(u, 16, hex) == 0 +#define MP_bytes(u) mpi_size(u) +#define MP_setbin(u,buf,len) mpi_write_binary(u,buf,len) +#define MP_getbin(u,buf,len) MP_new(u); mpi_read_binary(u,buf,len) + +typedef struct MDH { + MP_t p; + MP_t g; + MP_t pub_key; + MP_t priv_key; + long length; + dhm_context ctx; +} MDH; + +#define MDH_new() calloc(1,sizeof(MDH)) +#define MDH_free(vp) {MDH *_dh = vp; dhm_free(&_dh->ctx); MP_free(_dh->p); MP_free(_dh->g); MP_free(_dh->pub_key); MP_free(_dh->priv_key); free(_dh);} + +static int MDH_generate_key(MDH *dh) +{ + unsigned char out[2]; + MP_set(&dh->ctx.P, dh->p); + MP_set(&dh->ctx.G, dh->g); + dh->ctx.len = 128; + dhm_make_public(&dh->ctx, 1024, out, 1, havege_random, &RTMP_TLS_ctx->hs); + MP_new(dh->pub_key); + MP_new(dh->priv_key); + MP_set(dh->pub_key, &dh->ctx.GX); + MP_set(dh->priv_key, &dh->ctx.X); + return 1; +} + +static int MDH_compute_key(uint8_t *secret, size_t len, MP_t pub, MDH *dh) +{ + MP_set(&dh->ctx.GY, pub); + dhm_calc_secret(&dh->ctx, secret, &len); + return 0; +} + +#elif defined(USE_GNUTLS) +#include +#include +#include +typedef mpz_ptr MP_t; +#define MP_new(m) m = malloc(sizeof(*m)); mpz_init2(m, 1) +#define MP_set_w(mpi, w) mpz_set_ui(mpi, w) +#define MP_cmp(u, v) mpz_cmp(u, v) +#define MP_set(u, v) mpz_set(u, v) +#define MP_sub_w(mpi, w) mpz_sub_ui(mpi, mpi, w) +#define MP_cmp_1(mpi) mpz_cmp_ui(mpi, 1) +#define MP_modexp(r, y, q, p) mpz_powm(r, y, q, p) +#define MP_free(mpi) mpz_clear(mpi); free(mpi) +#define MP_gethex(u, hex, res) u = malloc(sizeof(*u)); mpz_init2(u, 1); res = (mpz_set_str(u, hex, 16) == 0) +#define MP_bytes(u) (mpz_sizeinbase(u, 2) + 7) / 8 +#define MP_setbin(u,buf,len) nettle_mpz_get_str_256(len,buf,u) +#define MP_getbin(u,buf,len) u = malloc(sizeof(*u)); mpz_init2(u, 1); nettle_mpz_set_str_256_u(u,len,buf) + +typedef struct MDH { + MP_t p; + MP_t g; + MP_t pub_key; + MP_t priv_key; + long length; +} MDH; + +#define MDH_new() calloc(1,sizeof(MDH)) +#define MDH_free(dh) do {MP_free(((MDH*)(dh))->p); MP_free(((MDH*)(dh))->g); MP_free(((MDH*)(dh))->pub_key); MP_free(((MDH*)(dh))->priv_key); free(dh);} while(0) + +static int MDH_generate_key(MDH *dh) +{ + int num_bytes; + uint32_t seed; + gmp_randstate_t rs; + + num_bytes = (mpz_sizeinbase(dh->p, 2) + 7) / 8 - 1; + if (num_bytes <= 0 || num_bytes > 18000) + return 0; + + dh->priv_key = calloc(1, sizeof(*dh->priv_key)); + if (!dh->priv_key) + return 0; + mpz_init2(dh->priv_key, 1); + gnutls_rnd(GNUTLS_RND_RANDOM, &seed, sizeof(seed)); + gmp_randinit_mt(rs); + gmp_randseed_ui(rs, seed); + mpz_urandomb(dh->priv_key, rs, num_bytes); + gmp_randclear(rs); + + dh->pub_key = calloc(1, sizeof(*dh->pub_key)); + if (!dh->pub_key) + return 0; + mpz_init2(dh->pub_key, 1); + if (!dh->pub_key) { + mpz_clear(dh->priv_key); + free(dh->priv_key); + return 0; + } + + mpz_powm(dh->pub_key, dh->g, dh->priv_key, dh->p); + + return 1; +} + +static int MDH_compute_key(uint8_t *secret, size_t len, MP_t pub, MDH *dh) +{ + mpz_ptr k; + int num_bytes; + + num_bytes = (mpz_sizeinbase(dh->p, 2) + 7) / 8; + if (num_bytes <= 0 || num_bytes > 18000) + return -1; + + k = calloc(1, sizeof(*k)); + if (!k) + return -1; + mpz_init2(k, 1); + + mpz_powm(k, pub, dh->priv_key, dh->p); + nettle_mpz_get_str_256(len, secret, k); + mpz_clear(k); + free(k); + + /* return the length of the shared secret key like DH_compute_key */ + return len; +} + +#else /* USE_OPENSSL */ +#include +#include + +typedef BIGNUM * MP_t; +#define MP_new(m) m = BN_new() +#define MP_set_w(mpi, w) BN_set_word(mpi, w) +#define MP_cmp(u, v) BN_cmp(u, v) +#define MP_set(u, v) BN_copy(u, v) +#define MP_sub_w(mpi, w) BN_sub_word(mpi, w) +#define MP_cmp_1(mpi) BN_cmp(mpi, BN_value_one()) +#define MP_modexp(r, y, q, p) do {BN_CTX *ctx = BN_CTX_new(); BN_mod_exp(r, y, q, p, ctx); BN_CTX_free(ctx);} while(0) +#define MP_free(mpi) BN_free(mpi) +#define MP_gethex(u, hex, res) res = BN_hex2bn(&u, hex) +#define MP_bytes(u) BN_num_bytes(u) +#define MP_setbin(u,buf,len) BN_bn2bin(u,buf) +#define MP_getbin(u,buf,len) u = BN_bin2bn(buf,len,0) + +#define MDH DH +#define MDH_new() DH_new() +#define MDH_free(dh) DH_free(dh) +#define MDH_generate_key(dh) DH_generate_key(dh) +#define MDH_compute_key(secret, seclen, pub, dh) DH_compute_key(secret, pub, dh) + +#endif + +#include "log.h" +#include "dhgroups.h" + +/* RFC 2631, Section 2.1.5, http://www.ietf.org/rfc/rfc2631.txt */ +static int +isValidPublicKey(MP_t y, MP_t p, MP_t q) +{ + int ret = TRUE; + MP_t bn; + assert(y); + + MP_new(bn); + assert(bn); + + /* y must lie in [2,p-1] */ + MP_set_w(bn, 1); + if (MP_cmp(y, bn) < 0) + { + RTMP_Log(RTMP_LOGERROR, "DH public key must be at least 2"); + ret = FALSE; + goto failed; + } + + /* bn = p-2 */ + MP_set(bn, p); + MP_sub_w(bn, 1); + if (MP_cmp(y, bn) > 0) + { + RTMP_Log(RTMP_LOGERROR, "DH public key must be at most p-2"); + ret = FALSE; + goto failed; + } + + /* Verify with Sophie-Germain prime + * + * This is a nice test to make sure the public key position is calculated + * correctly. This test will fail in about 50% of the cases if applied to + * random data. + */ + if (q) + { + /* y must fulfill y^q mod p = 1 */ + MP_modexp(bn, y, q, p); + + if (MP_cmp_1(bn) != 0) + { + RTMP_Log(RTMP_LOGWARNING, "DH public key does not fulfill y^q mod p = 1"); + } + } + +failed: + MP_free(bn); + return ret; +} + +static MDH * +DHInit(int nKeyBits) +{ + size_t res; + MDH *dh = MDH_new(); + + if (!dh) + goto failed; + + MP_new(dh->g); + + if (!dh->g) + goto failed; + + MP_gethex(dh->p, P1024, res); /* prime P1024, see dhgroups.h */ + if (!res) + { + goto failed; + } + + MP_set_w(dh->g, 2); /* base 2 */ + + dh->length = nKeyBits; + return dh; + +failed: + if (dh) + MDH_free(dh); + + return 0; +} + +static int +DHGenerateKey(MDH *dh) +{ + size_t res = 0; + if (!dh) + return 0; + + while (!res) + { + MP_t q1 = NULL; + + if (!MDH_generate_key(dh)) + return 0; + + MP_gethex(q1, Q1024, res); + assert(res); + + res = isValidPublicKey(dh->pub_key, dh->p, q1); + if (!res) + { + MP_free(dh->pub_key); + MP_free(dh->priv_key); + dh->pub_key = dh->priv_key = 0; + } + + MP_free(q1); + } + return 1; +} + +/* fill pubkey with the public key in BIG ENDIAN order + * 00 00 00 00 00 x1 x2 x3 ..... + */ + +static int +DHGetPublicKey(MDH *dh, uint8_t *pubkey, size_t nPubkeyLen) +{ + int len; + if (!dh || !dh->pub_key) + return 0; + + len = MP_bytes(dh->pub_key); + if (len <= 0 || len > (int) nPubkeyLen) + return 0; + + memset(pubkey, 0, nPubkeyLen); + MP_setbin(dh->pub_key, pubkey + (nPubkeyLen - len), len); + return 1; +} + +#if 0 /* unused */ +static int +DHGetPrivateKey(MDH *dh, uint8_t *privkey, size_t nPrivkeyLen) +{ + if (!dh || !dh->priv_key) + return 0; + + int len = MP_bytes(dh->priv_key); + if (len <= 0 || len > (int) nPrivkeyLen) + return 0; + + memset(privkey, 0, nPrivkeyLen); + MP_setbin(dh->priv_key, privkey + (nPrivkeyLen - len), len); + return 1; +} +#endif + +/* computes the shared secret key from the private MDH value and the + * other party's public key (pubkey) + */ +static int +DHComputeSharedSecretKey(MDH *dh, uint8_t *pubkey, size_t nPubkeyLen, + uint8_t *secret) +{ + MP_t q1 = NULL, pubkeyBn = NULL; + size_t len; + int res; + + if (!dh || !secret || nPubkeyLen >= INT_MAX) + return -1; + + MP_getbin(pubkeyBn, pubkey, nPubkeyLen); + if (!pubkeyBn) + return -1; + + MP_gethex(q1, Q1024, len); + assert(len); + + if (isValidPublicKey(pubkeyBn, dh->p, q1)) + res = MDH_compute_key(secret, nPubkeyLen, pubkeyBn, dh); + else + res = -1; + + MP_free(q1); + MP_free(pubkeyBn); + + return res; +} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/dhgroups.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/dhgroups.h new file mode 100644 index 0000000..2db3989 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/dhgroups.h @@ -0,0 +1,199 @@ +/* librtmp - Diffie-Hellmann Key Exchange + * Copyright (C) 2009 Andrej Stepanchuk + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +/* from RFC 3526, see http://www.ietf.org/rfc/rfc3526.txt */ + +/* 2^768 - 2 ^704 - 1 + 2^64 * { [2^638 pi] + 149686 } */ +#define P768 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A63A3620FFFFFFFFFFFFFFFF" + +/* 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 } */ +#define P1024 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381" \ + "FFFFFFFFFFFFFFFF" + +/* Group morder largest prime factor: */ +#define Q1024 \ + "7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68" \ + "948127044533E63A0105DF531D89CD9128A5043CC71A026E" \ + "F7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122" \ + "F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6" \ + "F71C35FDAD44CFD2D74F9208BE258FF324943328F67329C0" \ + "FFFFFFFFFFFFFFFF" + +/* 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 } */ +#define P1536 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF" + +/* 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 } */ +#define P2048 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AACAA68FFFFFFFFFFFFFFFF" + +/* 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 } */ +#define P3072 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF" + +/* 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 } */ +#define P4096 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" \ + "FFFFFFFFFFFFFFFF" + +/* 2^6144 - 2^6080 - 1 + 2^64 * { [2^6014 pi] + 929484 } */ +#define P6144 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" \ + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" \ + "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" \ + "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" \ + "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" \ + "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" \ + "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" \ + "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" \ + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" \ + "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" \ + "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" \ + "12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF" + +/* 2^8192 - 2^8128 - 1 + 2^64 * { [2^8062 pi] + 4743158 } */ +#define P8192 \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" \ + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" \ + "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" \ + "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" \ + "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" \ + "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" \ + "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" \ + "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" \ + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" \ + "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" \ + "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" \ + "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4" \ + "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300" \ + "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568" \ + "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" \ + "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B" \ + "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A" \ + "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36" \ + "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1" \ + "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92" \ + "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47" \ + "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" \ + "60C980DD98EDD3DFFFFFFFFFFFFFFFFF" + diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/handshake.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/handshake.h new file mode 100644 index 0000000..0438486 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/handshake.h @@ -0,0 +1,1419 @@ +/* + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * Copyright (C) 2010 2a665470ced7adb7156fcef47f8199a6371c117b8a79e399a2771e0b36384090 + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +/* This file is #included in rtmp.c, it is not meant to be compiled alone */ + +#ifdef USE_POLARSSL +#include +#include +#ifndef SHA256_DIGEST_LENGTH +#define SHA256_DIGEST_LENGTH 32 +#endif +#define HMAC_CTX sha2_context +#define HMAC_setup(ctx, key, len) sha2_hmac_starts(&ctx, (unsigned char *)key, len, 0) +#define HMAC_crunch(ctx, buf, len) sha2_hmac_update(&ctx, buf, len) +#define HMAC_finish(ctx, dig, dlen) dlen = SHA256_DIGEST_LENGTH; sha2_hmac_finish(&ctx, dig) + +typedef arc4_context * RC4_handle; +#define RC4_alloc(h) *h = malloc(sizeof(arc4_context)) +#define RC4_setkey(h,l,k) arc4_setup(h,k,l) +#define RC4_encrypt(h,l,d) arc4_crypt(h,l,(unsigned char *)d,(unsigned char *)d) +#define RC4_encrypt2(h,l,s,d) arc4_crypt(h,l,(unsigned char *)s,(unsigned char *)d) +#define RC4_free(h) free(h) + +#elif defined(USE_GNUTLS) +#include +#include +#ifndef SHA256_DIGEST_LENGTH +#define SHA256_DIGEST_LENGTH 32 +#endif +#undef HMAC_CTX +#define HMAC_CTX struct hmac_sha256_ctx +#define HMAC_setup(ctx, key, len) hmac_sha256_set_key(&ctx, len, key) +#define HMAC_crunch(ctx, buf, len) hmac_sha256_update(&ctx, len, buf) +#define HMAC_finish(ctx, dig, dlen) dlen = SHA256_DIGEST_LENGTH; hmac_sha256_digest(&ctx, SHA256_DIGEST_LENGTH, dig) +#define HMAC_close(ctx) + +typedef struct arcfour_ctx* RC4_handle; +#define RC4_alloc(h) *h = malloc(sizeof(struct arcfour_ctx)) +#define RC4_setkey(h,l,k) arcfour_set_key(h, l, k) +#define RC4_encrypt(h,l,d) arcfour_crypt(h,l,(uint8_t *)d,(uint8_t *)d) +#define RC4_encrypt2(h,l,s,d) arcfour_crypt(h,l,(uint8_t *)d,(uint8_t *)s) +#define RC4_free(h) free(h) + +#else /* USE_OPENSSL */ +#include +#include +#include +#if OPENSSL_VERSION_NUMBER < 0x0090800 || !defined(SHA256_DIGEST_LENGTH) +#error Your OpenSSL is too old, need 0.9.8 or newer with SHA256 +#endif +#define HMAC_setup(ctx, key, len) HMAC_CTX_init(&ctx); HMAC_Init_ex(&ctx, key, len, EVP_sha256(), 0) +#define HMAC_crunch(ctx, buf, len) HMAC_Update(&ctx, buf, len) +#define HMAC_finish(ctx, dig, dlen) HMAC_Final(&ctx, dig, &dlen); HMAC_CTX_cleanup(&ctx) + +typedef RC4_KEY * RC4_handle; +#define RC4_alloc(h) *h = malloc(sizeof(RC4_KEY)) +#define RC4_setkey(h,l,k) RC4_set_key(h,l,k) +#define RC4_encrypt(h,l,d) RC4(h,l,(uint8_t *)d,(uint8_t *)d) +#define RC4_encrypt2(h,l,s,d) RC4(h,l,(uint8_t *)s,(uint8_t *)d) +#define RC4_free(h) free(h) +#endif + +#define FP10 + +#include "dh.h" + +static const uint8_t GenuineFMSKey[] = { + 0x47, 0x65, 0x6e, 0x75, 0x69, 0x6e, 0x65, 0x20, 0x41, 0x64, 0x6f, 0x62, + 0x65, 0x20, 0x46, 0x6c, + 0x61, 0x73, 0x68, 0x20, 0x4d, 0x65, 0x64, 0x69, 0x61, 0x20, 0x53, 0x65, + 0x72, 0x76, 0x65, 0x72, + 0x20, 0x30, 0x30, 0x31, /* Genuine Adobe Flash Media Server 001 */ + + 0xf0, 0xee, 0xc2, 0x4a, 0x80, 0x68, 0xbe, 0xe8, 0x2e, 0x00, 0xd0, 0xd1, + 0x02, 0x9e, 0x7e, 0x57, 0x6e, 0xec, 0x5d, 0x2d, 0x29, 0x80, 0x6f, 0xab, + 0x93, 0xb8, 0xe6, 0x36, + 0xcf, 0xeb, 0x31, 0xae +}; /* 68 */ + +static const uint8_t GenuineFPKey[] = { + 0x47, 0x65, 0x6E, 0x75, 0x69, 0x6E, 0x65, 0x20, 0x41, 0x64, 0x6F, 0x62, + 0x65, 0x20, 0x46, 0x6C, + 0x61, 0x73, 0x68, 0x20, 0x50, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x20, 0x30, + 0x30, 0x31, /* Genuine Adobe Flash Player 001 */ + 0xF0, 0xEE, + 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02, 0x9E, + 0x7E, 0x57, 0x6E, 0xEC, + 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8, 0xE6, 0x36, 0xCF, 0xEB, + 0x31, 0xAE +}; /* 62 */ + +static void InitRC4Encryption + (uint8_t * secretKey, + uint8_t * pubKeyIn, + uint8_t * pubKeyOut, RC4_handle *rc4keyIn, RC4_handle *rc4keyOut) +{ + uint8_t digest[SHA256_DIGEST_LENGTH]; + unsigned int digestLen = 0; + HMAC_CTX ctx; + + RC4_alloc(rc4keyIn); + RC4_alloc(rc4keyOut); + + HMAC_setup(ctx, secretKey, 128); + HMAC_crunch(ctx, pubKeyIn, 128); + HMAC_finish(ctx, digest, digestLen); + + RTMP_Log(RTMP_LOGDEBUG, "RC4 Out Key: "); + RTMP_LogHex(RTMP_LOGDEBUG, digest, 16); + + RC4_setkey(*rc4keyOut, 16, digest); + + HMAC_setup(ctx, secretKey, 128); + HMAC_crunch(ctx, pubKeyOut, 128); + HMAC_finish(ctx, digest, digestLen); + + RTMP_Log(RTMP_LOGDEBUG, "RC4 In Key: "); + RTMP_LogHex(RTMP_LOGDEBUG, digest, 16); + + RC4_setkey(*rc4keyIn, 16, digest); +} + +typedef unsigned int (getoff)(uint8_t *buf, unsigned int len); + +static unsigned int +GetDHOffset2(uint8_t *handshake, unsigned int len) +{ + unsigned int offset = 0; + uint8_t *ptr = handshake + 768; + unsigned int res; + + assert(RTMP_SIG_SIZE <= len); + + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + + res = (offset % 632) + 8; + + if (res + 128 > 767) + { + RTMP_Log(RTMP_LOGERROR, + "%s: Couldn't calculate correct DH offset (got %d), exiting!", + __FUNCTION__, res); + exit(1); + } + return res; +} + +static unsigned int +GetDigestOffset2(uint8_t *handshake, unsigned int len) +{ + unsigned int offset = 0; + uint8_t *ptr = handshake + 772; + unsigned int res; + + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + + res = (offset % 728) + 776; + + if (res + 32 > 1535) + { + RTMP_Log(RTMP_LOGERROR, + "%s: Couldn't calculate correct digest offset (got %d), exiting", + __FUNCTION__, res); + exit(1); + } + return res; +} + +static unsigned int +GetDHOffset1(uint8_t *handshake, unsigned int len) +{ + unsigned int offset = 0; + uint8_t *ptr = handshake + 1532; + unsigned int res; + + assert(RTMP_SIG_SIZE <= len); + + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + + res = (offset % 632) + 772; + + if (res + 128 > 1531) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't calculate DH offset (got %d), exiting!", + __FUNCTION__, res); + exit(1); + } + + return res; +} + +static unsigned int +GetDigestOffset1(uint8_t *handshake, unsigned int len) +{ + unsigned int offset = 0; + uint8_t *ptr = handshake + 8; + unsigned int res; + + assert(12 <= len); + + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + ptr++; + offset += (*ptr); + + res = (offset % 728) + 12; + + if (res + 32 > 771) + { + RTMP_Log(RTMP_LOGERROR, + "%s: Couldn't calculate digest offset (got %d), exiting!", + __FUNCTION__, res); + exit(1); + } + + return res; +} + +static getoff *digoff[] = {GetDigestOffset1, GetDigestOffset2}; +static getoff *dhoff[] = {GetDHOffset1, GetDHOffset2}; + +static void +HMACsha256(const uint8_t *message, size_t messageLen, const uint8_t *key, + size_t keylen, uint8_t *digest) +{ + unsigned int digestLen; + HMAC_CTX ctx; + + HMAC_setup(ctx, key, keylen); + HMAC_crunch(ctx, message, messageLen); + HMAC_finish(ctx, digest, digestLen); + + assert(digestLen == 32); +} + +static void +CalculateDigest(unsigned int digestPos, uint8_t *handshakeMessage, + const uint8_t *key, size_t keyLen, uint8_t *digest) +{ + const int messageLen = RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH; + uint8_t message[RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH]; + + memcpy(message, handshakeMessage, digestPos); + memcpy(message + digestPos, + &handshakeMessage[digestPos + SHA256_DIGEST_LENGTH], + messageLen - digestPos); + + HMACsha256(message, messageLen, key, keyLen, digest); +} + +static int +VerifyDigest(unsigned int digestPos, uint8_t *handshakeMessage, const uint8_t *key, + size_t keyLen) +{ + uint8_t calcDigest[SHA256_DIGEST_LENGTH]; + + CalculateDigest(digestPos, handshakeMessage, key, keyLen, calcDigest); + + return memcmp(&handshakeMessage[digestPos], calcDigest, + SHA256_DIGEST_LENGTH) == 0; +} + +/* handshake + * + * Type = [1 bytes] plain: 0x03, encrypted: 0x06, 0x08, 0x09 + * -------------------------------------------------------------------- [1536 bytes] + * Uptime = [4 bytes] big endian unsigned number, uptime + * Version = [4 bytes] each byte represents a version number, e.g. 9.0.124.0 + * ... + * + */ + +static const uint32_t rtmpe8_keys[16][4] = { + {0xbff034b2, 0x11d9081f, 0xccdfb795, 0x748de732}, + {0x086a5eb6, 0x1743090e, 0x6ef05ab8, 0xfe5a39e2}, + {0x7b10956f, 0x76ce0521, 0x2388a73a, 0x440149a1}, + {0xa943f317, 0xebf11bb2, 0xa691a5ee, 0x17f36339}, + {0x7a30e00a, 0xb529e22c, 0xa087aea5, 0xc0cb79ac}, + {0xbdce0c23, 0x2febdeff, 0x1cfaae16, 0x1123239d}, + {0x55dd3f7b, 0x77e7e62e, 0x9bb8c499, 0xc9481ee4}, + {0x407bb6b4, 0x71e89136, 0xa7aebf55, 0xca33b839}, + {0xfcf6bdc3, 0xb63c3697, 0x7ce4f825, 0x04d959b2}, + {0x28e091fd, 0x41954c4c, 0x7fb7db00, 0xe3a066f8}, + {0x57845b76, 0x4f251b03, 0x46d45bcd, 0xa2c30d29}, + {0x0acceef8, 0xda55b546, 0x03473452, 0x5863713b}, + {0xb82075dc, 0xa75f1fee, 0xd84268e8, 0xa72a44cc}, + {0x07cf6e9e, 0xa16d7b25, 0x9fa7ae6c, 0xd92f5629}, + {0xfeb1eae4, 0x8c8c3ce1, 0x4e0064a7, 0x6a387c2a}, + {0x893a9427, 0xcc3013a2, 0xf106385b, 0xa829f927} +}; + +/* RTMPE type 8 uses XTEA on the regular signature + * http://en.wikipedia.org/wiki/XTEA + */ +static void rtmpe8_sig(uint8_t *in, uint8_t *out, int keyid) +{ + unsigned int i, num_rounds = 32; + uint32_t v0, v1, sum=0, delta=0x9E3779B9; + uint32_t const *k; + + v0 = in[0] | (in[1] << 8) | (in[2] << 16) | (in[3] << 24); + v1 = in[4] | (in[5] << 8) | (in[6] << 16) | (in[7] << 24); + k = rtmpe8_keys[keyid]; + + for (i=0; i < num_rounds; i++) { + v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]); + sum += delta; + v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]); + } + + out[0] = v0; v0 >>= 8; + out[1] = v0; v0 >>= 8; + out[2] = v0; v0 >>= 8; + out[3] = v0; + + out[4] = v1; v1 >>= 8; + out[5] = v1; v1 >>= 8; + out[6] = v1; v1 >>= 8; + out[7] = v1; +} + +/* RTMPE type 9 uses Blowfish on the regular signature + * http://en.wikipedia.org/wiki/Blowfish_(cipher) + */ +#define BF_ROUNDS 16 +typedef struct bf_key { + uint32_t s[4][256]; + uint32_t p[BF_ROUNDS+2]; +} bf_key; + +static const uint32_t bf_sinit[][256] = { + + /* S-Box 0 */ + { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, + 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, + 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, + 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, + 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, + 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, + 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, + 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, + 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, + 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, + 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, + 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, + 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, + 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, + 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, + 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, + 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, + 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, + 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, + 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, + 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, }, + + /* S-Box 1 */ + { 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, + 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, + 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, + 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, + 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, + 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, + 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, + 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, + 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, + 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, + 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, + 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, + 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, + 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, + 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, + 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, + 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, + 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, }, + + /* S-Box 2 */ + { 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, + 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, + 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, + 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, + 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, + 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, + 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, + 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, + 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, + 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, + 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, + 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, + 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, + 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, + 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, + 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, + 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, + 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, + 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, + 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, + 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, }, + + /* S-Box 3 */ + { 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, + 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, + 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, + 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, + 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, + 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, + 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, + 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, + 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, + 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, + 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, + 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, + 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, + 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, + 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, + 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, + 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, + 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, + 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, + 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, + 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, + 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6, }, +}; + +static const uint32_t bf_pinit[] = { + /* P-Box */ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, + 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b, +}; + +#define KEYBYTES 24 + +static const unsigned char rtmpe9_keys[16][KEYBYTES] = { + { 0x79, 0x34, 0x77, 0x4c, 0x67, 0xd1, 0x38, 0x3a, 0xdf, 0xb3, 0x56, 0xbe, + 0x8b, 0x7b, 0xd0, 0x24, 0x38, 0xe0, 0x73, 0x58, 0x41, 0x5d, 0x69, 0x67, }, + { 0x46, 0xf6, 0xb4, 0xcc, 0x01, 0x93, 0xe3, 0xa1, 0x9e, 0x7d, 0x3c, 0x65, + 0x55, 0x86, 0xfd, 0x09, 0x8f, 0xf7, 0xb3, 0xc4, 0x6f, 0x41, 0xca, 0x5c, }, + { 0x1a, 0xe7, 0xe2, 0xf3, 0xf9, 0x14, 0x79, 0x94, 0xc0, 0xd3, 0x97, 0x43, + 0x08, 0x7b, 0xb3, 0x84, 0x43, 0x2f, 0x9d, 0x84, 0x3f, 0x21, 0x01, 0x9b, }, + { 0xd3, 0xe3, 0x54, 0xb0, 0xf7, 0x1d, 0xf6, 0x2b, 0x5a, 0x43, 0x4d, 0x04, + 0x83, 0x64, 0x3e, 0x0d, 0x59, 0x2f, 0x61, 0xcb, 0xb1, 0x6a, 0x59, 0x0d, }, + { 0xc8, 0xc1, 0xe9, 0xb8, 0x16, 0x56, 0x99, 0x21, 0x7b, 0x5b, 0x36, 0xb7, + 0xb5, 0x9b, 0xdf, 0x06, 0x49, 0x2c, 0x97, 0xf5, 0x95, 0x48, 0x85, 0x7e, }, + { 0xeb, 0xe5, 0xe6, 0x2e, 0xa4, 0xba, 0xd4, 0x2c, 0xf2, 0x16, 0xe0, 0x8f, + 0x66, 0x23, 0xa9, 0x43, 0x41, 0xce, 0x38, 0x14, 0x84, 0x95, 0x00, 0x53, }, + { 0x66, 0xdb, 0x90, 0xf0, 0x3b, 0x4f, 0xf5, 0x6f, 0xe4, 0x9c, 0x20, 0x89, + 0x35, 0x5e, 0xd2, 0xb2, 0xc3, 0x9e, 0x9f, 0x7f, 0x63, 0xb2, 0x28, 0x81, }, + { 0xbb, 0x20, 0xac, 0xed, 0x2a, 0x04, 0x6a, 0x19, 0x94, 0x98, 0x9b, 0xc8, + 0xff, 0xcd, 0x93, 0xef, 0xc6, 0x0d, 0x56, 0xa7, 0xeb, 0x13, 0xd9, 0x30, }, + { 0xbc, 0xf2, 0x43, 0x82, 0x09, 0x40, 0x8a, 0x87, 0x25, 0x43, 0x6d, 0xe6, + 0xbb, 0xa4, 0xb9, 0x44, 0x58, 0x3f, 0x21, 0x7c, 0x99, 0xbb, 0x3f, 0x24, }, + { 0xec, 0x1a, 0xaa, 0xcd, 0xce, 0xbd, 0x53, 0x11, 0xd2, 0xfb, 0x83, 0xb6, + 0xc3, 0xba, 0xab, 0x4f, 0x62, 0x79, 0xe8, 0x65, 0xa9, 0x92, 0x28, 0x76, }, + { 0xc6, 0x0c, 0x30, 0x03, 0x91, 0x18, 0x2d, 0x7b, 0x79, 0xda, 0xe1, 0xd5, + 0x64, 0x77, 0x9a, 0x12, 0xc5, 0xb1, 0xd7, 0x91, 0x4f, 0x96, 0x4c, 0xa3, }, + { 0xd7, 0x7c, 0x2a, 0xbf, 0xa6, 0xe7, 0x85, 0x7c, 0x45, 0xad, 0xff, 0x12, + 0x94, 0xd8, 0xde, 0xa4, 0x5c, 0x3d, 0x79, 0xa4, 0x44, 0x02, 0x5d, 0x22, }, + { 0x16, 0x19, 0x0d, 0x81, 0x6a, 0x4c, 0xc7, 0xf8, 0xb8, 0xf9, 0x4e, 0xcd, + 0x2c, 0x9e, 0x90, 0x84, 0xb2, 0x08, 0x25, 0x60, 0xe1, 0x1e, 0xae, 0x18, }, + { 0xe9, 0x7c, 0x58, 0x26, 0x1b, 0x51, 0x9e, 0x49, 0x82, 0x60, 0x61, 0xfc, + 0xa0, 0xa0, 0x1b, 0xcd, 0xf5, 0x05, 0xd6, 0xa6, 0x6d, 0x07, 0x88, 0xa3, }, + { 0x2b, 0x97, 0x11, 0x8b, 0xd9, 0x4e, 0xd9, 0xdf, 0x20, 0xe3, 0x9c, 0x10, + 0xe6, 0xa1, 0x35, 0x21, 0x11, 0xf9, 0x13, 0x0d, 0x0b, 0x24, 0x65, 0xb2, }, + { 0x53, 0x6a, 0x4c, 0x54, 0xac, 0x8b, 0x9b, 0xb8, 0x97, 0x29, 0xfc, 0x60, + 0x2c, 0x5b, 0x3a, 0x85, 0x68, 0xb5, 0xaa, 0x6a, 0x44, 0xcd, 0x3f, 0xa7, }, +}; + +#define BF_ENC(X,S) \ + (((S[0][X>>24] + S[1][X>>16 & 0xff]) ^ S[2][(X>>8) & 0xff]) + S[3][X & 0xff]) + +static void bf_enc(uint32_t *x, bf_key *key) +{ + uint32_t Xl; + uint32_t Xr; + uint32_t temp; + int i; + + Xl = x[0]; + Xr = x[1]; + + for (i = 0; i < BF_ROUNDS; ++i) { + Xl ^= key->p[i]; + Xr ^= BF_ENC(Xl,key->s); + + temp = Xl; + Xl = Xr; + Xr = temp; + } + + Xl ^= key->p[BF_ROUNDS]; + Xr ^= key->p[BF_ROUNDS + 1]; + + x[0] = Xr; + x[1] = Xl; +} + +static void bf_setkey(const unsigned char *kp, int keybytes, bf_key *key) +{ + int i; + int j; + int k; + uint32_t data; + uint32_t d[2]; + + memcpy(key->p, bf_pinit, sizeof(key->p)); + memcpy(key->s, bf_sinit, sizeof(key->s)); + + j = 0; + for (i = 0; i < BF_ROUNDS + 2; ++i) { + data = 0x00000000; + for (k = 0; k < 4; ++k) { + data = (data << 8) | kp[j]; + j = j + 1; + if (j >= keybytes) { + j = 0; + } + } + key->p[i] ^= data; + } + + d[0] = 0x00000000; + d[1] = 0x00000000; + + for (i = 0; i < BF_ROUNDS + 2; i += 2) { + bf_enc(d, key); + + key->p[i] = d[0]; + key->p[i + 1] = d[1]; + } + + for (i = 0; i < 4; ++i) { + for (j = 0; j < 256; j += 2) { + + bf_enc(d, key); + + key->s[i][j] = d[0]; + key->s[i][j + 1] = d[1]; + } + } +} + +static void rtmpe9_sig(uint8_t *in, uint8_t *out, int keyid) +{ + uint32_t d[2]; + bf_key key; + + bf_setkey(rtmpe9_keys[keyid], KEYBYTES, &key); + + /* input is little-endian */ + d[0] = in[0] | (in[1] << 8) | (in[2] << 16) | (in[3] << 24); + d[1] = in[4] | (in[5] << 8) | (in[6] << 16) | (in[7] << 24); + bf_enc(d, &key); + out[0] = d[0] & 0xff; + out[1] = (d[0] >> 8) & 0xff; + out[2] = (d[0] >> 16) & 0xff; + out[3] = (d[0] >> 24) & 0xff; + out[4] = d[1] & 0xff; + out[5] = (d[1] >> 8) & 0xff; + out[6] = (d[1] >> 16) & 0xff; + out[7] = (d[1] >> 24) & 0xff; +} + +static int +HandShake(RTMP * r, int FP9HandShake) +{ + int i, offalg = 0; + int dhposClient = 0; + int digestPosClient = 0; + int encrypted = r->Link.protocol & RTMP_FEATURE_ENC; + + RC4_handle keyIn = 0; + RC4_handle keyOut = 0; + + int32_t *ip; + uint32_t uptime; + + uint8_t clientbuf[RTMP_SIG_SIZE + 4], *clientsig=clientbuf+4; + uint8_t serversig[RTMP_SIG_SIZE], client2[RTMP_SIG_SIZE], *reply; + uint8_t type; + getoff *getdh = NULL, *getdig = NULL; + + if (encrypted || r->Link.SWFSize) + FP9HandShake = TRUE; + else + FP9HandShake = FALSE; + + r->Link.rc4keyIn = r->Link.rc4keyOut = 0; + + if (encrypted) + { + clientsig[-1] = 0x06; /* 0x08 is RTMPE as well */ + offalg = 1; + } + else + clientsig[-1] = 0x03; + + uptime = htonl(RTMP_GetTime()); + memcpy(clientsig, &uptime, 4); + + if (FP9HandShake) + { + /* set version to at least 9.0.115.0 */ + if (encrypted) + { + clientsig[4] = 128; + clientsig[6] = 3; + } + else + { + clientsig[4] = 10; + clientsig[6] = 45; + } + clientsig[5] = 0; + clientsig[7] = 2; + + RTMP_Log(RTMP_LOGDEBUG, "%s: Client type: %02X", __FUNCTION__, clientsig[-1]); + getdig = digoff[offalg]; + getdh = dhoff[offalg]; + } + else + { + memset(&clientsig[4], 0, 4); + } + + /* generate random data */ +#ifdef _DEBUG + memset(clientsig+8, 0, RTMP_SIG_SIZE-8); +#else + ip = (int32_t *)(clientsig+8); + for (i = 2; i < RTMP_SIG_SIZE/4; i++) + *ip++ = rand(); +#endif + + /* set handshake digest */ + if (FP9HandShake) + { + if (encrypted) + { + /* generate Diffie-Hellmann parameters */ + r->Link.dh = DHInit(1024); + if (!r->Link.dh) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't initialize Diffie-Hellmann!", + __FUNCTION__); + return FALSE; + } + + dhposClient = getdh(clientsig, RTMP_SIG_SIZE); + RTMP_Log(RTMP_LOGDEBUG, "%s: DH pubkey position: %d", __FUNCTION__, dhposClient); + + if (!DHGenerateKey(r->Link.dh)) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't generate Diffie-Hellmann public key!", + __FUNCTION__); + return FALSE; + } + + if (!DHGetPublicKey(r->Link.dh, &clientsig[dhposClient], 128)) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't write public key!", __FUNCTION__); + return FALSE; + } + } + + digestPosClient = getdig(clientsig, RTMP_SIG_SIZE); /* reuse this value in verification */ + RTMP_Log(RTMP_LOGDEBUG, "%s: Client digest offset: %d", __FUNCTION__, + digestPosClient); + + CalculateDigest(digestPosClient, clientsig, GenuineFPKey, 30, + &clientsig[digestPosClient]); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Initial client digest: ", __FUNCTION__); + RTMP_LogHex(RTMP_LOGDEBUG, clientsig + digestPosClient, + SHA256_DIGEST_LENGTH); + } + +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, "Clientsig: "); + RTMP_LogHex(RTMP_LOGDEBUG, clientsig, RTMP_SIG_SIZE); +#endif + + if (!WriteN(r, (char *)clientsig-1, RTMP_SIG_SIZE + 1)) + return FALSE; + + if (ReadN(r, (char *)&type, 1) != 1) /* 0x03 or 0x06 */ + return FALSE; + + RTMP_Log(RTMP_LOGDEBUG, "%s: Type Answer : %02X", __FUNCTION__, type); + + if (type != clientsig[-1]) + RTMP_Log(RTMP_LOGWARNING, "%s: Type mismatch: client sent %d, server answered %d", + __FUNCTION__, clientsig[-1], type); + + if (ReadN(r, (char *)serversig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return FALSE; + + /* decode server response */ + memcpy(&uptime, serversig, 4); + uptime = ntohl(uptime); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Server Uptime : %d", __FUNCTION__, uptime); + RTMP_Log(RTMP_LOGDEBUG, "%s: FMS Version : %d.%d.%d.%d", __FUNCTION__, serversig[4], + serversig[5], serversig[6], serversig[7]); + + if (FP9HandShake && type == 3 && !serversig[4]) + FP9HandShake = FALSE; + +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, "Server signature:"); + RTMP_LogHex(RTMP_LOGDEBUG, serversig, RTMP_SIG_SIZE); +#endif + + if (FP9HandShake) + { + uint8_t digestResp[SHA256_DIGEST_LENGTH]; + uint8_t *signatureResp = NULL; + + /* we have to use this signature now to find the correct algorithms for getting the digest and DH positions */ + int digestPosServer = getdig(serversig, RTMP_SIG_SIZE); + + if (!VerifyDigest(digestPosServer, serversig, GenuineFMSKey, 36)) + { + RTMP_Log(RTMP_LOGWARNING, "Trying different position for server digest!"); + offalg ^= 1; + getdig = digoff[offalg]; + getdh = dhoff[offalg]; + digestPosServer = getdig(serversig, RTMP_SIG_SIZE); + + if (!VerifyDigest(digestPosServer, serversig, GenuineFMSKey, 36)) + { + RTMP_Log(RTMP_LOGERROR, "Couldn't verify the server digest"); /* continuing anyway will probably fail */ + return FALSE; + } + } + + /* generate SWFVerification token (SHA256 HMAC hash of decompressed SWF, key are the last 32 bytes of the server handshake) */ + if (r->Link.SWFSize) + { + const char swfVerify[] = { 0x01, 0x01 }; + char *vend = r->Link.SWFVerificationResponse+sizeof(r->Link.SWFVerificationResponse); + + memcpy(r->Link.SWFVerificationResponse, swfVerify, 2); + AMF_EncodeInt32(&r->Link.SWFVerificationResponse[2], vend, r->Link.SWFSize); + AMF_EncodeInt32(&r->Link.SWFVerificationResponse[6], vend, r->Link.SWFSize); + HMACsha256(r->Link.SWFHash, SHA256_DIGEST_LENGTH, + &serversig[RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH], + SHA256_DIGEST_LENGTH, + (uint8_t *)&r->Link.SWFVerificationResponse[10]); + } + + /* do Diffie-Hellmann Key exchange for encrypted RTMP */ + if (encrypted) + { + /* compute secret key */ + uint8_t secretKey[128] = { 0 }; + int len, dhposServer; + + dhposServer = getdh(serversig, RTMP_SIG_SIZE); + RTMP_Log(RTMP_LOGDEBUG, "%s: Server DH public key offset: %d", __FUNCTION__, + dhposServer); + len = DHComputeSharedSecretKey(r->Link.dh, &serversig[dhposServer], + 128, secretKey); + if (len < 0) + { + RTMP_Log(RTMP_LOGDEBUG, "%s: Wrong secret key position!", __FUNCTION__); + return FALSE; + } + + RTMP_Log(RTMP_LOGDEBUG, "%s: Secret key: ", __FUNCTION__); + RTMP_LogHex(RTMP_LOGDEBUG, secretKey, 128); + + InitRC4Encryption(secretKey, + (uint8_t *) & serversig[dhposServer], + (uint8_t *) & clientsig[dhposClient], + &keyIn, &keyOut); + } + + + reply = client2; +#ifdef _DEBUG + memset(reply, 0xff, RTMP_SIG_SIZE); +#else + ip = (int32_t *)reply; + for (i = 0; i < RTMP_SIG_SIZE/4; i++) + *ip++ = rand(); +#endif + /* calculate response now */ + signatureResp = reply+RTMP_SIG_SIZE-SHA256_DIGEST_LENGTH; + + HMACsha256(&serversig[digestPosServer], SHA256_DIGEST_LENGTH, + GenuineFPKey, sizeof(GenuineFPKey), digestResp); + HMACsha256(reply, RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH, digestResp, + SHA256_DIGEST_LENGTH, signatureResp); + + /* some info output */ + RTMP_Log(RTMP_LOGDEBUG, + "%s: Calculated digest key from secure key and server digest: ", + __FUNCTION__); + RTMP_LogHex(RTMP_LOGDEBUG, digestResp, SHA256_DIGEST_LENGTH); + +#ifdef FP10 + if (type == 8 ) + { + uint8_t *dptr = digestResp; + uint8_t *sig = signatureResp; + /* encrypt signatureResp */ + for (i=0; iLink.rc4keyIn = keyIn; + r->Link.rc4keyOut = keyOut; + + + /* update the keystreams */ + if (r->Link.rc4keyIn) + { + RC4_encrypt(r->Link.rc4keyIn, RTMP_SIG_SIZE, (uint8_t *) buff); + } + + if (r->Link.rc4keyOut) + { + RC4_encrypt(r->Link.rc4keyOut, RTMP_SIG_SIZE, (uint8_t *) buff); + } + } + } + else + { + if (memcmp(serversig, clientsig, RTMP_SIG_SIZE) != 0) + { + RTMP_Log(RTMP_LOGWARNING, "%s: client signature does not match!", + __FUNCTION__); + } + } + + RTMP_Log(RTMP_LOGDEBUG, "%s: Handshaking finished....", __FUNCTION__); + return TRUE; +} + +static int +SHandShake(RTMP * r) +{ + int i, offalg = 0; + int dhposServer = 0; + int digestPosServer = 0; + RC4_handle keyIn = 0; + RC4_handle keyOut = 0; + int FP9HandShake = FALSE; + int encrypted; + int32_t *ip; + + uint8_t clientsig[RTMP_SIG_SIZE]; + uint8_t serverbuf[RTMP_SIG_SIZE + 4], *serversig = serverbuf+4; + uint8_t type; + uint32_t uptime; + getoff *getdh = NULL, *getdig = NULL; + + if (ReadN(r, (char *)&type, 1) != 1) /* 0x03 or 0x06 */ + return FALSE; + + if (ReadN(r, (char *)clientsig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return FALSE; + + RTMP_Log(RTMP_LOGDEBUG, "%s: Type Requested : %02X", __FUNCTION__, type); + RTMP_LogHex(RTMP_LOGDEBUG2, clientsig, RTMP_SIG_SIZE); + + if (type == 3) + { + encrypted = FALSE; + } + else if (type == 6 || type == 8) + { + offalg = 1; + encrypted = TRUE; + FP9HandShake = TRUE; + r->Link.protocol |= RTMP_FEATURE_ENC; + /* use FP10 if client is capable */ + if (clientsig[4] == 128) + type = 8; + } + else + { + RTMP_Log(RTMP_LOGERROR, "%s: Unknown version %02x", + __FUNCTION__, type); + return FALSE; + } + + if (!FP9HandShake && clientsig[4]) + FP9HandShake = TRUE; + + serversig[-1] = type; + + r->Link.rc4keyIn = r->Link.rc4keyOut = 0; + + uptime = htonl(RTMP_GetTime()); + memcpy(serversig, &uptime, 4); + + if (FP9HandShake) + { + /* Server version */ + serversig[4] = 3; + serversig[5] = 5; + serversig[6] = 1; + serversig[7] = 1; + + getdig = digoff[offalg]; + getdh = dhoff[offalg]; + } + else + { + memset(&serversig[4], 0, 4); + } + + /* generate random data */ +#ifdef _DEBUG + memset(serversig+8, 0, RTMP_SIG_SIZE-8); +#else + ip = (int32_t *)(serversig+8); + for (i = 2; i < RTMP_SIG_SIZE/4; i++) + *ip++ = rand(); +#endif + + /* set handshake digest */ + if (FP9HandShake) + { + if (encrypted) + { + /* generate Diffie-Hellmann parameters */ + r->Link.dh = DHInit(1024); + if (!r->Link.dh) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't initialize Diffie-Hellmann!", + __FUNCTION__); + return FALSE; + } + + dhposServer = getdh(serversig, RTMP_SIG_SIZE); + RTMP_Log(RTMP_LOGDEBUG, "%s: DH pubkey position: %d", __FUNCTION__, dhposServer); + + if (!DHGenerateKey(r->Link.dh)) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't generate Diffie-Hellmann public key!", + __FUNCTION__); + return FALSE; + } + + if (!DHGetPublicKey + (r->Link.dh, (uint8_t *) &serversig[dhposServer], 128)) + { + RTMP_Log(RTMP_LOGERROR, "%s: Couldn't write public key!", __FUNCTION__); + return FALSE; + } + } + + digestPosServer = getdig(serversig, RTMP_SIG_SIZE); /* reuse this value in verification */ + RTMP_Log(RTMP_LOGDEBUG, "%s: Server digest offset: %d", __FUNCTION__, + digestPosServer); + + CalculateDigest(digestPosServer, serversig, GenuineFMSKey, 36, + &serversig[digestPosServer]); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Initial server digest: ", __FUNCTION__); + RTMP_LogHex(RTMP_LOGDEBUG, serversig + digestPosServer, + SHA256_DIGEST_LENGTH); + } + + RTMP_Log(RTMP_LOGDEBUG2, "Serversig: "); + RTMP_LogHex(RTMP_LOGDEBUG2, serversig, RTMP_SIG_SIZE); + + if (!WriteN(r, (char *)serversig-1, RTMP_SIG_SIZE + 1)) + return FALSE; + + /* decode client response */ + memcpy(&uptime, clientsig, 4); + uptime = ntohl(uptime); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Client Uptime : %d", __FUNCTION__, uptime); + RTMP_Log(RTMP_LOGDEBUG, "%s: Player Version: %d.%d.%d.%d", __FUNCTION__, clientsig[4], + clientsig[5], clientsig[6], clientsig[7]); + + if (FP9HandShake) + { + uint8_t digestResp[SHA256_DIGEST_LENGTH]; + uint8_t *signatureResp = NULL; + + /* we have to use this signature now to find the correct algorithms for getting the digest and DH positions */ + int digestPosClient = getdig(clientsig, RTMP_SIG_SIZE); + + if (!VerifyDigest(digestPosClient, clientsig, GenuineFPKey, 30)) + { + RTMP_Log(RTMP_LOGWARNING, "Trying different position for client digest!"); + offalg ^= 1; + getdig = digoff[offalg]; + getdh = dhoff[offalg]; + + digestPosClient = getdig(clientsig, RTMP_SIG_SIZE); + + if (!VerifyDigest(digestPosClient, clientsig, GenuineFPKey, 30)) + { + RTMP_Log(RTMP_LOGERROR, "Couldn't verify the client digest"); /* continuing anyway will probably fail */ + return FALSE; + } + } + + /* generate SWFVerification token (SHA256 HMAC hash of decompressed SWF, key are the last 32 bytes of the server handshake) */ + if (r->Link.SWFSize) + { + const char swfVerify[] = { 0x01, 0x01 }; + char *vend = r->Link.SWFVerificationResponse+sizeof(r->Link.SWFVerificationResponse); + + memcpy(r->Link.SWFVerificationResponse, swfVerify, 2); + AMF_EncodeInt32(&r->Link.SWFVerificationResponse[2], vend, r->Link.SWFSize); + AMF_EncodeInt32(&r->Link.SWFVerificationResponse[6], vend, r->Link.SWFSize); + HMACsha256(r->Link.SWFHash, SHA256_DIGEST_LENGTH, + &serversig[RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH], + SHA256_DIGEST_LENGTH, + (uint8_t *)&r->Link.SWFVerificationResponse[10]); + } + + /* do Diffie-Hellmann Key exchange for encrypted RTMP */ + if (encrypted) + { + int dhposClient, len; + /* compute secret key */ + uint8_t secretKey[128] = { 0 }; + + dhposClient = getdh(clientsig, RTMP_SIG_SIZE); + RTMP_Log(RTMP_LOGDEBUG, "%s: Client DH public key offset: %d", __FUNCTION__, + dhposClient); + len = + DHComputeSharedSecretKey(r->Link.dh, + (uint8_t *) &clientsig[dhposClient], 128, + secretKey); + if (len < 0) + { + RTMP_Log(RTMP_LOGDEBUG, "%s: Wrong secret key position!", __FUNCTION__); + return FALSE; + } + + RTMP_Log(RTMP_LOGDEBUG, "%s: Secret key: ", __FUNCTION__); + RTMP_LogHex(RTMP_LOGDEBUG, secretKey, 128); + + InitRC4Encryption(secretKey, + (uint8_t *) &clientsig[dhposClient], + (uint8_t *) &serversig[dhposServer], + &keyIn, &keyOut); + } + + + /* calculate response now */ + signatureResp = clientsig+RTMP_SIG_SIZE-SHA256_DIGEST_LENGTH; + + HMACsha256(&clientsig[digestPosClient], SHA256_DIGEST_LENGTH, + GenuineFMSKey, sizeof(GenuineFMSKey), digestResp); + HMACsha256(clientsig, RTMP_SIG_SIZE - SHA256_DIGEST_LENGTH, digestResp, + SHA256_DIGEST_LENGTH, signatureResp); +#ifdef FP10 + if (type == 8 ) + { + uint8_t *dptr = digestResp; + uint8_t *sig = signatureResp; + /* encrypt signatureResp */ + for (i=0; iLink.rc4keyIn = keyIn; + r->Link.rc4keyOut = keyOut; + + /* update the keystreams */ + if (r->Link.rc4keyIn) + { + RC4_encrypt(r->Link.rc4keyIn, RTMP_SIG_SIZE, (uint8_t *) buff); + } + + if (r->Link.rc4keyOut) + { + RC4_encrypt(r->Link.rc4keyOut, RTMP_SIG_SIZE, (uint8_t *) buff); + } + } + } + else + { + if (memcmp(serversig, clientsig, RTMP_SIG_SIZE) != 0) + { + RTMP_Log(RTMP_LOGWARNING, "%s: client signature does not match!", + __FUNCTION__); + } + } + + RTMP_Log(RTMP_LOGDEBUG, "%s: Handshaking finished....", __FUNCTION__); + return TRUE; +} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/hashswf.c b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/hashswf.c new file mode 100644 index 0000000..9f4e2c0 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/hashswf.c @@ -0,0 +1,665 @@ +/* + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include +#include +#include +#include + +#include "rtmp_sys.h" +#include "log.h" +#include "http.h" + +#ifdef CRYPTO +#ifdef USE_POLARSSL +#include +#ifndef SHA256_DIGEST_LENGTH +#define SHA256_DIGEST_LENGTH 32 +#endif +#define HMAC_CTX sha2_context +#define HMAC_setup(ctx, key, len) sha2_hmac_starts(&ctx, (unsigned char *)key, len, 0) +#define HMAC_crunch(ctx, buf, len) sha2_hmac_update(&ctx, buf, len) +#define HMAC_finish(ctx, dig, dlen) dlen = SHA256_DIGEST_LENGTH; sha2_hmac_finish(&ctx, dig) +#define HMAC_close(ctx) +#elif defined(USE_GNUTLS) +#include +#ifndef SHA256_DIGEST_LENGTH +#define SHA256_DIGEST_LENGTH 32 +#endif +#undef HMAC_CTX +#define HMAC_CTX struct hmac_sha256_ctx +#define HMAC_setup(ctx, key, len) hmac_sha256_set_key(&ctx, len, key) +#define HMAC_crunch(ctx, buf, len) hmac_sha256_update(&ctx, len, buf) +#define HMAC_finish(ctx, dig, dlen) dlen = SHA256_DIGEST_LENGTH; hmac_sha256_digest(&ctx, SHA256_DIGEST_LENGTH, dig) +#define HMAC_close(ctx) +#else /* USE_OPENSSL */ +#include +#include +#include +#include +#define HMAC_setup(ctx, key, len) HMAC_CTX_init(&ctx); HMAC_Init_ex(&ctx, (unsigned char *)key, len, EVP_sha256(), 0) +#define HMAC_crunch(ctx, buf, len) HMAC_Update(&ctx, (unsigned char *)buf, len) +#define HMAC_finish(ctx, dig, dlen) HMAC_Final(&ctx, (unsigned char *)dig, &dlen); +#define HMAC_close(ctx) HMAC_CTX_cleanup(&ctx) +#endif + +extern void RTMP_TLS_Init(); +extern TLS_CTX RTMP_TLS_ctx; + +#include + +#endif /* CRYPTO */ + +#define AGENT "Mozilla/5.0" + +HTTPResult +HTTP_get(struct HTTP_ctx *http, const char *url, HTTP_read_callback *cb) +{ + char *host, *path; + char *p1, *p2; + char hbuf[256]; + int port = 80; +#ifdef CRYPTO + int ssl = 0; +#endif + int hlen, flen = 0; + int rc, i; + int len_known; + HTTPResult ret = HTTPRES_OK; + struct sockaddr_in sa; + RTMPSockBuf sb = {0}; + + http->status = -1; + + memset(&sa, 0, sizeof(struct sockaddr_in)); + sa.sin_family = AF_INET; + + /* we only handle http here */ + if (strncasecmp(url, "http", 4)) + return HTTPRES_BAD_REQUEST; + + if (url[4] == 's') + { +#ifdef CRYPTO + ssl = 1; + port = 443; + if (!RTMP_TLS_ctx) + RTMP_TLS_Init(); +#else + return HTTPRES_BAD_REQUEST; +#endif + } + + p1 = strchr(url + 4, ':'); + if (!p1 || strncmp(p1, "://", 3)) + return HTTPRES_BAD_REQUEST; + + host = p1 + 3; + path = strchr(host, '/'); + hlen = path - host; + strncpy(hbuf, host, hlen); + hbuf[hlen] = '\0'; + host = hbuf; + p1 = strrchr(host, ':'); + if (p1) + { + *p1++ = '\0'; + port = atoi(p1); + } + + sa.sin_addr.s_addr = inet_addr(host); + if (sa.sin_addr.s_addr == INADDR_NONE) + { + struct hostent *hp = gethostbyname(host); + if (!hp || !hp->h_addr) + return HTTPRES_LOST_CONNECTION; + sa.sin_addr = *(struct in_addr *)hp->h_addr; + } + sa.sin_port = htons(port); + sb.sb_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (sb.sb_socket == -1) + return HTTPRES_LOST_CONNECTION; + i = + sprintf(sb.sb_buf, + "GET %s HTTP/1.0\r\nUser-Agent: %s\r\nHost: %s\r\nReferer: %.*s\r\n", + path, AGENT, host, (int)(path - url + 1), url); + if (http->date[0]) + i += sprintf(sb.sb_buf + i, "If-Modified-Since: %s\r\n", http->date); + i += sprintf(sb.sb_buf + i, "\r\n"); + + if (connect + (sb.sb_socket, (struct sockaddr *)&sa, sizeof(struct sockaddr)) < 0) + { + ret = HTTPRES_LOST_CONNECTION; + goto leave; + } +#ifdef CRYPTO + if (ssl) + { +#ifdef NO_SSL + RTMP_Log(RTMP_LOGERROR, "%s, No SSL/TLS support", __FUNCTION__); + ret = HTTPRES_BAD_REQUEST; + goto leave; +#else + TLS_client(RTMP_TLS_ctx, sb.sb_ssl); + TLS_setfd(sb.sb_ssl, sb.sb_socket); + if (TLS_connect(sb.sb_ssl) < 0) + { + RTMP_Log(RTMP_LOGERROR, "%s, TLS_Connect failed", __FUNCTION__); + ret = HTTPRES_LOST_CONNECTION; + goto leave; + } +#endif + } +#endif + RTMPSockBuf_Send(&sb, sb.sb_buf, i); + + /* set timeout */ +#define HTTP_TIMEOUT 5 + { + SET_RCVTIMEO(tv, HTTP_TIMEOUT); + if (setsockopt + (sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv))) + { + RTMP_Log(RTMP_LOGERROR, "%s, Setting socket timeout to %ds failed!", + __FUNCTION__, HTTP_TIMEOUT); + } + } + + sb.sb_size = 0; + sb.sb_timedout = FALSE; + if (RTMPSockBuf_Fill(&sb) < 1) + { + ret = HTTPRES_LOST_CONNECTION; + goto leave; + } + if (strncmp(sb.sb_buf, "HTTP/1", 6)) + { + ret = HTTPRES_BAD_REQUEST; + goto leave; + } + + p1 = strchr(sb.sb_buf, ' '); + rc = atoi(p1 + 1); + http->status = rc; + + if (rc >= 300) + { + if (rc == 304) + { + ret = HTTPRES_OK_NOT_MODIFIED; + goto leave; + } + else if (rc == 404) + ret = HTTPRES_NOT_FOUND; + else if (rc >= 500) + ret = HTTPRES_SERVER_ERROR; + else if (rc >= 400) + ret = HTTPRES_BAD_REQUEST; + else + ret = HTTPRES_REDIRECTED; + } + + p1 = memchr(sb.sb_buf, '\n', sb.sb_size); + if (!p1) + { + ret = HTTPRES_BAD_REQUEST; + goto leave; + } + sb.sb_start = p1 + 1; + sb.sb_size -= sb.sb_start - sb.sb_buf; + + while ((p2 = memchr(sb.sb_start, '\r', sb.sb_size))) + { + if (*sb.sb_start == '\r') + { + sb.sb_start += 2; + sb.sb_size -= 2; + break; + } + else + if (!strncasecmp + (sb.sb_start, "Content-Length: ", sizeof("Content-Length: ") - 1)) + { + flen = atoi(sb.sb_start + sizeof("Content-Length: ") - 1); + } + else + if (!strncasecmp + (sb.sb_start, "Last-Modified: ", sizeof("Last-Modified: ") - 1)) + { + *p2 = '\0'; + strcpy(http->date, sb.sb_start + sizeof("Last-Modified: ") - 1); + } + p2 += 2; + sb.sb_size -= p2 - sb.sb_start; + sb.sb_start = p2; + if (sb.sb_size < 1) + { + if (RTMPSockBuf_Fill(&sb) < 1) + { + ret = HTTPRES_LOST_CONNECTION; + goto leave; + } + } + } + + len_known = flen > 0; + while ((!len_known || flen > 0) && + (sb.sb_size > 0 || RTMPSockBuf_Fill(&sb) > 0)) + { + cb(sb.sb_start, 1, sb.sb_size, http->data); + if (len_known) + flen -= sb.sb_size; + http->size += sb.sb_size; + sb.sb_size = 0; + } + + if (flen > 0) + ret = HTTPRES_LOST_CONNECTION; + +leave: + RTMPSockBuf_Close(&sb); + return ret; +} + +#ifdef CRYPTO + +#define CHUNK 16384 + +struct info +{ + z_stream *zs; + HMAC_CTX ctx; + int first; + int zlib; + int size; +}; + +static size_t +swfcrunch(void *ptr, size_t size, size_t nmemb, void *stream) +{ + struct info *i = stream; + char *p = ptr; + size_t len = size * nmemb; + + if (i->first) + { + i->first = 0; + /* compressed? */ + if (!strncmp(p, "CWS", 3)) + { + *p = 'F'; + i->zlib = 1; + } + HMAC_crunch(i->ctx, (unsigned char *)p, 8); + p += 8; + len -= 8; + i->size = 8; + } + + if (i->zlib) + { + unsigned char out[CHUNK]; + i->zs->next_in = (unsigned char *)p; + i->zs->avail_in = len; + do + { + i->zs->avail_out = CHUNK; + i->zs->next_out = out; + inflate(i->zs, Z_NO_FLUSH); + len = CHUNK - i->zs->avail_out; + i->size += len; + HMAC_crunch(i->ctx, out, len); + } + while (i->zs->avail_out == 0); + } + else + { + i->size += len; + HMAC_crunch(i->ctx, (unsigned char *)p, len); + } + return size * nmemb; +} + +static int tzoff; +static int tzchecked; + +#define JAN02_1980 318340800 + +static const char *monthtab[12] = { "Jan", "Feb", "Mar", + "Apr", "May", "Jun", + "Jul", "Aug", "Sep", + "Oct", "Nov", "Dec" +}; +static const char *days[] = + { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; + +/* Parse an HTTP datestamp into Unix time */ +static time_t +make_unix_time(char *s) +{ + struct tm time; + int i, ysub = 1900, fmt = 0; + char *month; + char *n; + time_t res; + + if (s[3] != ' ') + { + fmt = 1; + if (s[3] != ',') + ysub = 0; + } + for (n = s; *n; ++n) + if (*n == '-' || *n == ':') + *n = ' '; + + time.tm_mon = 0; + n = strchr(s, ' '); + if (fmt) + { + /* Day, DD-MMM-YYYY HH:MM:SS GMT */ + time.tm_mday = strtol(n + 1, &n, 0); + month = n + 1; + n = strchr(month, ' '); + time.tm_year = strtol(n + 1, &n, 0); + time.tm_hour = strtol(n + 1, &n, 0); + time.tm_min = strtol(n + 1, &n, 0); + time.tm_sec = strtol(n + 1, NULL, 0); + } + else + { + /* Unix ctime() format. Does not conform to HTTP spec. */ + /* Day MMM DD HH:MM:SS YYYY */ + month = n + 1; + n = strchr(month, ' '); + while (isspace(*n)) + n++; + time.tm_mday = strtol(n, &n, 0); + time.tm_hour = strtol(n + 1, &n, 0); + time.tm_min = strtol(n + 1, &n, 0); + time.tm_sec = strtol(n + 1, &n, 0); + time.tm_year = strtol(n + 1, NULL, 0); + } + if (time.tm_year > 100) + time.tm_year -= ysub; + + for (i = 0; i < 12; i++) + if (!strncasecmp(month, monthtab[i], 3)) + { + time.tm_mon = i; + break; + } + time.tm_isdst = 0; /* daylight saving is never in effect in GMT */ + + /* this is normally the value of extern int timezone, but some + * braindead C libraries don't provide it. + */ + if (!tzchecked) + { + struct tm *tc; + time_t then = JAN02_1980; + tc = localtime(&then); + tzoff = (12 - tc->tm_hour) * 3600 + tc->tm_min * 60 + tc->tm_sec; + tzchecked = 1; + } + res = mktime(&time); + /* Unfortunately, mktime() assumes the input is in local time, + * not GMT, so we have to correct it here. + */ + if (res != -1) + res += tzoff; + return res; +} + +/* Convert a Unix time to a network time string + * Weekday, DD-MMM-YYYY HH:MM:SS GMT + */ +static void +strtime(time_t * t, char *s) +{ + struct tm *tm; + + tm = gmtime((time_t *) t); + sprintf(s, "%s, %02d %s %d %02d:%02d:%02d GMT", + days[tm->tm_wday], tm->tm_mday, monthtab[tm->tm_mon], + tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); +} + +#define HEX2BIN(a) (((a)&0x40)?((a)&0xf)+9:((a)&0xf)) + +int +RTMP_HashSWF(const char *url, unsigned int *size, unsigned char *hash, + int age) +{ + FILE *f = NULL; + char *path, date[64], cctim[64]; + long pos = 0; + time_t ctim = -1, cnow; + int i, got = 0, ret = 0; + unsigned int hlen; + struct info in = { 0 }; + struct HTTP_ctx http = { 0 }; + HTTPResult httpres; + z_stream zs = { 0 }; + AVal home, hpre; + + date[0] = '\0'; +#ifdef _WIN32 +#ifdef XBMC4XBOX + hpre.av_val = "Q:"; + hpre.av_len = 2; + home.av_val = "\\UserData"; +#else + hpre.av_val = getenv("HOMEDRIVE"); + hpre.av_len = strlen(hpre.av_val); + home.av_val = getenv("HOMEPATH"); +#endif +#define DIRSEP "\\" + +#else /* !_WIN32 */ + hpre.av_val = ""; + hpre.av_len = 0; + home.av_val = getenv("HOME"); +#define DIRSEP "/" +#endif + if (!home.av_val) + home.av_val = "."; + home.av_len = strlen(home.av_val); + + /* SWF hash info is cached in a fixed-format file. + * url: + * ctim: HTTP datestamp of when we last checked it. + * date: HTTP datestamp of the SWF's last modification. + * size: SWF size in hex + * hash: SWF hash in hex + * + * These fields must be present in this order. All fields + * besides URL are fixed size. + */ + path = malloc(hpre.av_len + home.av_len + sizeof(DIRSEP ".swfinfo")); + sprintf(path, "%s%s" DIRSEP ".swfinfo", hpre.av_val, home.av_val); + + f = fopen(path, "r+"); + while (f) + { + char buf[4096], *file, *p; + + file = strchr(url, '/'); + if (!file) + break; + file += 2; + file = strchr(file, '/'); + if (!file) + break; + file++; + hlen = file - url; + p = strrchr(file, '/'); + if (p) + file = p; + else + file--; + + while (fgets(buf, sizeof(buf), f)) + { + char *r1; + + got = 0; + + if (strncmp(buf, "url: ", 5)) + continue; + if (strncmp(buf + 5, url, hlen)) + continue; + r1 = strrchr(buf, '/'); + i = strlen(r1); + r1[--i] = '\0'; + if (strncmp(r1, file, i)) + continue; + pos = ftell(f); + while (got < 4 && fgets(buf, sizeof(buf), f)) + { + if (!strncmp(buf, "size: ", 6)) + { + *size = strtol(buf + 6, NULL, 16); + got++; + } + else if (!strncmp(buf, "hash: ", 6)) + { + unsigned char *ptr = hash, *in = (unsigned char *)buf + 6; + int l = strlen((char *)in) - 1; + for (i = 0; i < l; i += 2) + *ptr++ = (HEX2BIN(in[i]) << 4) | HEX2BIN(in[i + 1]); + got++; + } + else if (!strncmp(buf, "date: ", 6)) + { + buf[strlen(buf) - 1] = '\0'; + strncpy(date, buf + 6, sizeof(date)); + got++; + } + else if (!strncmp(buf, "ctim: ", 6)) + { + buf[strlen(buf) - 1] = '\0'; + ctim = make_unix_time(buf + 6); + got++; + } + else if (!strncmp(buf, "url: ", 5)) + break; + } + break; + } + break; + } + + cnow = time(NULL); + /* If we got a cache time, see if it's young enough to use directly */ + if (age && ctim > 0) + { + ctim = cnow - ctim; + ctim /= 3600 * 24; /* seconds to days */ + if (ctim < age) /* ok, it's new enough */ + goto out; + } + + in.first = 1; + HMAC_setup(in.ctx, "Genuine Adobe Flash Player 001", 30); + inflateInit(&zs); + in.zs = &zs; + + http.date = date; + http.data = ∈ + + httpres = HTTP_get(&http, url, swfcrunch); + + inflateEnd(&zs); + + if (httpres != HTTPRES_OK && httpres != HTTPRES_OK_NOT_MODIFIED) + { + ret = -1; + if (httpres == HTTPRES_LOST_CONNECTION) + RTMP_Log(RTMP_LOGERROR, "%s: connection lost while downloading swfurl %s", + __FUNCTION__, url); + else if (httpres == HTTPRES_NOT_FOUND) + RTMP_Log(RTMP_LOGERROR, "%s: swfurl %s not found", __FUNCTION__, url); + else + RTMP_Log(RTMP_LOGERROR, "%s: couldn't contact swfurl %s (HTTP error %d)", + __FUNCTION__, url, http.status); + } + else + { + if (got && pos) + fseek(f, pos, SEEK_SET); + else + { + char *q; + if (!f) + f = fopen(path, "w"); + if (!f) + { + int err = errno; + RTMP_Log(RTMP_LOGERROR, + "%s: couldn't open %s for writing, errno %d (%s)", + __FUNCTION__, path, err, strerror(err)); + ret = -1; + goto out; + } + fseek(f, 0, SEEK_END); + q = strchr(url, '?'); + if (q) + i = q - url; + else + i = strlen(url); + + fprintf(f, "url: %.*s\n", i, url); + } + strtime(&cnow, cctim); + fprintf(f, "ctim: %s\n", cctim); + + if (!in.first) + { + HMAC_finish(in.ctx, hash, hlen); + *size = in.size; + + fprintf(f, "date: %s\n", date); + fprintf(f, "size: %08x\n", in.size); + fprintf(f, "hash: "); + for (i = 0; i < SHA256_DIGEST_LENGTH; i++) + fprintf(f, "%02x", hash[i]); + fprintf(f, "\n"); + } + } + HMAC_close(in.ctx); +out: + free(path); + if (f) + fclose(f); + return ret; +} +#else +int +RTMP_HashSWF(const char *url, unsigned int *size, unsigned char *hash, + int age) +{ + return -1; +} +#endif diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/http.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/http.h new file mode 100644 index 0000000..cf3d903 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/http.h @@ -0,0 +1,47 @@ +#ifndef __RTMP_HTTP_H__ +#define __RTMP_HTTP_H__ +/* + * Copyright (C) 2010 Howard Chu + * Copyright (C) 2010 Antti Ajanki + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +typedef enum { + HTTPRES_OK, /* result OK */ + HTTPRES_OK_NOT_MODIFIED, /* not modified since last request */ + HTTPRES_NOT_FOUND, /* not found */ + HTTPRES_BAD_REQUEST, /* client error */ + HTTPRES_SERVER_ERROR, /* server reported an error */ + HTTPRES_REDIRECTED, /* resource has been moved */ + HTTPRES_LOST_CONNECTION /* connection lost while waiting for data */ +} HTTPResult; + +struct HTTP_ctx { + char *date; + int size; + int status; + void *data; +}; + +typedef size_t (HTTP_read_callback)(void *ptr, size_t size, size_t nmemb, void *stream); + +HTTPResult HTTP_get(struct HTTP_ctx *http, const char *url, HTTP_read_callback *cb); + +#endif diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/librtmp.3 b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/librtmp.3 new file mode 100644 index 0000000..7c424aa --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/librtmp.3 @@ -0,0 +1,210 @@ +.TH LIBRTMP 3 "2011-07-20" "RTMPDump v2.4" +.\" Copyright 2011 Howard Chu. +.\" Copying permitted according to the GNU General Public License V2. +.SH NAME +librtmp \- RTMPDump Real-Time Messaging Protocol API +.SH LIBRARY +RTMPDump RTMP (librtmp, -lrtmp) +.SH SYNOPSIS +.B #include +.SH DESCRIPTION +The Real-Time Messaging Protocol (RTMP) is used for streaming +multimedia content across a TCP/IP network. This API provides most client +functions and a few server functions needed to support RTMP, RTMP tunneled +in HTTP (RTMPT), encrypted RTMP (RTMPE), RTMP over SSL/TLS (RTMPS) and +tunneled variants of these encrypted types (RTMPTE, RTMPTS). The basic +RTMP specification has been published by Adobe but this API was +reverse-engineered without use of the Adobe specification. As such, it may +deviate from any published specifications but it usually duplicates the +actual behavior of the original Adobe clients. + +The RTMPDump software package includes a basic client utility program +in +.BR rtmpdump (1), +some sample servers, and a library used to provide programmatic access +to the RTMP protocol. This man page gives an overview of the RTMP +library routines. These routines are found in the -lrtmp library. Many +other routines are also available, but they are not documented yet. + +The basic interaction is as follows. A session handle is created using +.BR RTMP_Alloc () +and initialized using +.BR RTMP_Init (). +All session parameters are provided using +.BR RTMP_SetupURL (). +The network connection is established using +.BR RTMP_Connect (), +and then the RTMP session is established using +.BR RTMP_ConnectStream (). +The stream is read using +.BR RTMP_Read (). +A client can publish a stream by calling +.BR RTMP_EnableWrite () +before the +.BR RTMP_Connect () +call, and then using +.BR RTMP_Write () +after the session is established. +While a stream is playing it may be paused and unpaused using +.BR RTMP_Pause (). +The stream playback position can be moved using +.BR RTMP_Seek (). +When +.BR RTMP_Read () +returns 0 bytes, the stream is complete and may be closed using +.BR RTMP_Close (). +The session handle is freed using +.BR RTMP_Free (). + +All data is transferred using FLV format. The basic session requires +an RTMP URL. The RTMP URL format is of the form +.nf + rtmp[t][e|s]://hostname[:port][/app[/playpath]] +.fi + +Plain rtmp, as well as tunneled and encrypted sessions are supported. + +Additional options may be specified by appending space-separated +key=value pairs to the URL. Special characters in values may need +to be escaped to prevent misinterpretation by the option parser. +The escape encoding uses a backslash followed by two hexadecimal digits +representing the ASCII value of the character. E.g., spaces must +be escaped as \fB\\20\fP and backslashes must be escaped as \fB\\5c\fP. +.SH OPTIONS +.SS "Network Parameters" +These options define how to connect to the media server. +.TP +.BI socks= host:port +Use the specified SOCKS4 proxy. +.SS "Connection Parameters" +These options define the content of the RTMP Connect request packet. +If correct values are not provided, the media server will reject the +connection attempt. +.TP +.BI app= name +Name of application to connect to on the RTMP server. Overrides +the app in the RTMP URL. Sometimes the librtmp URL parser cannot +determine the app name automatically, so it must be given explicitly +using this option. +.TP +.BI tcUrl= url +URL of the target stream. Defaults to rtmp[t][e|s]://host[:port]/app. +.TP +.BI pageUrl= url +URL of the web page in which the media was embedded. By default no +value will be sent. +.TP +.BI swfUrl= url +URL of the SWF player for the media. By default no value will be sent. +.TP +.BI flashVer= version +Version of the Flash plugin used to run the SWF player. The +default is "LNX 10,0,32,18". +.TP +.BI conn= type:data +Append arbitrary AMF data to the Connect message. The type +must be B for Boolean, N for number, S for string, O for object, or Z +for null. For Booleans the data must be either 0 or 1 for FALSE or TRUE, +respectively. Likewise for Objects the data must be 0 or 1 to end or +begin an object, respectively. Data items in subobjects may be named, by +prefixing the type with 'N' and specifying the name before the value, e.g. +NB:myFlag:1. This option may be used multiple times to construct arbitrary +AMF sequences. E.g. +.nf + conn=B:1 conn=S:authMe conn=O:1 conn=NN:code:1.23 conn=NS:flag:ok conn=O:0 +.fi +.SS "Session Parameters" +These options take effect after the Connect request has succeeded. +.TP +.BI playpath= path +Overrides the playpath parsed from the RTMP URL. Sometimes the +rtmpdump URL parser cannot determine the correct playpath +automatically, so it must be given explicitly using this option. +.TP +.BI playlist= 0|1 +If the value is 1 or TRUE, issue a set_playlist command before sending the +play command. The playlist will just contain the current playpath. If the +value is 0 or FALSE, the set_playlist command will not be sent. The +default is FALSE. +.TP +.BI live= 0|1 +Specify that the media is a live stream. No resuming or seeking in +live streams is possible. +.TP +.BI subscribe= path +Name of live stream to subscribe to. Defaults to +.IR playpath . +.TP +.BI start= num +Start at +.I num +seconds into the stream. Not valid for live streams. +.TP +.BI stop= num +Stop at +.I num +seconds into the stream. +.TP +.BI buffer= num +Set buffer time to +.I num +milliseconds. The default is 30000. +.TP +.BI timeout= num +Timeout the session after +.I num +seconds without receiving any data from the server. The default is 120. +.SS "Security Parameters" +These options handle additional authentication requests from the server. +.TP +.BI token= key +Key for SecureToken response, used if the server requires SecureToken +authentication. +.TP +.BI jtv= JSON +JSON token used by legacy Justin.tv servers. Invokes NetStream.Authenticate.UsherToken +.TP +.BI swfVfy= 0|1 +If the value is 1 or TRUE, the SWF player is retrieved from the +specified +.I swfUrl +for performing SWF Verification. The SWF hash and size (used in the +verification step) are computed automatically. Also the SWF information is +cached in a +.I .swfinfo +file in the user's home directory, so that it doesn't need to be retrieved +and recalculated every time. The .swfinfo file records +the SWF URL, the time it was fetched, the modification timestamp of the SWF +file, its size, and its hash. By default, the cached info will be used +for 30 days before re-checking. +.TP +.BI swfAge= days +Specify how many days to use the cached SWF info before re-checking. Use +0 to always check the SWF URL. Note that if the check shows that the +SWF file has the same modification timestamp as before, it will not be +retrieved again. +.SH EXAMPLES +An example character string suitable for use with +.BR RTMP_SetupURL (): +.nf + "rtmp://flashserver:1935/ondemand/thefile swfUrl=http://flashserver/player.swf swfVfy=1" +.fi +.SH ENVIRONMENT +.TP +.B HOME +The value of +.RB $ HOME +is used as the location for the +.I .swfinfo +file. +.SH FILES +.TP +.I $HOME/.swfinfo +Cache of SWF Verification information +.SH "SEE ALSO" +.BR rtmpdump (1), +.BR rtmpgw (8) +.SH AUTHORS +Andrej Stepanchuk, Howard Chu, The Flvstreamer Team +.br + diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/librtmp.3.html b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/librtmp.3.html new file mode 100644 index 0000000..6f59851 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/librtmp.3.html @@ -0,0 +1,312 @@ + + +LIBRTMP(3): + + + + + +
LIBRTMP(3)LIBRTMP(3) +
RTMPDump v2.42011-07-20LIBRTMP(3) +


    + +
+ +

NAME

    +librtmp − RTMPDump Real-Time Messaging Protocol API +
+ +

LIBRARY

    +RTMPDump RTMP (librtmp, -lrtmp) +
+ +

SYNOPSIS

    +#include <librtmp/rtmp.h> +
+ +

DESCRIPTION

    +The Real-Time Messaging Protocol (RTMP) is used for streaming +multimedia content across a TCP/IP network. This API provides most client +functions and a few server functions needed to support RTMP, RTMP tunneled +in HTTP (RTMPT), encrypted RTMP (RTMPE), RTMP over SSL/TLS (RTMPS) and +tunneled variants of these encrypted types (RTMPTE, RTMPTS). The basic +RTMP specification has been published by Adobe but this API was +reverse-engineered without use of the Adobe specification. As such, it may +deviate from any published specifications but it usually duplicates the +actual behavior of the original Adobe clients. +

    +The RTMPDump software package includes a basic client utility program +in +rtmpdump(1), +some sample servers, and a library used to provide programmatic access +to the RTMP protocol. This man page gives an overview of the RTMP +library routines. These routines are found in the -lrtmp library. Many +other routines are also available, but they are not documented yet. +

    +The basic interaction is as follows. A session handle is created using +RTMP_Alloc() +and initialized using +RTMP_Init(). +All session parameters are provided using +RTMP_SetupURL(). +The network connection is established using +RTMP_Connect(), +and then the RTMP session is established using +RTMP_ConnectStream(). +The stream is read using +RTMP_Read(). +A client can publish a stream by calling +RTMP_EnableWrite() +before the +RTMP_Connect() +call, and then using +RTMP_Write() +after the session is established. +While a stream is playing it may be paused and unpaused using +RTMP_Pause(). +The stream playback position can be moved using +RTMP_Seek(). +When +RTMP_Read() +returns 0 bytes, the stream is complete and may be closed using +RTMP_Close(). +The session handle is freed using +RTMP_Free(). +

    +All data is transferred using FLV format. The basic session requires +an RTMP URL. The RTMP URL format is of the form +

    +  rtmp[t][e|s]://hostname[:port][/app[/playpath]]
    +
    +

    +Plain rtmp, as well as tunneled and encrypted sessions are supported. +

    +Additional options may be specified by appending space-separated +key=value pairs to the URL. Special characters in values may need +to be escaped to prevent misinterpretation by the option parser. +The escape encoding uses a backslash followed by two hexadecimal digits +representing the ASCII value of the character. E.g., spaces must +be escaped as \20 and backslashes must be escaped as \5c. +

+ +

OPTIONS

    +
+ +

Network Parameters

    +These options define how to connect to the media server. +

    +

    +socks=host:port +
    +Use the specified SOCKS4 proxy. +
    +
+ +

Connection Parameters

    +These options define the content of the RTMP Connect request packet. +If correct values are not provided, the media server will reject the +connection attempt. +

    +

    +app=name +
    +Name of application to connect to on the RTMP server. Overrides +the app in the RTMP URL. Sometimes the librtmp URL parser cannot +determine the app name automatically, so it must be given explicitly +using this option. +
    +

    +

    +tcUrl=url +
    +URL of the target stream. Defaults to rtmp[t][e|s]://host[:port]/app. +
    +

    +

    +pageUrl=url +
    +URL of the web page in which the media was embedded. By default no +value will be sent. +
    +

    +

    +swfUrl=url +
    +URL of the SWF player for the media. By default no value will be sent. +
    +

    +

    +flashVer=version +
    +Version of the Flash plugin used to run the SWF player. The +default is "LNX 10,0,32,18". +
    +

    +

    +conn=type:data +
    +Append arbitrary AMF data to the Connect message. The type +must be B for Boolean, N for number, S for string, O for object, or Z +for null. For Booleans the data must be either 0 or 1 for FALSE or TRUE, +respectively. Likewise for Objects the data must be 0 or 1 to end or +begin an object, respectively. Data items in subobjects may be named, by +prefixing the type with 'N' and specifying the name before the value, e.g. +NB:myFlag:1. This option may be used multiple times to construct arbitrary +AMF sequences. E.g. +
    +  conn=B:1 conn=S:authMe conn=O:1 conn=NN:code:1.23 conn=NS:flag:ok conn=O:0
    +
    +
    +
+ +

Session Parameters

    +These options take effect after the Connect request has succeeded. +

    +

    +playpath=path +
    +Overrides the playpath parsed from the RTMP URL. Sometimes the +rtmpdump URL parser cannot determine the correct playpath +automatically, so it must be given explicitly using this option. +
    +

    +

    +playlist=0|1 +
    +If the value is 1 or TRUE, issue a set_playlist command before sending the +play command. The playlist will just contain the current playpath. If the +value is 0 or FALSE, the set_playlist command will not be sent. The +default is FALSE. +
    +

    +

    +live=0|1 +
    +Specify that the media is a live stream. No resuming or seeking in +live streams is possible. +
    +

    +

    +subscribe=path +
    +Name of live stream to subscribe to. Defaults to +playpath. +
    +

    +

    +start=num +
    +Start at +num +seconds into the stream. Not valid for live streams. +
    +

    +

    +stop=num +
    +Stop at +num +seconds into the stream. +
    +

    +

    +buffer=num +
    +Set buffer time to +num +milliseconds. The default is 30000. +
    +

    +

    +timeout=num +
    +Timeout the session after +num +seconds without receiving any data from the server. The default is 120. +
    +
+ +

Security Parameters

    +These options handle additional authentication requests from the server. +

    +

    +token=key +
    +Key for SecureToken response, used if the server requires SecureToken +authentication. +
    +

    +

    +jtv=JSON +
    +JSON token used by legacy Justin.tv servers. Invokes NetStream.Authenticate.UsherToken +
    +

    +

    +swfVfy=0|1 +
    +If the value is 1 or TRUE, the SWF player is retrieved from the +specified +swfUrl +for performing SWF Verification. The SWF hash and size (used in the +verification step) are computed automatically. Also the SWF information is +cached in a +.swfinfo +file in the user's home directory, so that it doesn't need to be retrieved +and recalculated every time. The .swfinfo file records +the SWF URL, the time it was fetched, the modification timestamp of the SWF +file, its size, and its hash. By default, the cached info will be used +for 30 days before re-checking. +
    +

    +

    +swfAge=days +
    +Specify how many days to use the cached SWF info before re-checking. Use +0 to always check the SWF URL. Note that if the check shows that the +SWF file has the same modification timestamp as before, it will not be +retrieved again. +
    +
+ +

EXAMPLES

    +An example character string suitable for use with +RTMP_SetupURL(): +
    +  "rtmp://flashserver:1935/ondemand/thefile swfUrl=http://flashserver/player.swf swfVfy=1"
    +
    +
+ +

ENVIRONMENT

    +

    +

    +HOME +
    +The value of +$HOME +is used as the location for the +.swfinfo +file. +
    +
+ +

FILES

    +

    +

    +$HOME/.swfinfo +
    +Cache of SWF Verification information +
    +
+ +

SEE ALSO

+ +

AUTHORS

diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/librtmp.pc.in b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/librtmp.pc.in new file mode 100644 index 0000000..a82beca --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/librtmp.pc.in @@ -0,0 +1,13 @@ +prefix=@prefix@ +exec_prefix=${prefix} +libdir=@libdir@ +incdir=${prefix}/include + +Name: librtmp +Description: RTMP implementation +Version: @VERSION@ +Requires: @CRYPTO_REQ@ +URL: http://rtmpdump.mplayerhq.hu +Libs: -L${libdir} -lrtmp -lz +Libs.private: @PRIVATE_LIBS@ +Cflags: -I${incdir} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/log.c b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/log.c new file mode 100644 index 0000000..90719b4 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/log.c @@ -0,0 +1,220 @@ +/* + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include +#include +#include +#include + +#include "rtmp_sys.h" +#include "log.h" + +#define MAX_PRINT_LEN 2048 + +RTMP_LogLevel RTMP_debuglevel = RTMP_LOGERROR; + +static int neednl; + +static FILE *fmsg; + +static RTMP_LogCallback rtmp_log_default, *cb = rtmp_log_default; + +static const char *levels[] = { + "CRIT", "ERROR", "WARNING", "INFO", + "DEBUG", "DEBUG2" +}; + +static void rtmp_log_default(int level, const char *format, va_list vl) +{ + char str[MAX_PRINT_LEN]=""; + + vsnprintf(str, MAX_PRINT_LEN-1, format, vl); + + /* Filter out 'no-name' */ + if ( RTMP_debuglevel RTMP_debuglevel ) + return; + + ptr = line; + + for(i=0; i> 4)]; + *ptr++ = hexdig[0x0f & data[i]]; + if ((i & 0x0f) == 0x0f) { + *ptr = '\0'; + ptr = line; + RTMP_Log(level, "%s", line); + } else { + *ptr++ = ' '; + } + } + if (i & 0x0f) { + *ptr = '\0'; + RTMP_Log(level, "%s", line); + } +} + +void RTMP_LogHexString(int level, const uint8_t *data, unsigned long len) +{ +#define BP_OFFSET 9 +#define BP_GRAPH 60 +#define BP_LEN 80 + char line[BP_LEN]; + unsigned long i; + + if ( !data || level > RTMP_debuglevel ) + return; + + /* in case len is zero */ + line[0] = '\0'; + + for ( i = 0 ; i < len ; i++ ) { + int n = i & 15; + unsigned off; + + if( !n ) { + if( i ) RTMP_Log( level, "%s", line ); + memset( line, ' ', sizeof(line)-2 ); + line[sizeof(line)-2] = '\0'; + + off = i % 0x0ffffU; + + line[2] = hexdig[0x0f & (off >> 12)]; + line[3] = hexdig[0x0f & (off >> 8)]; + line[4] = hexdig[0x0f & (off >> 4)]; + line[5] = hexdig[0x0f & off]; + line[6] = ':'; + } + + off = BP_OFFSET + n*3 + ((n >= 8)?1:0); + line[off] = hexdig[0x0f & ( data[i] >> 4 )]; + line[off+1] = hexdig[0x0f & data[i]]; + + off = BP_GRAPH + n + ((n >= 8)?1:0); + + if ( isprint( data[i] )) { + line[BP_GRAPH + n] = data[i]; + } else { + line[BP_GRAPH + n] = '.'; + } + } + + RTMP_Log( level, "%s", line ); +} + +/* These should only be used by apps, never by the library itself */ +void RTMP_LogPrintf(const char *format, ...) +{ + char str[MAX_PRINT_LEN]=""; + int len; + va_list args; + va_start(args, format); + len = vsnprintf(str, MAX_PRINT_LEN-1, format, args); + va_end(args); + + if ( RTMP_debuglevel==RTMP_LOGCRIT ) + return; + + if ( !fmsg ) fmsg = stderr; + + if (neednl) { + putc('\n', fmsg); + neednl = 0; + } + + if (len > MAX_PRINT_LEN-1) + len = MAX_PRINT_LEN-1; + fprintf(fmsg, "%s", str); + if (str[len-1] == '\n') + fflush(fmsg); +} + +void RTMP_LogStatus(const char *format, ...) +{ + char str[MAX_PRINT_LEN]=""; + va_list args; + va_start(args, format); + vsnprintf(str, MAX_PRINT_LEN-1, format, args); + va_end(args); + + if ( RTMP_debuglevel==RTMP_LOGCRIT ) + return; + + if ( !fmsg ) fmsg = stderr; + + fprintf(fmsg, "%s", str); + fflush(fmsg); + neednl = 1; +} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/log.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/log.h new file mode 100644 index 0000000..2adb111 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/log.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#ifndef __RTMP_LOG_H__ +#define __RTMP_LOG_H__ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif +/* Enable this to get full debugging output */ +/* #define _DEBUG */ + +#ifdef _DEBUG +#undef NODEBUG +#endif + +typedef enum +{ RTMP_LOGCRIT=0, RTMP_LOGERROR, RTMP_LOGWARNING, RTMP_LOGINFO, + RTMP_LOGDEBUG, RTMP_LOGDEBUG2, RTMP_LOGALL +} RTMP_LogLevel; + +extern RTMP_LogLevel RTMP_debuglevel; + +typedef void (RTMP_LogCallback)(int level, const char *fmt, va_list); +void RTMP_LogSetCallback(RTMP_LogCallback *cb); +void RTMP_LogSetOutput(FILE *file); +#ifdef __GNUC__ +void RTMP_LogPrintf(const char *format, ...) __attribute__ ((__format__ (__printf__, 1, 2))); +void RTMP_LogStatus(const char *format, ...) __attribute__ ((__format__ (__printf__, 1, 2))); +void RTMP_Log(int level, const char *format, ...) __attribute__ ((__format__ (__printf__, 2, 3))); +#else +void RTMP_LogPrintf(const char *format, ...); +void RTMP_LogStatus(const char *format, ...); +void RTMP_Log(int level, const char *format, ...); +#endif +void RTMP_LogHex(int level, const uint8_t *data, unsigned long len); +void RTMP_LogHexString(int level, const uint8_t *data, unsigned long len); +void RTMP_LogSetLevel(RTMP_LogLevel lvl); +RTMP_LogLevel RTMP_LogGetLevel(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/parseurl.c b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/parseurl.c new file mode 100644 index 0000000..768d125 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/parseurl.c @@ -0,0 +1,289 @@ +/* + * Copyright (C) 2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include + +#include +#include + +#include "rtmp_sys.h" +#include "log.h" + +int RTMP_ParseURL(const char *url, int *protocol, AVal *host, unsigned int *port, + AVal *playpath, AVal *app) +{ + char *p, *end, *col, *ques, *slash; + + RTMP_Log(RTMP_LOGDEBUG, "Parsing..."); + + *protocol = RTMP_PROTOCOL_RTMP; + *port = 0; + playpath->av_len = 0; + playpath->av_val = NULL; + app->av_len = 0; + app->av_val = NULL; + + /* Old School Parsing */ + + /* look for usual :// pattern */ + p = strstr(url, "://"); + if(!p) { + RTMP_Log(RTMP_LOGERROR, "RTMP URL: No :// in url!"); + return RTMP_ERROR_URL_MISSING_PROTOCOL; + } + { + int len = (int)(p-url); + + if(len == 4 && strncasecmp(url, "rtmp", 4)==0) + *protocol = RTMP_PROTOCOL_RTMP; + else if(len == 5 && strncasecmp(url, "rtmpt", 5)==0) + *protocol = RTMP_PROTOCOL_RTMPT; + else if(len == 5 && strncasecmp(url, "rtmps", 5)==0) + *protocol = RTMP_PROTOCOL_RTMPS; + else if(len == 5 && strncasecmp(url, "rtmpe", 5)==0) + *protocol = RTMP_PROTOCOL_RTMPE; + else if(len == 5 && strncasecmp(url, "rtmfp", 5)==0) + *protocol = RTMP_PROTOCOL_RTMFP; + else if(len == 6 && strncasecmp(url, "rtmpte", 6)==0) + *protocol = RTMP_PROTOCOL_RTMPTE; + else if(len == 6 && strncasecmp(url, "rtmpts", 6)==0) + *protocol = RTMP_PROTOCOL_RTMPTS; + else { + RTMP_Log(RTMP_LOGWARNING, "Unknown protocol!\n"); + goto parsehost; + } + } + + RTMP_Log(RTMP_LOGDEBUG, "Parsed protocol: %d", *protocol); + +parsehost: + /* let's get the hostname */ + p+=3; + + /* check for sudden death */ + if(*p==0) { + RTMP_Log(RTMP_LOGWARNING, "No hostname in URL!"); + return RTMP_ERROR_URL_MISSING_HOSTNAME; + } + + end = p + strlen(p); + col = strchr(p, ':'); + ques = strchr(p, '?'); + slash = strchr(p, '/'); + + { + int hostlen; + if(slash) + hostlen = slash - p; + else + hostlen = end - p; + if(col && col -p < hostlen) + hostlen = col - p; + + if(hostlen < 256) { + host->av_val = p; + host->av_len = hostlen; + RTMP_Log(RTMP_LOGDEBUG, "Parsed host : %.*s", hostlen, host->av_val); + } else { + RTMP_Log(RTMP_LOGWARNING, "Hostname exceeds 255 characters!"); + } + + p+=hostlen; + } + + /* get the port number if available */ + if(*p == ':') { + unsigned int p2; + p++; + p2 = atoi(p); + if(p2 > 65535) { + RTMP_Log(RTMP_LOGWARNING, "Invalid port number!"); + } else { + *port = p2; + } + } + + if(!slash) { + RTMP_Log(RTMP_LOGWARNING, "No application or playpath in URL!"); + return RTMP_SUCCESS; + } + p = slash+1; + + { + /* parse application + * + * rtmp://host[:port]/app[/appinstance][/...] + * application = app[/appinstance] + */ + + char *slash2, *slash3 = NULL, *slash4 = NULL; + int applen, appnamelen; + + slash2 = strchr(p, '/'); + if(slash2) + slash3 = strchr(slash2+1, '/'); + if(slash3) + slash4 = strchr(slash3+1, '/'); + + applen = end-p; /* ondemand, pass all parameters as app */ + appnamelen = applen; /* ondemand length */ + + if(ques && strstr(p, "slist=")) { /* whatever it is, the '?' and slist= means we need to use everything as app and parse plapath from slist= */ + appnamelen = ques-p; + } + else if(strncmp(p, "ondemand/", 9)==0) { + /* app = ondemand/foobar, only pass app=ondemand */ + applen = 8; + appnamelen = 8; + } + else { /* app!=ondemand, so app is app[/appinstance] */ + if(slash4) + appnamelen = slash4-p; + else if(slash3) + appnamelen = slash3-p; + else if(slash2) + appnamelen = slash2-p; + + applen = appnamelen; + } + + app->av_val = p; + app->av_len = applen; + RTMP_Log(RTMP_LOGDEBUG, "Parsed app : %.*s", applen, p); + + p += appnamelen; + } + + if (*p == '/') + p++; + + if (end-p) { + AVal av = {p, end-p}; + RTMP_ParsePlaypath(&av, playpath); + } + + return RTMP_SUCCESS; +} + +/* + * Extracts playpath from RTMP URL. playpath is the file part of the + * URL, i.e. the part that comes after rtmp://host:port/app/ + * + * Returns the stream name in a format understood by FMS. The name is + * the playpath part of the URL with formatting depending on the stream + * type: + * + * mp4 streams: prepend "mp4:", remove extension + * mp3 streams: prepend "mp3:", remove extension + * flv streams: remove extension + */ +void RTMP_ParsePlaypath(AVal *in, AVal *out) { + int addMP4 = 0; + int addMP3 = 0; + int subExt = 0; + const char *playpath = in->av_val; + const char *temp, *q, *ext = NULL; + const char *ppstart = playpath; + char *streamname, *destptr, *p; + + int pplen = in->av_len; + + out->av_val = NULL; + out->av_len = 0; + + if ((*ppstart == '?') && + (temp=strstr(ppstart, "slist=")) != 0) { + ppstart = temp+6; + pplen = strlen(ppstart); + + temp = strchr(ppstart, '&'); + if (temp) { + pplen = temp-ppstart; + } + } + + q = strchr(ppstart, '?'); + if (pplen >= 4) { + if (q) + ext = q-4; + else + ext = &ppstart[pplen-4]; + if ((strncmp(ext, ".f4v", 4) == 0) || + (strncmp(ext, ".mp4", 4) == 0)) { + addMP4 = 1; + subExt = 1; + /* Only remove .flv from rtmp URL, not slist params */ + } else if ((ppstart == playpath) && + (strncmp(ext, ".flv", 4) == 0)) { + subExt = 1; + } else if (strncmp(ext, ".mp3", 4) == 0) { + addMP3 = 1; + subExt = 1; + } + } + + streamname = (char *)malloc((pplen+4+1)*sizeof(char)); + if (!streamname) + return; + + destptr = streamname; + if (addMP4) { + if (strncmp(ppstart, "mp4:", 4)) { + strcpy(destptr, "mp4:"); + destptr += 4; + } else { + subExt = 0; + } + } else if (addMP3) { + if (strncmp(ppstart, "mp3:", 4)) { + strcpy(destptr, "mp3:"); + destptr += 4; + } else { + subExt = 0; + } + } + + for (p=(char *)ppstart; pplen >0;) { + /* skip extension */ + if (subExt && p == ext) { + p += 4; + pplen -= 4; + continue; + } + if (*p == '%') { + unsigned int c; + sscanf(p+1, "%02x", &c); + *destptr++ = c; + pplen -= 3; + p += 3; + } else { + *destptr++ = *p++; + pplen--; + } + } + *destptr = '\0'; + + out->av_val = streamname; + out->av_len = destptr - streamname; +} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/rtmp.c b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/rtmp.c new file mode 100644 index 0000000..1ff094e --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/rtmp.c @@ -0,0 +1,5228 @@ +/* + * Copyright (C) 2005-2008 Team XBMC + * http://www.xbmc.org + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#include +#include +#include +#include +#include + +#include "rtmp_sys.h" +#include "log.h" + +#ifdef CRYPTO +#ifdef USE_POLARSSL +#include +#include +#include +#define MD5_DIGEST_LENGTH 16 + +static const char *my_dhm_P = + "E4004C1F94182000103D883A448B3F80" \ + "2CE4B44A83301270002C20D0321CFD00" \ + "11CCEF784C26A400F43DFB901BCA7538" \ + "F2C6B176001CF5A0FD16D2C48B1D0C1C" \ + "F6AC8E1DA6BCC3B4E1F96B0564965300" \ + "FFA1D0B601EB2800F489AA512C4B248C" \ + "01F76949A60BB7F00A40B1EAB64BDD48" \ + "E8A700D60B7F1200FA8E77B0A979DABF"; + +static const char *my_dhm_G = "4"; + +#elif defined(USE_GNUTLS) +#include +#define MD5_DIGEST_LENGTH 16 +#include +#include +#else /* USE_OPENSSL */ +#include +#include +#include +#include +#include +#endif +TLS_CTX RTMP_TLS_ctx; +#endif + +#define RTMP_SIG_SIZE 1536 +#define RTMP_LARGE_HEADER_SIZE 12 + +static const int packetSize[] = { 12, 8, 4, 1 }; + +int RTMP_ctrlC; + +const char RTMPProtocolStrings[][7] = { + "RTMP", + "RTMPT", + "RTMPE", + "RTMPTE", + "RTMPS", + "RTMPTS", + "", + "", + "RTMFP" +}; + +const char RTMPProtocolStringsLower[][7] = { + "rtmp", + "rtmpt", + "rtmpe", + "rtmpte", + "rtmps", + "rtmpts", + "", + "", + "rtmfp" +}; + +static const char *RTMPT_cmds[] = { + "open", + "send", + "idle", + "close" +}; + +typedef enum { + RTMPT_OPEN=0, RTMPT_SEND, RTMPT_IDLE, RTMPT_CLOSE +} RTMPTCmd; + +static int DumpMetaData(AMFObject *obj); +static int HandShake(RTMP *r, int FP9HandShake); +static int SocksNegotiate(RTMP *r); + +static RTMPResult SendConnectPacket(RTMP *r, RTMPPacket *cp); +static RTMPResult SendCheckBW(RTMP *r); +static RTMPResult SendCheckBWResult(RTMP *r, double txn); +static RTMPResult SendDeleteStream(RTMP *r, double dStreamId); +static RTMPResult SendFCSubscribe(RTMP *r, AVal *subscribepath); +static RTMPResult SendPlay(RTMP *r); +static RTMPResult SendBytesReceived(RTMP *r); +static RTMPResult SendUsherToken(RTMP *r, AVal *usherToken); + +#if 0 /* unused */ +static int SendBGHasStream(RTMP *r, double dId, AVal *playpath); +#endif + +static int HandleInvoke(RTMP *r, const char *body, unsigned int nBodySize); +static int HandleMetadata(RTMP *r, char *body, unsigned int len); +static void HandleChangeChunkSize(RTMP *r, const RTMPPacket *packet); +static void HandleAudio(RTMP *r, const RTMPPacket *packet); +static void HandleVideo(RTMP *r, const RTMPPacket *packet); +static void HandleCtrl(RTMP *r, const RTMPPacket *packet); +static void HandleServerBW(RTMP *r, const RTMPPacket *packet); +static void HandleClientBW(RTMP *r, const RTMPPacket *packet); + +static int ReadN(RTMP *r, char *buffer, int n); +static int WriteN(RTMP *r, const char *buffer, int n); + +static void DecodeTEA(AVal *key, AVal *text); + +static int HTTP_Post(RTMP *r, RTMPTCmd cmd, const char *buf, int len); +static int HTTP_read(RTMP *r, int fill); + +#ifndef _WIN32 +static int clk_tck; +#endif + +#ifdef CRYPTO +#include "handshake.h" +#endif + +uint32_t +RTMP_GetTime() +{ +#ifdef _DEBUG + return 0; +#elif defined(_WIN32) + return timeGetTime(); +#else + struct tms t; + if (!clk_tck) clk_tck = sysconf(_SC_CLK_TCK); + return times(&t) * 1000 / clk_tck; +#endif +} + +void +RTMP_UserInterrupt() +{ + RTMP_ctrlC = TRUE; +} + +void +RTMPPacket_Reset(RTMPPacket *p) +{ + p->m_headerType = 0; + p->m_packetType = 0; + p->m_nChannel = 0; + p->m_nTimeStamp = 0; + p->m_nInfoField2 = 0; + p->m_hasAbsTimestamp = FALSE; + p->m_nBodySize = 0; + p->m_nBytesRead = 0; +} + +int +RTMPPacket_Alloc(RTMPPacket *p, int nSize) +{ + char *ptr = calloc(1, nSize + RTMP_MAX_HEADER_SIZE); + if (!ptr) + return FALSE; + p->m_body = ptr + RTMP_MAX_HEADER_SIZE; + p->m_nBytesRead = 0; + return TRUE; +} + +void +RTMPPacket_Free(RTMPPacket *p) +{ + if (p->m_body) + { + free(p->m_body - RTMP_MAX_HEADER_SIZE); + p->m_body = NULL; + } +} + +void +RTMPPacket_Dump(RTMPPacket *p) +{ + RTMP_Log(RTMP_LOGDEBUG, + "RTMP PACKET: packet type: 0x%02x. channel: 0x%02x. info 1: %d info 2: %d. Body size: %u. body: 0x%02x", + p->m_packetType, p->m_nChannel, p->m_nTimeStamp, p->m_nInfoField2, + p->m_nBodySize, p->m_body ? (unsigned char)p->m_body[0] : 0); +} + +int +RTMP_LibVersion() +{ + return RTMP_LIB_VERSION; +} + +void +RTMP_TLS_Init() +{ +#ifdef CRYPTO +#ifdef USE_POLARSSL + /* Do this regardless of NO_SSL, we use havege for rtmpe too */ + RTMP_TLS_ctx = calloc(1,sizeof(struct tls_ctx)); + havege_init(&RTMP_TLS_ctx->hs); +#elif defined(USE_GNUTLS) && !defined(NO_SSL) + /* Technically we need to initialize libgcrypt ourselves if + * we're not going to call gnutls_global_init(). Ignoring this + * for now. + */ + gnutls_global_init(); + RTMP_TLS_ctx = malloc(sizeof(struct tls_ctx)); + gnutls_certificate_allocate_credentials(&RTMP_TLS_ctx->cred); + gnutls_priority_init(&RTMP_TLS_ctx->prios, "NORMAL", NULL); + gnutls_certificate_set_x509_trust_file(RTMP_TLS_ctx->cred, + "ca.pem", GNUTLS_X509_FMT_PEM); +#elif !defined(NO_SSL) /* USE_OPENSSL */ + /* libcrypto doesn't need anything special */ + SSL_load_error_strings(); + SSL_library_init(); + OpenSSL_add_all_digests(); + RTMP_TLS_ctx = SSL_CTX_new(SSLv23_method()); + SSL_CTX_set_options(RTMP_TLS_ctx, SSL_OP_ALL); + SSL_CTX_set_default_verify_paths(RTMP_TLS_ctx); +#endif +#endif +} + +void * +RTMP_TLS_AllocServerContext(const char* cert, const char* key) +{ + void *ctx = NULL; +#ifdef CRYPTO + if (!RTMP_TLS_ctx) + RTMP_TLS_Init(); +#ifdef USE_POLARSSL + tls_server_ctx *tc = ctx = calloc(1, sizeof(struct tls_server_ctx)); + tc->dhm_P = my_dhm_P; + tc->dhm_G = my_dhm_G; + tc->hs = &RTMP_TLS_ctx->hs; + if (x509parse_crtfile(&tc->cert, cert)) { + free(tc); + return NULL; + } + if (x509parse_keyfile(&tc->key, key, NULL)) { + x509_free(&tc->cert); + free(tc); + return NULL; + } +#elif defined(USE_GNUTLS) && !defined(NO_SSL) + gnutls_certificate_allocate_credentials((gnutls_certificate_credentials*) &ctx); + if (gnutls_certificate_set_x509_key_file(ctx, cert, key, GNUTLS_X509_FMT_PEM) != 0) { + gnutls_certificate_free_credentials(ctx); + return NULL; + } +#elif !defined(NO_SSL) /* USE_OPENSSL */ + ctx = SSL_CTX_new(SSLv23_server_method()); + if (!SSL_CTX_use_certificate_chain_file(ctx, cert)) { + SSL_CTX_free(ctx); + return NULL; + } + if (!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM)) { + SSL_CTX_free(ctx); + return NULL; + } +#endif +#endif + return ctx; +} + +void +RTMP_TLS_FreeServerContext(void *ctx) +{ +#ifdef CRYPTO +#ifdef USE_POLARSSL + x509_free(&((tls_server_ctx*)ctx)->cert); + rsa_free(&((tls_server_ctx*)ctx)->key); + free(ctx); +#elif defined(USE_GNUTLS) && !defined(NO_SSL) + gnutls_certificate_free_credentials(ctx); +#elif !defined(NO_SSL) /* USE_OPENSSL */ + SSL_CTX_free(ctx); +#endif +#endif +} + +RTMP * +RTMP_Alloc() +{ + return calloc(1, sizeof(RTMP)); +} + +void +RTMP_Free(RTMP *r) +{ + free(r); +} + +void +RTMP_Init(RTMP *r) +{ +#ifdef CRYPTO + if (!RTMP_TLS_ctx) + RTMP_TLS_Init(); +#endif + + memset(r, 0, sizeof(RTMP)); + r->m_sb.sb_socket = -1; + r->m_inChunkSize = RTMP_DEFAULT_CHUNKSIZE; + r->m_outChunkSize = RTMP_DEFAULT_CHUNKSIZE; + r->m_nBufferMS = 30000; + r->m_nClientBW = 2500000; + r->m_nClientBW2 = 2; + r->m_nServerBW = 2500000; + r->m_fAudioCodecs = 3191.0; + r->m_fVideoCodecs = 252.0; + r->Link.receiveTimeoutInMs = 10000; + r->Link.swfAge = 30; +} + +void +RTMP_EnableWrite(RTMP *r) +{ + r->Link.protocol |= RTMP_FEATURE_WRITE; +} + +double +RTMP_GetDuration(RTMP *r) +{ + return r->m_fDuration; +} + +int +RTMP_IsConnected(RTMP *r) +{ + return r->m_sb.sb_socket != -1; +} + +int +RTMP_Socket(RTMP *r) +{ + return r->m_sb.sb_socket; +} + +int +RTMP_IsTimedout(RTMP *r) +{ + return r->m_sb.sb_timedout; +} + +void +RTMP_SetBufferMS(RTMP *r, int size) +{ + r->m_nBufferMS = size; +} + +void +RTMP_UpdateBufferMS(RTMP *r) +{ + RTMP_SendCtrl(r, 3, r->m_stream_id, r->m_nBufferMS); +} + +#undef OSS +#ifdef _WIN32 +#define OSS "WIN" +#elif defined(__sun__) +#define OSS "SOL" +#elif defined(__APPLE__) +#define OSS "MAC" +#elif defined(__linux__) +#define OSS "LNX" +#else +#define OSS "GNU" +#endif +#define DEF_VERSTR OSS " 10,0,32,18" +static const char DEFAULT_FLASH_VER[] = DEF_VERSTR; +const AVal RTMP_DefaultFlashVer = + { (char *)DEFAULT_FLASH_VER, sizeof(DEFAULT_FLASH_VER) - 1 }; + +static void +SocksSetup(RTMP *r, AVal *sockshost) +{ + if (sockshost->av_len) + { + const char *socksport = strchr(sockshost->av_val, ':'); + char *hostname = strdup(sockshost->av_val); + + if (socksport) + hostname[socksport - sockshost->av_val] = '\0'; + r->Link.sockshost.av_val = hostname; + r->Link.sockshost.av_len = strlen(hostname); + + r->Link.socksport = socksport ? atoi(socksport + 1) : 1080; + RTMP_Log(RTMP_LOGDEBUG, "Connecting via SOCKS proxy: %s:%d", r->Link.sockshost.av_val, + r->Link.socksport); + } + else + { + r->Link.sockshost.av_val = NULL; + r->Link.sockshost.av_len = 0; + r->Link.socksport = 0; + } +} + +void +RTMP_SetupStream(RTMP *r, + int protocol, + AVal *host, + unsigned int port, + AVal *sockshost, + AVal *playpath, + AVal *tcUrl, + AVal *swfUrl, + AVal *pageUrl, + AVal *app, + AVal *auth, + AVal *swfSHA256Hash, + uint32_t swfSize, + AVal *flashVer, + AVal *subscribepath, + AVal *usherToken, + int dStart, + int dStop, int bLiveStream, long int timeoutInMs) +{ + RTMP_Log(RTMP_LOGDEBUG, "Protocol : %s", RTMPProtocolStrings[protocol&7]); + RTMP_Log(RTMP_LOGDEBUG, "Hostname : %.*s", host->av_len, host->av_val); + RTMP_Log(RTMP_LOGDEBUG, "Port : %d", port); + RTMP_Log(RTMP_LOGDEBUG, "Playpath : %s", playpath->av_val); + + if (tcUrl && tcUrl->av_val) + RTMP_Log(RTMP_LOGDEBUG, "tcUrl : %s", tcUrl->av_val); + if (swfUrl && swfUrl->av_val) + RTMP_Log(RTMP_LOGDEBUG, "swfUrl : %s", swfUrl->av_val); + if (pageUrl && pageUrl->av_val) + RTMP_Log(RTMP_LOGDEBUG, "pageUrl : %s", pageUrl->av_val); + if (app && app->av_val) + RTMP_Log(RTMP_LOGDEBUG, "app : %.*s", app->av_len, app->av_val); + if (auth && auth->av_val) + RTMP_Log(RTMP_LOGDEBUG, "auth : %s", auth->av_val); + if (subscribepath && subscribepath->av_val) + RTMP_Log(RTMP_LOGDEBUG, "subscribepath : %s", subscribepath->av_val); + if (usherToken && usherToken->av_val) + RTMP_Log(RTMP_LOGDEBUG, "NetStream.Authenticate.UsherToken : %s", usherToken->av_val); + if (flashVer && flashVer->av_val) + RTMP_Log(RTMP_LOGDEBUG, "flashVer : %s", flashVer->av_val); + if (dStart > 0) + RTMP_Log(RTMP_LOGDEBUG, "StartTime : %d msec", dStart); + if (dStop > 0) + RTMP_Log(RTMP_LOGDEBUG, "StopTime : %d msec", dStop); + + RTMP_Log(RTMP_LOGDEBUG, "live : %s", bLiveStream ? "yes" : "no"); + RTMP_Log(RTMP_LOGDEBUG, "timeoutInMs : %ld sec", timeoutInMs); + +#ifdef CRYPTO + if (swfSHA256Hash != NULL && swfSize > 0) + { + memcpy(r->Link.SWFHash, swfSHA256Hash->av_val, sizeof(r->Link.SWFHash)); + r->Link.SWFSize = swfSize; + RTMP_Log(RTMP_LOGDEBUG, "SWFSHA256:"); + RTMP_LogHex(RTMP_LOGDEBUG, r->Link.SWFHash, sizeof(r->Link.SWFHash)); + RTMP_Log(RTMP_LOGDEBUG, "SWFSize : %u", r->Link.SWFSize); + } + else + { + r->Link.SWFSize = 0; + } +#endif + + SocksSetup(r, sockshost); + + if (tcUrl && tcUrl->av_len) + r->Link.tcUrl = *tcUrl; + if (swfUrl && swfUrl->av_len) + r->Link.swfUrl = *swfUrl; + if (pageUrl && pageUrl->av_len) + r->Link.pageUrl = *pageUrl; + if (app && app->av_len) + r->Link.app = *app; + if (auth && auth->av_len) + { + r->Link.auth = *auth; + r->Link.lFlags |= RTMP_LF_AUTH; + } + if (flashVer && flashVer->av_len) + r->Link.flashVer = *flashVer; + else + r->Link.flashVer = RTMP_DefaultFlashVer; + if (subscribepath && subscribepath->av_len) + r->Link.subscribepath = *subscribepath; + if (usherToken && usherToken->av_len) + r->Link.usherToken = *usherToken; + r->Link.seekTime = dStart; + r->Link.stopTime = dStop; + if (bLiveStream) + r->Link.lFlags |= RTMP_LF_LIVE; + r->Link.receiveTimeoutInMs = timeoutInMs; + + r->Link.protocol = protocol; + r->Link.hostname = *host; + r->Link.port = port; + r->Link.playpath = *playpath; + + if (r->Link.port == 0) + { + if (protocol & RTMP_FEATURE_SSL) + r->Link.port = 443; + else if (protocol & RTMP_FEATURE_HTTP) + r->Link.port = 80; + else + r->Link.port = 1935; + } +} + +enum { OPT_STR=0, OPT_INT, OPT_BOOL, OPT_CONN }; +static const char *optinfo[] = { + "string", "integer", "boolean", "AMF" }; + +#define OFF(x) offsetof(struct RTMP,x) + +static struct urlopt { + AVal name; + off_t off; + int otype; + int omisc; + char *use; +} options[] = { + { AVC("socks"), OFF(Link.sockshost), OPT_STR, 0, + "Use the specified SOCKS proxy" }, + { AVC("app"), OFF(Link.app), OPT_STR, 0, + "Name of target app on server" }, + { AVC("tcUrl"), OFF(Link.tcUrl), OPT_STR, 0, + "URL to played stream" }, + { AVC("pageUrl"), OFF(Link.pageUrl), OPT_STR, 0, + "URL of played media's web page" }, + { AVC("swfUrl"), OFF(Link.swfUrl), OPT_STR, 0, + "URL to player SWF file" }, + { AVC("flashver"), OFF(Link.flashVer), OPT_STR, 0, + "Flash version string (default " DEF_VERSTR ")" }, + { AVC("conn"), OFF(Link.extras), OPT_CONN, 0, + "Append arbitrary AMF data to Connect message" }, + { AVC("playpath"), OFF(Link.playpath), OPT_STR, 0, + "Path to target media on server" }, + { AVC("playlist"), OFF(Link.lFlags), OPT_BOOL, RTMP_LF_PLST, + "Set playlist before play command" }, + { AVC("live"), OFF(Link.lFlags), OPT_BOOL, RTMP_LF_LIVE, + "Stream is live, no seeking possible" }, + { AVC("subscribe"), OFF(Link.subscribepath), OPT_STR, 0, + "Stream to subscribe to" }, + { AVC("jtv"), OFF(Link.usherToken), OPT_STR, 0, + "Justin.tv authentication token" }, + { AVC("token"), OFF(Link.token), OPT_STR, 0, + "Key for SecureToken response" }, + { AVC("swfVfy"), OFF(Link.lFlags), OPT_BOOL, RTMP_LF_SWFV, + "Perform SWF Verification" }, + { AVC("swfAge"), OFF(Link.swfAge), OPT_INT, 0, + "Number of days to use cached SWF hash" }, + { AVC("start"), OFF(Link.seekTime), OPT_INT, 0, + "Stream start position in milliseconds" }, + { AVC("stop"), OFF(Link.stopTime), OPT_INT, 0, + "Stream stop position in milliseconds" }, + { AVC("buffer"), OFF(m_nBufferMS), OPT_INT, 0, + "Buffer time in milliseconds" }, + { AVC("timeout"), OFF(Link.receiveTimeoutInMs), OPT_INT, 0, + "Session timeout in seconds" }, + { AVC("pubUser"), OFF(Link.pubUser), OPT_STR, 0, + "Publisher username" }, + { AVC("pubPasswd"), OFF(Link.pubPasswd), OPT_STR, 0, + "Publisher password" }, + { {NULL,0}, 0, 0} +}; + +static const AVal truth[] = { + AVC("1"), + AVC("on"), + AVC("yes"), + AVC("true"), + {0,0} +}; + +static void RTMP_OptUsage() +{ + int i; + + RTMP_Log(RTMP_LOGERROR, "Valid RTMP options are:\n"); + for (i=0; options[i].name.av_len; i++) { + RTMP_Log(RTMP_LOGERROR, "%10s %-7s %s\n", options[i].name.av_val, + optinfo[options[i].otype], options[i].use); + } +} + +static int +parseAMF(AMFObject *obj, AVal *av, int *depth) +{ + AMFObjectProperty prop = {{0,0}}; + int i; + char *p, *arg = av->av_val; + + if (arg[1] == ':') + { + p = (char *)arg+2; + switch(arg[0]) + { + case 'B': + prop.p_type = AMF_BOOLEAN; + prop.p_vu.p_number = atoi(p); + break; + case 'S': + prop.p_type = AMF_STRING; + prop.p_vu.p_aval.av_val = p; + prop.p_vu.p_aval.av_len = av->av_len - (p-arg); + break; + case 'N': + prop.p_type = AMF_NUMBER; + prop.p_vu.p_number = strtod(p, NULL); + break; + case 'Z': + prop.p_type = AMF_NULL; + break; + case 'O': + i = atoi(p); + if (i) + { + prop.p_type = AMF_OBJECT; + } + else + { + (*depth)--; + return 0; + } + break; + default: + return -1; + } + } + else if (arg[2] == ':' && arg[0] == 'N') + { + p = strchr(arg+3, ':'); + if (!p || !*depth) + return -1; + prop.p_name.av_val = (char *)arg+3; + prop.p_name.av_len = p - (arg+3); + + p++; + switch(arg[1]) + { + case 'B': + prop.p_type = AMF_BOOLEAN; + prop.p_vu.p_number = atoi(p); + break; + case 'S': + prop.p_type = AMF_STRING; + prop.p_vu.p_aval.av_val = p; + prop.p_vu.p_aval.av_len = av->av_len - (p-arg); + break; + case 'N': + prop.p_type = AMF_NUMBER; + prop.p_vu.p_number = strtod(p, NULL); + break; + case 'O': + prop.p_type = AMF_OBJECT; + break; + default: + return -1; + } + } + else + return -1; + + if (*depth) + { + AMFObject *o2; + for (i=0; i<*depth; i++) + { + o2 = &obj->o_props[obj->o_num-1].p_vu.p_object; + obj = o2; + } + } + AMF_AddProp(obj, &prop); + if (prop.p_type == AMF_OBJECT) + (*depth)++; + return 0; +} + +int RTMP_SetOpt(RTMP *r, const AVal *opt, AVal *arg) +{ + int i; + void *v; + + for (i=0; options[i].name.av_len; i++) { + if (opt->av_len != options[i].name.av_len) continue; + if (strcasecmp(opt->av_val, options[i].name.av_val)) continue; + v = (char *)r + options[i].off; + switch(options[i].otype) { + case OPT_STR: { + AVal *aptr = v; + *aptr = *arg; } + break; + case OPT_INT: { + long l = strtol(arg->av_val, NULL, 0); + *(int *)v = l; } + break; + case OPT_BOOL: { + int j, fl; + fl = *(int *)v; + for (j=0; truth[j].av_len; j++) { + if (arg->av_len != truth[j].av_len) continue; + if (strcasecmp(arg->av_val, truth[j].av_val)) continue; + fl |= options[i].omisc; break; } + *(int *)v = fl; + } + break; + case OPT_CONN: + if (parseAMF(&r->Link.extras, arg, &r->Link.edepth)) { + return RTMP_ERROR_UNKNOWN_RTMP_AMF_TYPE; + } + break; + } + break; + } + if (!options[i].name.av_len) { + RTMP_Log(RTMP_LOGERROR, "Unknown option %s", opt->av_val); + RTMP_OptUsage(); + return RTMP_ERROR_UNKNOWN_RTMP_OPTION; + } + + return RTMP_SUCCESS; +} + +RTMPResult RTMP_SetupURL(RTMP *r, char *url) +{ + AVal opt, arg; + char *p1, *p2, *ptr = strchr(url, ' '); + int ret, len; + unsigned int port = 0; + + if (ptr) + *ptr = '\0'; + + len = strlen(url); + ret = RTMP_ParseURL(url, &r->Link.protocol, &r->Link.hostname, + &port, &r->Link.playpath0, &r->Link.app); + if (ret != RTMP_SUCCESS) + { + return ret; + } + r->Link.port = port; + r->Link.playpath = r->Link.playpath0; + + while (ptr) { + *ptr++ = '\0'; + p1 = ptr; + p2 = strchr(p1, '='); + if (!p2) + break; + opt.av_val = p1; + opt.av_len = p2 - p1; + *p2++ = '\0'; + arg.av_val = p2; + ptr = strchr(p2, ' '); + if (ptr) { + *ptr = '\0'; + arg.av_len = ptr - p2; + /* skip repeated spaces */ + while(ptr[1] == ' ') + *ptr++ = '\0'; + } else { + arg.av_len = strlen(p2); + } + + /* unescape */ + port = arg.av_len; + for (p1=p2; port >0;) { + if (*p1 == '\\') { + unsigned int c; + if (port < 3) + { + return RTMP_ERROR_URL_INCORRECT_PORT; + } + sscanf(p1+1, "%02x", &c); + *p2++ = c; + port -= 3; + p1 += 3; + } else { + *p2++ = *p1++; + port--; + } + } + arg.av_len = p2 - arg.av_val; + + ret = RTMP_SetOpt(r, &opt, &arg); + if (ret != RTMP_SUCCESS) + return ret; + } + + if (!r->Link.tcUrl.av_len) + { + r->Link.tcUrl.av_val = url; + if (r->Link.app.av_len) + { + if (r->Link.app.av_val < url + len) + { + /* if app is part of original url, just use it */ + r->Link.tcUrl.av_len = r->Link.app.av_len + (r->Link.app.av_val - url); + } + else + { + len = r->Link.hostname.av_len + r->Link.app.av_len + + sizeof("rtmpte://:65535/"); + r->Link.tcUrl.av_val = malloc(len); + r->Link.tcUrl.av_len = snprintf(r->Link.tcUrl.av_val, len, + "%s://%.*s:%d/%.*s", + RTMPProtocolStringsLower[r->Link.protocol], + r->Link.hostname.av_len, r->Link.hostname.av_val, + r->Link.port, + r->Link.app.av_len, r->Link.app.av_val); + r->Link.lFlags |= RTMP_LF_FTCU; + } + } + else + { + r->Link.tcUrl.av_len = strlen(url); + } + } + +#ifdef CRYPTO + if ((r->Link.lFlags & RTMP_LF_SWFV) && r->Link.swfUrl.av_len) + RTMP_HashSWF(r->Link.swfUrl.av_val, &r->Link.SWFSize, + (unsigned char *)r->Link.SWFHash, r->Link.swfAge); +#endif + + SocksSetup(r, &r->Link.sockshost); + + if (r->Link.port == 0) + { + if (r->Link.protocol & RTMP_FEATURE_SSL) + r->Link.port = 443; + else if (r->Link.protocol & RTMP_FEATURE_HTTP) + r->Link.port = 80; + else + r->Link.port = 1935; + } + return RTMP_SUCCESS; +} + +static RTMPResult +add_addr_info(struct sockaddr_in *service, AVal *host, int port) +{ + char *hostname; + RTMPResult ret = RTMP_SUCCESS; + if (host->av_val[host->av_len]) + { + hostname = malloc(host->av_len+1); + memcpy(hostname, host->av_val, host->av_len); + hostname[host->av_len] = '\0'; + } + else + { + hostname = host->av_val; + } + + service->sin_addr.s_addr = inet_addr(hostname); + if (service->sin_addr.s_addr == INADDR_NONE) + { + struct hostent *host = gethostbyname(hostname); + if (host == NULL || host->h_addr == NULL) + { + RTMP_Log(RTMP_LOGERROR, "Problem accessing the DNS. (addr: %s)", hostname); + ret = RTMP_ERROR_DNS_NOT_REACHABLE; + goto finish; + } + service->sin_addr = *(struct in_addr *)host->h_addr; + } + + service->sin_port = htons(port); +finish: + if (hostname != host->av_val) + free(hostname); + return ret; +} + +RTMPResult +RTMP_Connect0(RTMP *r, struct sockaddr * service) +{ + int on = 1; + r->m_sb.sb_timedout = FALSE; + r->m_pausing = 0; + r->m_fDuration = 0.0; + + r->m_sb.sb_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (r->m_sb.sb_socket != -1) + { + int err; + struct timeval send_timeout; + + send_timeout.tv_sec = r->Link.sendTimeoutInMs / 1000; + send_timeout.tv_usec = (r->Link.sendTimeoutInMs % 1000) * 1000; + err = setsockopt(r->m_sb.sb_socket, SOL_SOCKET, SO_SNDTIMEO, &send_timeout, sizeof(send_timeout)); + if (err) + { + RTMP_Log(RTMP_LOGERROR, "Error %d setting SO_SNDTIMEO", errno); + } + + if (connect(r->m_sb.sb_socket, service, sizeof(struct sockaddr)) < 0) + { + int err = GetSockError(); + RTMP_Log(RTMP_LOGERROR, "%s, failed to connect socket. %d (%s)", + __FUNCTION__, err, strerror(err)); + RTMP_Close(r); + return RTMP_ERROR_SOCKET_CONNECT_FAIL; + } + + if (r->Link.socksport) + { + RTMP_Log(RTMP_LOGDEBUG, "%s ... SOCKS negotiation", __FUNCTION__); + if (!SocksNegotiate(r)) + { + RTMP_Log(RTMP_LOGERROR, "%s, SOCKS negotiation failed.", __FUNCTION__); + RTMP_Close(r); + return RTMP_ERROR_SOCKS_NEGOTIATION_FAIL; + } + } + } + else + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to create socket. Error: %d", __FUNCTION__, + GetSockError()); + return RTMP_ERROR_SOCKET_CREATE_FAIL; + } + + /* set timeout */ + { + struct timeval tv; + + tv.tv_sec = r->Link.receiveTimeoutInMs / 1000; + tv.tv_usec = (r->Link.receiveTimeoutInMs % 1000) * 1000; + if (setsockopt + (r->m_sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv))) + { + RTMP_Log(RTMP_LOGERROR, "%s, Setting socket timeout to %dms failed!", + __FUNCTION__, r->Link.receiveTimeoutInMs); + } + } + + setsockopt(r->m_sb.sb_socket, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof(on)); + + return RTMP_SUCCESS; +} + +int +RTMP_TLS_Accept(RTMP *r, void *ctx) +{ +#if defined(CRYPTO) && !defined(NO_SSL) + TLS_server(ctx, r->m_sb.sb_ssl); + TLS_setfd(r->m_sb.sb_ssl, r->m_sb.sb_socket); + if (TLS_accept(r->m_sb.sb_ssl) < 0) + { + RTMP_Log(RTMP_LOGERROR, "%s, TLS_Connect failed", __FUNCTION__); + return FALSE; + } + return TRUE; +#else + return FALSE; +#endif +} + +RTMPResult +RTMP_Connect1(RTMP *r, RTMPPacket *cp) +{ + if (r->Link.protocol & RTMP_FEATURE_SSL) + { +#if defined(CRYPTO) && !defined(NO_SSL) + TLS_client(RTMP_TLS_ctx, r->m_sb.sb_ssl); + TLS_setfd(r->m_sb.sb_ssl, r->m_sb.sb_socket); + if (TLS_connect(r->m_sb.sb_ssl) < 0) + { + RTMP_Log(RTMP_LOGERROR, "%s, TLS_Connect failed", __FUNCTION__); + RTMP_Close(r); + return FALSE; + } +#else + RTMP_Log(RTMP_LOGERROR, "%s, no SSL/TLS support", __FUNCTION__); + RTMP_Close(r); + return RTMP_ERROR_NO_SSL_TLS_SUPP; + +#endif + } + if (r->Link.protocol & RTMP_FEATURE_HTTP) + { + r->m_msgCounter = 1; + r->m_clientID.av_val = NULL; + r->m_clientID.av_len = 0; + HTTP_Post(r, RTMPT_OPEN, "", 1); + if (HTTP_read(r, 1) != 0) + { + r->m_msgCounter = 0; + RTMP_Log(RTMP_LOGDEBUG, "%s, Could not connect for handshake", __FUNCTION__); + RTMP_Close(r); + return RTMP_ERROR_HANDSHAKE_CONNECT_FAIL; + } + r->m_msgCounter = 0; + } + RTMP_Log(RTMP_LOGDEBUG, "%s, ... connected, handshaking", __FUNCTION__); + if (!HandShake(r, TRUE)) + { + RTMP_Log(RTMP_LOGERROR, "%s, handshake failed.", __FUNCTION__); + RTMP_Close(r); + return RTMP_ERROR_HANDSHAKE_FAIL; + } + RTMP_Log(RTMP_LOGDEBUG, "%s, handshaked", __FUNCTION__); + + if (SendConnectPacket(r, cp) != RTMP_SUCCESS) + { + RTMP_Log(RTMP_LOGERROR, "%s, RTMP connect failed.", __FUNCTION__); + RTMP_Close(r); + return RTMP_ERROR_CONNECT_FAIL; + } + return RTMP_SUCCESS; +} + +RTMPResult +RTMP_Connect(RTMP *r, RTMPPacket *cp) +{ + struct sockaddr_in service; + RTMPResult ret = RTMP_SUCCESS; + if (!r->Link.hostname.av_len) + return RTMP_ERROR_URL_MISSING_PROTOCOL; + + memset(&service, 0, sizeof(struct sockaddr_in)); + service.sin_family = AF_INET; + + if (r->Link.socksport) + { + /* Connect via SOCKS */ + ret = add_addr_info(&service, &r->Link.sockshost, r->Link.socksport); + if (ret != RTMP_SUCCESS) + { + return ret; + } + } + else + { + /* Connect directly */ + ret = add_addr_info(&service, &r->Link.hostname, r->Link.port); + if (ret != RTMP_SUCCESS) + { + return ret; + } + } + + ret = RTMP_Connect0(r, (struct sockaddr *)&service); + if (ret != RTMP_SUCCESS) + return ret; + + r->m_bSendCounter = TRUE; + + return RTMP_Connect1(r, cp); +} + +static int +SocksNegotiate(RTMP *r) +{ + unsigned long addr; + struct sockaddr_in service; + memset(&service, 0, sizeof(struct sockaddr_in)); + + add_addr_info(&service, &r->Link.hostname, r->Link.port); + addr = htonl(service.sin_addr.s_addr); + + { + char packet[] = { + 4, 1, /* SOCKS 4, connect */ + (r->Link.port >> 8) & 0xFF, + (r->Link.port) & 0xFF, + (char)(addr >> 24) & 0xFF, (char)(addr >> 16) & 0xFF, + (char)(addr >> 8) & 0xFF, (char)addr & 0xFF, + 0 + }; /* NULL terminate */ + + WriteN(r, packet, sizeof packet); + + if (ReadN(r, packet, 8) != 8) + return FALSE; + + if (packet[0] == 0 && packet[1] == 90) + { + return TRUE; + } + else + { + RTMP_Log(RTMP_LOGERROR, "%s, SOCKS returned error code %d", __FUNCTION__, packet[1]); + return FALSE; + } + } +} + +RTMPResult +RTMP_ConnectStream(RTMP *r, int seekTime) +{ + RTMPPacket packet = { 0 }; + + /* seekTime was already set by SetupStream / SetupURL. + * This is only needed by ReconnectStream. + */ + if (seekTime > 0) + r->Link.seekTime = seekTime; + + r->m_mediaChannel = 0; + + while (!r->m_bPlaying && RTMP_IsConnected(r) && RTMP_ReadPacket(r, &packet)) + { + if (RTMPPacket_IsReady(&packet)) + { + if (!packet.m_nBodySize) + continue; + if ((packet.m_packetType == RTMP_PACKET_TYPE_AUDIO) || + (packet.m_packetType == RTMP_PACKET_TYPE_VIDEO) || + (packet.m_packetType == RTMP_PACKET_TYPE_INFO)) + { + RTMP_Log(RTMP_LOGWARNING, "Received FLV packet before play()! Ignoring."); + RTMPPacket_Free(&packet); + continue; + } + + RTMP_ClientPacket(r, &packet); + RTMPPacket_Free(&packet); + } + } + + if (r->m_bPlaying) + { + return RTMP_SUCCESS; + } + else + { + return RTMP_ERROR_OPEN_CONNECT_STREAM; + } +} + +RTMPResult +RTMP_ReconnectStream(RTMP *r, int seekTime) +{ + RTMP_DeleteStream(r); + + RTMP_SendCreateStream(r); + + return RTMP_ConnectStream(r, seekTime); +} + +RTMPResult +RTMP_ToggleStream(RTMP *r) +{ + RTMPResult res; + + if (!r->m_pausing) + { + if (RTMP_IsTimedout(r) && r->m_read.status == RTMP_READ_EOF) + r->m_read.status = 0; + + res = RTMP_SendPause(r, TRUE, r->m_pauseStamp); + if (res != RTMP_SUCCESS) + return res; + + r->m_pausing = 1; + sleep(1); + } + res = RTMP_SendPause(r, FALSE, r->m_pauseStamp); + r->m_pausing = 3; + return res; +} + +void +RTMP_DeleteStream(RTMP *r) +{ + if (r->m_stream_id < 0) + return; + + r->m_bPlaying = FALSE; + + SendDeleteStream(r, r->m_stream_id); + r->m_stream_id = -1; +} + +int +RTMP_GetNextMediaPacket(RTMP *r, RTMPPacket *packet) +{ + int bHasMediaPacket = 0; + + while (!bHasMediaPacket && RTMP_IsConnected(r) + && RTMP_ReadPacket(r, packet)) + { + if (!RTMPPacket_IsReady(packet)) + { + continue; + } + + bHasMediaPacket = RTMP_ClientPacket(r, packet); + + if (!bHasMediaPacket) + { + RTMPPacket_Free(packet); + } + else if (r->m_pausing == 3) + { + if (packet->m_nTimeStamp <= r->m_mediaStamp) + { + bHasMediaPacket = 0; +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, + "Skipped type: %02X, size: %d, TS: %d ms, abs TS: %d, pause: %d ms", + packet->m_packetType, packet->m_nBodySize, + packet->m_nTimeStamp, packet->m_hasAbsTimestamp, + r->m_mediaStamp); +#endif + RTMPPacket_Free(packet); + continue; + } + r->m_pausing = 0; + } + } + + if (bHasMediaPacket) + r->m_bPlaying = TRUE; + else if (r->m_sb.sb_timedout && !r->m_pausing) + r->m_pauseStamp = r->m_mediaChannel < r->m_channelsAllocatedIn ? + r->m_channelTimestamp[r->m_mediaChannel] : 0; + + return bHasMediaPacket; +} + +int +RTMP_ClientPacket(RTMP *r, RTMPPacket *packet) +{ + int bHasMediaPacket = 0; + switch (packet->m_packetType) + { + case RTMP_PACKET_TYPE_CHUNK_SIZE: + /* chunk size */ + HandleChangeChunkSize(r, packet); + break; + + case RTMP_PACKET_TYPE_BYTES_READ_REPORT: + /* bytes read report */ + RTMP_Log(RTMP_LOGDEBUG, "%s, received: bytes read report", __FUNCTION__); + break; + + case RTMP_PACKET_TYPE_CONTROL: + /* ctrl */ + HandleCtrl(r, packet); + break; + + case RTMP_PACKET_TYPE_SERVER_BW: + /* server bw */ + HandleServerBW(r, packet); + break; + + case RTMP_PACKET_TYPE_CLIENT_BW: + /* client bw */ + HandleClientBW(r, packet); + break; + + case RTMP_PACKET_TYPE_AUDIO: + /* audio data */ + /*RTMP_Log(RTMP_LOGDEBUG, "%s, received: audio %lu bytes", __FUNCTION__, packet.m_nBodySize); */ + HandleAudio(r, packet); + bHasMediaPacket = 1; + if (!r->m_mediaChannel) + r->m_mediaChannel = packet->m_nChannel; + if (!r->m_pausing) + r->m_mediaStamp = packet->m_nTimeStamp; + break; + + case RTMP_PACKET_TYPE_VIDEO: + /* video data */ + /*RTMP_Log(RTMP_LOGDEBUG, "%s, received: video %lu bytes", __FUNCTION__, packet.m_nBodySize); */ + HandleVideo(r, packet); + bHasMediaPacket = 1; + if (!r->m_mediaChannel) + r->m_mediaChannel = packet->m_nChannel; + if (!r->m_pausing) + r->m_mediaStamp = packet->m_nTimeStamp; + break; + + case RTMP_PACKET_TYPE_FLEX_STREAM_SEND: + /* flex stream send */ + RTMP_Log(RTMP_LOGDEBUG, + "%s, flex stream send, size %u bytes, not supported, ignoring", + __FUNCTION__, packet->m_nBodySize); + break; + + case RTMP_PACKET_TYPE_FLEX_SHARED_OBJECT: + /* flex shared object */ + RTMP_Log(RTMP_LOGDEBUG, + "%s, flex shared object, size %u bytes, not supported, ignoring", + __FUNCTION__, packet->m_nBodySize); + break; + + case RTMP_PACKET_TYPE_FLEX_MESSAGE: + /* flex message */ + { + RTMP_Log(RTMP_LOGDEBUG, + "%s, flex message, size %u bytes, not fully supported", + __FUNCTION__, packet->m_nBodySize); + /*RTMP_LogHex(packet.m_body, packet.m_nBodySize); */ + + /* some DEBUG code */ +#if 0 + RTMP_LIB_AMFObject obj; + int nRes = obj.Decode(packet.m_body+1, packet.m_nBodySize-1); + if(nRes < 0) { + RTMP_Log(RTMP_LOGERROR, "%s, error decoding AMF3 packet", __FUNCTION__); + /*return; */ + } + + obj.Dump(); +#endif + + if (HandleInvoke(r, packet->m_body + 1, packet->m_nBodySize - 1) == 1) + bHasMediaPacket = 2; + break; + } + case RTMP_PACKET_TYPE_INFO: + /* metadata (notify) */ + RTMP_Log(RTMP_LOGDEBUG, "%s, received: notify %u bytes", __FUNCTION__, + packet->m_nBodySize); + if (HandleMetadata(r, packet->m_body, packet->m_nBodySize)) + bHasMediaPacket = 1; + break; + + case RTMP_PACKET_TYPE_SHARED_OBJECT: + RTMP_Log(RTMP_LOGDEBUG, "%s, shared object, not supported, ignoring", + __FUNCTION__); + break; + + case RTMP_PACKET_TYPE_INVOKE: + /* invoke */ + RTMP_Log(RTMP_LOGDEBUG, "%s, received: invoke %u bytes", __FUNCTION__, + packet->m_nBodySize); + /*RTMP_LogHex(packet.m_body, packet.m_nBodySize); */ + + if (HandleInvoke(r, packet->m_body, packet->m_nBodySize) == 1) + bHasMediaPacket = 2; + break; + + case RTMP_PACKET_TYPE_FLASH_VIDEO: + { + /* go through FLV packets and handle metadata packets */ + unsigned int pos = 0; + uint32_t nTimeStamp = packet->m_nTimeStamp; + + while (pos + 11 < packet->m_nBodySize) + { + uint32_t dataSize = AMF_DecodeInt24(packet->m_body + pos + 1); /* size without header (11) and prevTagSize (4) */ + + if (pos + 11 + dataSize + 4 > packet->m_nBodySize) + { + RTMP_Log(RTMP_LOGWARNING, "Stream corrupt?!"); + break; + } + if (packet->m_body[pos] == 0x12) + { + HandleMetadata(r, packet->m_body + pos + 11, dataSize); + } + else if (packet->m_body[pos] == 8 || packet->m_body[pos] == 9) + { + nTimeStamp = AMF_DecodeInt24(packet->m_body + pos + 4); + nTimeStamp |= (packet->m_body[pos + 7] << 24); + } + pos += (11 + dataSize + 4); + } + if (!r->m_pausing) + r->m_mediaStamp = nTimeStamp; + + /* FLV tag(s) */ + /*RTMP_Log(RTMP_LOGDEBUG, "%s, received: FLV tag(s) %lu bytes", __FUNCTION__, packet.m_nBodySize); */ + bHasMediaPacket = 1; + break; + } + default: + RTMP_Log(RTMP_LOGDEBUG, "%s, unknown packet type received: 0x%02x", __FUNCTION__, + packet->m_packetType); +#ifdef _DEBUG + RTMP_LogHex(RTMP_LOGDEBUG, packet->m_body, packet->m_nBodySize); +#endif + } + + return bHasMediaPacket; +} + +#ifdef _DEBUG +extern FILE *netstackdump; +extern FILE *netstackdump_read; +#endif + +static int +ReadN(RTMP *r, char *buffer, int n) +{ + int nOriginalSize = n; + int avail; + char *ptr; + + r->m_sb.sb_timedout = FALSE; + +#ifdef _DEBUG + memset(buffer, 0, n); +#endif + + ptr = buffer; + while (n > 0) + { + int nBytes = 0, nRead; + if (r->Link.protocol & RTMP_FEATURE_HTTP) + { + int refill = 0; + while (!r->m_resplen) + { + int ret; + if (r->m_sb.sb_size < 13 || refill) + { + if (!r->m_unackd) + HTTP_Post(r, RTMPT_IDLE, "", 1); + if (RTMPSockBuf_Fill(&r->m_sb) < 1) + { + if (!r->m_sb.sb_timedout) + RTMP_Close(r); + return 0; + } + } + if ((ret = HTTP_read(r, 0)) == -1) + { + RTMP_Log(RTMP_LOGDEBUG, "%s, No valid HTTP response found", __FUNCTION__); + RTMP_Close(r); + return 0; + } + else if (ret == -2) + { + refill = 1; + } + else + { + refill = 0; + } + } + if (r->m_resplen && !r->m_sb.sb_size) + RTMPSockBuf_Fill(&r->m_sb); + avail = r->m_sb.sb_size; + if (avail > r->m_resplen) + avail = r->m_resplen; + } + else + { + avail = r->m_sb.sb_size; + if (avail == 0) + { + if (RTMPSockBuf_Fill(&r->m_sb) < 1) + { + if (!r->m_sb.sb_timedout) + RTMP_Close(r); + return 0; + } + avail = r->m_sb.sb_size; + } + } + nRead = ((n < avail) ? n : avail); + if (nRead > 0 && r->m_sb.sb_start != NULL) + { + memcpy(ptr, r->m_sb.sb_start, nRead); + r->m_sb.sb_start += nRead; + r->m_sb.sb_size -= nRead; + nBytes = nRead; + r->m_nBytesIn += nRead; + if (r->m_bSendCounter + && r->m_nBytesIn > ( r->m_nBytesInSent + r->m_nClientBW / 10)) + { + RTMPResult result = SendBytesReceived(r); + if (result != RTMP_SUCCESS) + return result; + } + } + /*RTMP_Log(RTMP_LOGDEBUG, "%s: %d bytes\n", __FUNCTION__, nBytes); */ +#ifdef _DEBUG + fwrite(ptr, 1, nBytes, netstackdump_read); +#endif + + if (nBytes == 0) + { + RTMP_Log(RTMP_LOGDEBUG, "%s, RTMP socket closed by peer", __FUNCTION__); + /*goto again; */ + RTMP_Close(r); + break; + } + + if (r->Link.protocol & RTMP_FEATURE_HTTP) + r->m_resplen -= nBytes; + +#ifdef CRYPTO + if (r->Link.rc4keyIn) + { + RC4_encrypt(r->Link.rc4keyIn, nBytes, ptr); + } +#endif + + n -= nBytes; + ptr += nBytes; + } + + return nOriginalSize - n; +} + +static int +WriteN(RTMP *r, const char *buffer, int n) +{ + const char *ptr = buffer; +#ifdef CRYPTO + char *encrypted = 0; + char buf[RTMP_BUFFER_CACHE_SIZE]; + + if (r->Link.rc4keyOut) + { + if (n > sizeof(buf)) + encrypted = (char *)malloc(n); + else + encrypted = (char *)buf; + ptr = encrypted; + RC4_encrypt2(r->Link.rc4keyOut, n, buffer, ptr); + } +#endif + + while (n > 0) + { + int nBytes; + + if (r->Link.protocol & RTMP_FEATURE_HTTP) + nBytes = HTTP_Post(r, RTMPT_SEND, ptr, n); + else + nBytes = RTMPSockBuf_Send(&r->m_sb, ptr, n); + /*RTMP_Log(RTMP_LOGDEBUG, "%s: %d\n", __FUNCTION__, nBytes); */ + + if (nBytes < 0) + { + int sockerr = GetSockError(); + RTMP_Log(RTMP_LOGERROR, "%s, RTMP send error %d (%d bytes)", __FUNCTION__, + sockerr, n); + + if (sockerr == EINTR && !RTMP_ctrlC) + continue; + + RTMP_Close(r); + n = 1; + break; + } + + if (nBytes == 0) + break; + + n -= nBytes; + ptr += nBytes; + } + +#ifdef CRYPTO + if (encrypted && encrypted != buf) + free(encrypted); +#endif + + return n == 0; +} + +#define SAVC(x) static const AVal av_##x = AVC(#x) + +SAVC(app); +SAVC(connect); +SAVC(flashVer); +SAVC(swfUrl); +SAVC(pageUrl); +SAVC(tcUrl); +SAVC(fpad); +SAVC(capabilities); +SAVC(audioCodecs); +SAVC(videoCodecs); +SAVC(videoFunction); +SAVC(objectEncoding); +SAVC(secureToken); +SAVC(secureTokenResponse); +SAVC(type); +SAVC(nonprivate); + +static RTMPResult +SendConnectPacket(RTMP *r, RTMPPacket *cp) +{ + RTMPPacket packet; + char pbuf[4096], *pend = pbuf + sizeof(pbuf); + char *enc; + + if (cp) + return RTMP_SendPacket(r, cp, TRUE); + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_connect); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_OBJECT; + + enc = AMF_EncodeNamedString(enc, pend, &av_app, &r->Link.app); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + if (r->Link.protocol & RTMP_FEATURE_WRITE) + { + enc = AMF_EncodeNamedString(enc, pend, &av_type, &av_nonprivate); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + } + if (r->Link.flashVer.av_len) + { + enc = AMF_EncodeNamedString(enc, pend, &av_flashVer, &r->Link.flashVer); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + } + if (r->Link.swfUrl.av_len) + { + enc = AMF_EncodeNamedString(enc, pend, &av_swfUrl, &r->Link.swfUrl); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + } + if (r->Link.tcUrl.av_len) + { + enc = AMF_EncodeNamedString(enc, pend, &av_tcUrl, &r->Link.tcUrl); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + } + if (!(r->Link.protocol & RTMP_FEATURE_WRITE)) + { + enc = AMF_EncodeNamedBoolean(enc, pend, &av_fpad, FALSE); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + enc = AMF_EncodeNamedNumber(enc, pend, &av_capabilities, 15.0); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + enc = AMF_EncodeNamedNumber(enc, pend, &av_audioCodecs, r->m_fAudioCodecs); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + enc = AMF_EncodeNamedNumber(enc, pend, &av_videoCodecs, r->m_fVideoCodecs); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + enc = AMF_EncodeNamedNumber(enc, pend, &av_videoFunction, 1.0); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + if (r->Link.pageUrl.av_len) + { + enc = AMF_EncodeNamedString(enc, pend, &av_pageUrl, &r->Link.pageUrl); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + } + } + if (r->m_fEncoding != 0.0 || r->m_bSendEncoding) + { /* AMF0, AMF3 not fully supported yet */ + enc = AMF_EncodeNamedNumber(enc, pend, &av_objectEncoding, r->m_fEncoding); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + } + if (enc + 3 >= pend) + return RTMP_ERROR_CONNECT_FAIL; + *enc++ = 0; + *enc++ = 0; /* end of object - 0x00 0x00 0x09 */ + *enc++ = AMF_OBJECT_END; + + /* add auth string */ + if (r->Link.auth.av_len) + { + enc = AMF_EncodeBoolean(enc, pend, r->Link.lFlags & RTMP_LF_AUTH); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + enc = AMF_EncodeString(enc, pend, &r->Link.auth); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + } + if (r->Link.extras.o_num) + { + int i; + for (i = 0; i < r->Link.extras.o_num; i++) + { + enc = AMFProp_Encode(&r->Link.extras.o_props[i], enc, pend); + if (!enc) + return RTMP_ERROR_CONNECT_FAIL; + } + } + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, TRUE); +} + +#if 0 /* unused */ +SAVC(bgHasStream); + +static int +SendBGHasStream(RTMP *r, double dId, AVal *playpath) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_bgHasStream); + enc = AMF_EncodeNumber(enc, pend, dId); + *enc++ = AMF_NULL; + + enc = AMF_EncodeString(enc, pend, playpath); + if (enc == NULL) + return FALSE; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, TRUE); +} +#endif + +SAVC(createStream); + +RTMPResult +RTMP_SendCreateStream(RTMP *r) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_createStream); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; /* NULL */ + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, TRUE); +} + +SAVC(FCSubscribe); + +static RTMPResult +SendFCSubscribe(RTMP *r, AVal *subscribepath) +{ + RTMPPacket packet; + char pbuf[512], *pend = pbuf + sizeof(pbuf); + char *enc; + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + RTMP_Log(RTMP_LOGDEBUG, "FCSubscribe: %s", subscribepath->av_val); + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_FCSubscribe); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, subscribepath); + + if (!enc) + return RTMP_ERROR_AMF_ENCODE_FAIL; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, TRUE); +} + +/* Justin.tv specific authentication */ +static const AVal av_NetStream_Authenticate_UsherToken = AVC("NetStream.Authenticate.UsherToken"); + +static RTMPResult +SendUsherToken(RTMP *r, AVal *usherToken) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + char *enc; + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + RTMP_Log(RTMP_LOGDEBUG, "UsherToken: %s", usherToken->av_val); + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_NetStream_Authenticate_UsherToken); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, usherToken); + + if (!enc) + return FALSE; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, FALSE); +} +/******************************************/ + +SAVC(releaseStream); + +static RTMPResult +SendReleaseStream(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_releaseStream); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, &r->Link.playpath); + if (!enc) + return FALSE; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, FALSE); +} + +SAVC(FCPublish); + +static RTMPResult +SendFCPublish(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_FCPublish); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, &r->Link.playpath); + if (!enc) + return FALSE; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, FALSE); +} + +SAVC(FCUnpublish); + +static RTMPResult +SendFCUnpublish(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_FCUnpublish); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, &r->Link.playpath); + if (!enc) + return FALSE; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, FALSE); +} + +SAVC(publish); +SAVC(live); +SAVC(record); + +static RTMPResult +SendPublish(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x04; /* source channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = r->m_stream_id; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_publish); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, &r->Link.playpath); + if (!enc) + return FALSE; + + /* FIXME: should we choose live based on Link.lFlags & RTMP_LF_LIVE? */ + enc = AMF_EncodeString(enc, pend, &av_live); + if (!enc) + return FALSE; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, TRUE); +} + +SAVC(deleteStream); + +static RTMPResult +SendDeleteStream(RTMP *r, double dStreamId) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_deleteStream); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeNumber(enc, pend, dStreamId); + + packet.m_nBodySize = enc - packet.m_body; + + /* no response expected */ + return RTMP_SendPacket(r, &packet, FALSE); +} + +SAVC(pause); + +RTMPResult +RTMP_SendPause(RTMP *r, int DoPause, int iTime) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x08; /* video channel */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_pause); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeBoolean(enc, pend, DoPause); + enc = AMF_EncodeNumber(enc, pend, (double)iTime); + + packet.m_nBodySize = enc - packet.m_body; + + RTMP_Log(RTMP_LOGDEBUG, "%s, %d, pauseTime=%d", __FUNCTION__, DoPause, iTime); + return RTMP_SendPacket(r, &packet, TRUE); +} + +RTMPResult RTMP_Pause(RTMP *r, int DoPause) +{ + if (DoPause) + r->m_pauseStamp = r->m_mediaChannel < r->m_channelsAllocatedIn ? + r->m_channelTimestamp[r->m_mediaChannel] : 0; + return RTMP_SendPause(r, DoPause, r->m_pauseStamp); +} + +SAVC(seek); + +RTMPResult +RTMP_SendSeek(RTMP *r, int iTime) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x08; /* video channel */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_seek); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + enc = AMF_EncodeNumber(enc, pend, (double)iTime); + + packet.m_nBodySize = enc - packet.m_body; + + r->m_read.flags |= RTMP_READ_SEEKING; + r->m_read.nResumeTS = 0; + + return RTMP_SendPacket(r, &packet, TRUE); +} + +RTMPResult +RTMP_SendServerBW(RTMP *r) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x02; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = RTMP_PACKET_TYPE_SERVER_BW; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + packet.m_nBodySize = 4; + + AMF_EncodeInt32(packet.m_body, pend, r->m_nServerBW); + return RTMP_SendPacket(r, &packet, FALSE); +} + +RTMPResult +RTMP_SendClientBW(RTMP *r) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x02; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = RTMP_PACKET_TYPE_CLIENT_BW; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + packet.m_nBodySize = 5; + + AMF_EncodeInt32(packet.m_body, pend, r->m_nClientBW); + packet.m_body[4] = r->m_nClientBW2; + return RTMP_SendPacket(r, &packet, FALSE); +} + +static RTMPResult +SendBytesReceived(RTMP *r) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + + packet.m_nChannel = 0x02; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_BYTES_READ_REPORT; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + packet.m_nBodySize = 4; + + AMF_EncodeInt32(packet.m_body, pend, r->m_nBytesIn); /* hard coded for now */ + r->m_nBytesInSent = r->m_nBytesIn; + + /*RTMP_Log(RTMP_LOGDEBUG, "Send bytes report. 0x%x (%d bytes)", (unsigned int)m_nBytesIn, m_nBytesIn); */ + return RTMP_SendPacket(r, &packet, FALSE); +} + +SAVC(_checkbw); + +static RTMPResult +SendCheckBW(RTMP *r) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; /* RTMP_GetTime(); */ + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av__checkbw); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + + packet.m_nBodySize = enc - packet.m_body; + + /* triggers _onbwcheck and eventually results in _onbwdone */ + return RTMP_SendPacket(r, &packet, FALSE); +} + +SAVC(_result); + +static RTMPResult +SendCheckBWResult(RTMP *r, double txn) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0x16 * r->m_nBWCheckCounter; /* temp inc value. till we figure it out. */ + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av__result); + enc = AMF_EncodeNumber(enc, pend, txn); + *enc++ = AMF_NULL; + enc = AMF_EncodeNumber(enc, pend, (double)r->m_nBWCheckCounter++); + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, FALSE); +} + +SAVC(ping); +SAVC(pong); + +static RTMPResult +SendPong(RTMP *r, double txn) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0x16 * r->m_nBWCheckCounter; /* temp inc value. till we figure it out. */ + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_pong); + enc = AMF_EncodeNumber(enc, pend, txn); + *enc++ = AMF_NULL; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, FALSE); +} + +SAVC(play); + +static RTMPResult +SendPlay(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x08; /* we make 8 our stream channel */ + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = r->m_stream_id; /*0x01000000; */ + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_play); + enc = AMF_EncodeNumber(enc, pend, ++r->m_numInvokes); + *enc++ = AMF_NULL; + + RTMP_Log(RTMP_LOGDEBUG, "%s, seekTime=%d, stopTime=%d, sending play: %s", + __FUNCTION__, r->Link.seekTime, r->Link.stopTime, + r->Link.playpath.av_val); + enc = AMF_EncodeString(enc, pend, &r->Link.playpath); + if (!enc) + return FALSE; + + /* Optional parameters start and len. + * + * start: -2, -1, 0, positive number + * -2: looks for a live stream, then a recorded stream, + * if not found any open a live stream + * -1: plays a live stream + * >=0: plays a recorded streams from 'start' milliseconds + */ + if (r->Link.lFlags & RTMP_LF_LIVE) + enc = AMF_EncodeNumber(enc, pend, -1000.0); + else + { + if (r->Link.seekTime > 0.0) + enc = AMF_EncodeNumber(enc, pend, r->Link.seekTime); /* resume from here */ + else + enc = AMF_EncodeNumber(enc, pend, -2000.0); /* corresponds to -2 in the comment above */ + } + if (!enc) + return FALSE; + + /* len: -1, 0, positive number + * -1: plays live or recorded stream to the end (default) + * 0: plays a frame 'start' ms away from the beginning + * >0: plays a live or recoded stream for 'len' milliseconds + */ + /*enc += EncodeNumber(enc, -1.0); */ /* len */ + if (r->Link.stopTime) + { + enc = AMF_EncodeNumber(enc, pend, r->Link.stopTime - r->Link.seekTime); + if (!enc) + return FALSE; + } + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, TRUE); +} + +SAVC(set_playlist); +SAVC(0); + +static RTMPResult +SendPlaylist(RTMP *r) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x08; /* we make 8 our stream channel */ + packet.m_headerType = RTMP_PACKET_SIZE_LARGE; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = r->m_stream_id; /*0x01000000; */ + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_set_playlist); + enc = AMF_EncodeNumber(enc, pend, 0); + *enc++ = AMF_NULL; + *enc++ = AMF_ECMA_ARRAY; + *enc++ = 0; + *enc++ = 0; + *enc++ = 0; + *enc++ = AMF_OBJECT; + enc = AMF_EncodeNamedString(enc, pend, &av_0, &r->Link.playpath); + if (!enc) + return FALSE; + if (enc + 3 >= pend) + return FALSE; + *enc++ = 0; + *enc++ = 0; + *enc++ = AMF_OBJECT_END; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, TRUE); +} + +static RTMPResult +SendSecureTokenResponse(RTMP *r, AVal *resp) +{ + RTMPPacket packet; + char pbuf[1024], *pend = pbuf + sizeof(pbuf); + char *enc; + + packet.m_nChannel = 0x03; /* control channel (invoke) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_INVOKE; + packet.m_nTimeStamp = 0; + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + enc = packet.m_body; + enc = AMF_EncodeString(enc, pend, &av_secureTokenResponse); + enc = AMF_EncodeNumber(enc, pend, 0.0); + *enc++ = AMF_NULL; + enc = AMF_EncodeString(enc, pend, resp); + if (!enc) + return FALSE; + + packet.m_nBodySize = enc - packet.m_body; + + return RTMP_SendPacket(r, &packet, FALSE); +} + +/* +from http://jira.red5.org/confluence/display/docs/Ping: + +Ping is the most mysterious message in RTMP and till now we haven't fully interpreted it yet. In summary, Ping message is used as a special command that are exchanged between client and server. This page aims to document all known Ping messages. Expect the list to grow. + +The type of Ping packet is 0x4 and contains two mandatory parameters and two optional parameters. The first parameter is the type of Ping and in short integer. The second parameter is the target of the ping. As Ping is always sent in Channel 2 (control channel) and the target object in RTMP header is always 0 which means the Connection object, it's necessary to put an extra parameter to indicate the exact target object the Ping is sent to. The second parameter takes this responsibility. The value has the same meaning as the target object field in RTMP header. (The second value could also be used as other purposes, like RTT Ping/Pong. It is used as the timestamp.) The third and fourth parameters are optional and could be looked upon as the parameter of the Ping packet. Below is an unexhausted list of Ping messages. + + * type 0: Clear the stream. No third and fourth parameters. The second parameter could be 0. After the connection is established, a Ping 0,0 will be sent from server to client. The message will also be sent to client on the start of Play and in response of a Seek or Pause/Resume request. This Ping tells client to re-calibrate the clock with the timestamp of the next packet server sends. + * type 1: Tell the stream to clear the playing buffer. + * type 3: Buffer time of the client. The third parameter is the buffer time in millisecond. + * type 4: Reset a stream. Used together with type 0 in the case of VOD. Often sent before type 0. + * type 6: Ping the client from server. The second parameter is the current time. + * type 7: Pong reply from client. The second parameter is the time the server sent with his ping request. + * type 26: SWFVerification request + * type 27: SWFVerification response +*/ +RTMPResult +RTMP_SendCtrl(RTMP *r, short nType, unsigned int nObject, unsigned int nTime) +{ + RTMPPacket packet; + char pbuf[256], *pend = pbuf + sizeof(pbuf); + int nSize; + char *buf; + + RTMP_Log(RTMP_LOGDEBUG, "sending ctrl. type: 0x%04x", (unsigned short)nType); + + packet.m_nChannel = 0x02; /* control channel (ping) */ + packet.m_headerType = RTMP_PACKET_SIZE_MEDIUM; + packet.m_packetType = RTMP_PACKET_TYPE_CONTROL; + packet.m_nTimeStamp = 0; /* RTMP_GetTime(); */ + packet.m_nInfoField2 = 0; + packet.m_hasAbsTimestamp = 0; + packet.m_body = pbuf + RTMP_MAX_HEADER_SIZE; + + switch(nType) { + case 0x03: nSize = 10; break; /* buffer time */ + case 0x1A: nSize = 3; break; /* SWF verify request */ + case 0x1B: nSize = 44; break; /* SWF verify response */ + default: nSize = 6; break; + } + + packet.m_nBodySize = nSize; + + buf = packet.m_body; + buf = AMF_EncodeInt16(buf, pend, nType); + + if (nType == 0x1B) + { +#ifdef CRYPTO + memcpy(buf, r->Link.SWFVerificationResponse, 42); + RTMP_Log(RTMP_LOGDEBUG, "Sending SWFVerification response: "); + RTMP_LogHex(RTMP_LOGDEBUG, (uint8_t *)packet.m_body, packet.m_nBodySize); +#endif + } + else if (nType == 0x1A) + { + *buf = nObject & 0xff; + } + else + { + if (nSize > 2) + buf = AMF_EncodeInt32(buf, pend, nObject); + + if (nSize > 6) + buf = AMF_EncodeInt32(buf, pend, nTime); + } + + return RTMP_SendPacket(r, &packet, FALSE); +} + +static void +AV_erase(RTMP_METHOD *vals, int *num, int i, int freeit) +{ + if (freeit) + free(vals[i].name.av_val); + (*num)--; + for (; i < *num; i++) + { + vals[i] = vals[i + 1]; + } + vals[i].name.av_val = NULL; + vals[i].name.av_len = 0; + vals[i].num = 0; +} + +void +RTMP_DropRequest(RTMP *r, int i, int freeit) +{ + AV_erase(r->m_methodCalls, &r->m_numCalls, i, freeit); +} + +static void +AV_queue(RTMP_METHOD **vals, int *num, AVal *av, int txn) +{ + char *tmp; + if (!(*num & 0x0f)) + *vals = realloc(*vals, (*num + 16) * sizeof(RTMP_METHOD)); + tmp = malloc(av->av_len + 1); + memcpy(tmp, av->av_val, av->av_len); + tmp[av->av_len] = '\0'; + (*vals)[*num].num = txn; + (*vals)[*num].name.av_len = av->av_len; + (*vals)[(*num)++].name.av_val = tmp; +} + +static void +AV_clear(RTMP_METHOD *vals, int num) +{ + int i; + for (i = 0; i < num; i++) + free(vals[i].name.av_val); + free(vals); +} + + +#ifdef CRYPTO +static int +b64enc(const unsigned char *input, int length, char *output, int maxsize) +{ +#ifdef USE_POLARSSL + size_t buf_size = maxsize; + if(base64_encode((unsigned char *) output, &buf_size, input, length) == 0) + { + output[buf_size] = '\0'; + return 1; + } + else + { + RTMP_Log(RTMP_LOGDEBUG, "%s, error", __FUNCTION__); + return 0; + } +#elif defined(USE_GNUTLS) + if (BASE64_ENCODE_RAW_LENGTH(length) <= maxsize) + base64_encode_raw((uint8_t*) output, length, input); + else + { + RTMP_Log(RTMP_LOGDEBUG, "%s, error", __FUNCTION__); + return 0; + } +#else /* USE_OPENSSL */ + BIO *bmem, *b64; + BUF_MEM *bptr; + + b64 = BIO_new(BIO_f_base64()); + bmem = BIO_new(BIO_s_mem()); + b64 = BIO_push(b64, bmem); + BIO_write(b64, input, length); + if (BIO_flush(b64) == 1) + { + BIO_get_mem_ptr(b64, &bptr); + memcpy(output, bptr->data, bptr->length-1); + output[bptr->length-1] = '\0'; + } + else + { + RTMP_Log(RTMP_LOGDEBUG, "%s, error", __FUNCTION__); + return 0; + } + BIO_free_all(b64); +#endif + return 1; +} + +#ifdef USE_POLARSSL +#define MD5_CTX md5_context +#define MD5_Init(ctx) md5_starts(ctx) +#define MD5_Update(ctx,data,len) md5_update(ctx,(unsigned char *)data,len) +#define MD5_Final(dig,ctx) md5_finish(ctx,dig) +#elif defined(USE_GNUTLS) +typedef struct md5_ctx MD5_CTX; +#define MD5_Init(ctx) md5_init(ctx) +#define MD5_Update(ctx,data,len) md5_update(ctx,len,data) +#define MD5_Final(dig,ctx) md5_digest(ctx,MD5_DIGEST_LENGTH,dig) +#else +#endif + +static const AVal av_authmod_adobe = AVC("authmod=adobe"); +static const AVal av_authmod_llnw = AVC("authmod=llnw"); + +static void hexenc(unsigned char *inbuf, int len, char *dst) +{ + char *ptr = dst; + while(len--) { + sprintf(ptr, "%02x", *inbuf++); + ptr += 2; + } + *ptr = '\0'; +} + +static int +PublisherAuth(RTMP *r, AVal *description) +{ + char *token_in = NULL; + char *ptr; + unsigned char md5sum_val[MD5_DIGEST_LENGTH+1]; + MD5_CTX md5ctx; + int challenge2_data; +#define RESPONSE_LEN 32 +#define CHALLENGE2_LEN 16 +#define SALTED2_LEN (32+8+8+8) +#define B64DIGEST_LEN 24 /* 16 byte digest => 22 b64 chars + 2 chars padding */ +#define B64INT_LEN 8 /* 4 byte int => 6 b64 chars + 2 chars padding */ +#define HEXHASH_LEN (2*MD5_DIGEST_LENGTH) + char response[RESPONSE_LEN]; + char challenge2[CHALLENGE2_LEN]; + char salted2[SALTED2_LEN]; + AVal pubToken; + + if (strstr(description->av_val, av_authmod_adobe.av_val) != NULL) + { + if(strstr(description->av_val, "code=403 need auth") != NULL) + { + if (strstr(r->Link.app.av_val, av_authmod_adobe.av_val) != NULL) { + RTMP_Log(RTMP_LOGERROR, "%s, wrong pubUser & pubPasswd for publisher auth", __FUNCTION__); + r->Link.pFlags |= RTMP_PUB_CLEAN; + return 0; + } else if(r->Link.pubUser.av_len && r->Link.pubPasswd.av_len) { + pubToken.av_val = malloc(r->Link.pubUser.av_len + av_authmod_adobe.av_len + 8); + pubToken.av_len = sprintf(pubToken.av_val, "?%s&user=%s", + av_authmod_adobe.av_val, + r->Link.pubUser.av_val); + RTMP_Log(RTMP_LOGDEBUG, "%s, pubToken1: %s", __FUNCTION__, pubToken.av_val); + r->Link.pFlags |= RTMP_PUB_NAME; + } else { + RTMP_Log(RTMP_LOGERROR, "%s, need to set pubUser & pubPasswd for publisher auth", __FUNCTION__); + r->Link.pFlags |= RTMP_PUB_CLEAN; + return 0; + } + } + else if((token_in = strstr(description->av_val, "?reason=needauth")) != NULL) + { + char *par, *val = NULL, *orig_ptr; + AVal user, salt, opaque, challenge, *aptr = NULL; + opaque.av_len = 0; + challenge.av_len = 0; + + ptr = orig_ptr = strdup(token_in); + while (ptr) + { + par = ptr; + ptr = strchr(par, '&'); + if(ptr) + *ptr++ = '\0'; + + val = strchr(par, '='); + if(val) + *val++ = '\0'; + + if (aptr) { + aptr->av_len = par - aptr->av_val - 1; + aptr = NULL; + } + if (strcmp(par, "user") == 0){ + user.av_val = val; + aptr = &user; + } else if (strcmp(par, "salt") == 0){ + salt.av_val = val; + aptr = &salt; + } else if (strcmp(par, "opaque") == 0){ + opaque.av_val = val; + aptr = &opaque; + } else if (strcmp(par, "challenge") == 0){ + challenge.av_val = val; + aptr = &challenge; + } + + RTMP_Log(RTMP_LOGDEBUG, "%s, par:\"%s\" = val:\"%s\"", __FUNCTION__, par, val); + } + if (aptr) + aptr->av_len = strlen(aptr->av_val); + + /* hash1 = base64enc(md5(user + _aodbeAuthSalt + password)) */ + MD5_Init(&md5ctx); + MD5_Update(&md5ctx, user.av_val, user.av_len); + MD5_Update(&md5ctx, salt.av_val, salt.av_len); + MD5_Update(&md5ctx, r->Link.pubPasswd.av_val, r->Link.pubPasswd.av_len); + MD5_Final(md5sum_val, &md5ctx); + RTMP_Log(RTMP_LOGDEBUG, "%s, md5(%s%s%s) =>", __FUNCTION__, + user.av_val, salt.av_val, r->Link.pubPasswd.av_val); + RTMP_LogHexString(RTMP_LOGDEBUG, md5sum_val, MD5_DIGEST_LENGTH); + + b64enc(md5sum_val, MD5_DIGEST_LENGTH, salted2, SALTED2_LEN); + RTMP_Log(RTMP_LOGDEBUG, "%s, b64(md5_1) = %s", __FUNCTION__, salted2); + + challenge2_data = rand(); + + b64enc((unsigned char *) &challenge2_data, sizeof(int), challenge2, CHALLENGE2_LEN); + RTMP_Log(RTMP_LOGDEBUG, "%s, b64(%d) = %s", __FUNCTION__, challenge2_data, challenge2); + + MD5_Init(&md5ctx); + MD5_Update(&md5ctx, salted2, B64DIGEST_LEN); + /* response = base64enc(md5(hash1 + opaque + challenge2)) */ + if (opaque.av_len) + MD5_Update(&md5ctx, opaque.av_val, opaque.av_len); + else if (challenge.av_len) + MD5_Update(&md5ctx, challenge.av_val, challenge.av_len); + MD5_Update(&md5ctx, challenge2, B64INT_LEN); + MD5_Final(md5sum_val, &md5ctx); + + RTMP_Log(RTMP_LOGDEBUG, "%s, md5(%s%s%s) =>", __FUNCTION__, + salted2, opaque.av_len ? opaque.av_val : "", challenge2); + RTMP_LogHexString(RTMP_LOGDEBUG, md5sum_val, MD5_DIGEST_LENGTH); + + b64enc(md5sum_val, MD5_DIGEST_LENGTH, response, RESPONSE_LEN); + RTMP_Log(RTMP_LOGDEBUG, "%s, b64(md5_2) = %s", __FUNCTION__, response); + + /* have all hashes, create auth token for the end of app */ + pubToken.av_val = malloc(32 + B64INT_LEN + B64DIGEST_LEN + opaque.av_len); + pubToken.av_len = sprintf(pubToken.av_val, + "&challenge=%s&response=%s&opaque=%s", + challenge2, + response, + opaque.av_len ? opaque.av_val : ""); + RTMP_Log(RTMP_LOGDEBUG, "%s, pubToken2: %s", __FUNCTION__, pubToken.av_val); + free(orig_ptr); + r->Link.pFlags |= RTMP_PUB_RESP|RTMP_PUB_CLATE; + } + else if(strstr(description->av_val, "?reason=authfailed") != NULL) + { + RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed: wrong password", __FUNCTION__); + r->Link.pFlags |= RTMP_PUB_CLEAN; + return 0; + } + else if(strstr(description->av_val, "?reason=nosuchuser") != NULL) + { + RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed: no such user", __FUNCTION__); + r->Link.pFlags |= RTMP_PUB_CLEAN; + return 0; + } + else + { + RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed: unknown auth mode: %s", + __FUNCTION__, description->av_val); + r->Link.pFlags |= RTMP_PUB_CLEAN; + return 0; + } + + ptr = malloc(r->Link.app.av_len + pubToken.av_len); + strncpy(ptr, r->Link.app.av_val, r->Link.app.av_len); + strncpy(ptr + r->Link.app.av_len, pubToken.av_val, pubToken.av_len); + r->Link.app.av_len += pubToken.av_len; + if(r->Link.pFlags & RTMP_PUB_ALLOC) + free(r->Link.app.av_val); + r->Link.app.av_val = ptr; + + ptr = malloc(r->Link.tcUrl.av_len + pubToken.av_len); + strncpy(ptr, r->Link.tcUrl.av_val, r->Link.tcUrl.av_len); + strncpy(ptr + r->Link.tcUrl.av_len, pubToken.av_val, pubToken.av_len); + r->Link.tcUrl.av_len += pubToken.av_len; + if(r->Link.pFlags & RTMP_PUB_ALLOC) + free(r->Link.tcUrl.av_val); + r->Link.tcUrl.av_val = ptr; + + free(pubToken.av_val); + r->Link.pFlags |= RTMP_PUB_ALLOC; + + RTMP_Log(RTMP_LOGDEBUG, "%s, new app: %.*s tcUrl: %.*s playpath: %s", __FUNCTION__, + r->Link.app.av_len, r->Link.app.av_val, + r->Link.tcUrl.av_len, r->Link.tcUrl.av_val, + r->Link.playpath.av_val); + } + else if (strstr(description->av_val, av_authmod_llnw.av_val) != NULL) + { + if(strstr(description->av_val, "code=403 need auth") != NULL) + { + /* This part seems to be the same for llnw and adobe */ + + if (strstr(r->Link.app.av_val, av_authmod_llnw.av_val) != NULL) { + RTMP_Log(RTMP_LOGERROR, "%s, wrong pubUser & pubPasswd for publisher auth", __FUNCTION__); + r->Link.pFlags |= RTMP_PUB_CLEAN; + return 0; + } else if(r->Link.pubUser.av_len && r->Link.pubPasswd.av_len) { + pubToken.av_val = malloc(r->Link.pubUser.av_len + av_authmod_llnw.av_len + 8); + pubToken.av_len = sprintf(pubToken.av_val, "?%s&user=%s", + av_authmod_llnw.av_val, + r->Link.pubUser.av_val); + RTMP_Log(RTMP_LOGDEBUG, "%s, pubToken1: %s", __FUNCTION__, pubToken.av_val); + r->Link.pFlags |= RTMP_PUB_NAME; + } else { + RTMP_Log(RTMP_LOGERROR, "%s, need to set pubUser & pubPasswd for publisher auth", __FUNCTION__); + r->Link.pFlags |= RTMP_PUB_CLEAN; + return 0; + } + } + else if((token_in = strstr(description->av_val, "?reason=needauth")) != NULL) + { + char *orig_ptr; + char *par, *val = NULL; + char hash1[HEXHASH_LEN+1], hash2[HEXHASH_LEN+1], hash3[HEXHASH_LEN+1]; + AVal user, nonce, *aptr = NULL; + AVal apptmp; + + /* llnw auth method + * Seems to be closely based on HTTP Digest Auth: + * http://tools.ietf.org/html/rfc2617 + * http://en.wikipedia.org/wiki/Digest_access_authentication + */ + + const char authmod[] = "llnw"; + const char realm[] = "live"; + const char method[] = "publish"; + const char qop[] = "auth"; + /* nc = 1..connection count (or rather, number of times cnonce has been reused) */ + int nc = 1; + /* nchex = hexenc(nc) (8 hex digits according to RFC 2617) */ + char nchex[9]; + /* cnonce = hexenc(4 random bytes) (initialized on first connection) */ + char cnonce[9]; + + ptr = orig_ptr = strdup(token_in); + /* Extract parameters (we need user and nonce) */ + while (ptr) + { + par = ptr; + ptr = strchr(par, '&'); + if(ptr) + *ptr++ = '\0'; + + val = strchr(par, '='); + if(val) + *val++ = '\0'; + + if (aptr) { + aptr->av_len = par - aptr->av_val - 1; + aptr = NULL; + } + if (strcmp(par, "user") == 0){ + user.av_val = val; + aptr = &user; + } else if (strcmp(par, "nonce") == 0){ + nonce.av_val = val; + aptr = &nonce; + } + + RTMP_Log(RTMP_LOGDEBUG, "%s, par:\"%s\" = val:\"%s\"", __FUNCTION__, par, val); + } + if (aptr) + aptr->av_len = strlen(aptr->av_val); + + /* FIXME: handle case where user==NULL or nonce==NULL */ + + sprintf(nchex, "%08x", nc); + sprintf(cnonce, "%08x", rand()); + + /* hash1 = hexenc(md5(user + ":" + realm + ":" + password)) */ + MD5_Init(&md5ctx); + MD5_Update(&md5ctx, user.av_val, user.av_len); + MD5_Update(&md5ctx, ":", 1); + MD5_Update(&md5ctx, realm, sizeof(realm)-1); + MD5_Update(&md5ctx, ":", 1); + MD5_Update(&md5ctx, r->Link.pubPasswd.av_val, r->Link.pubPasswd.av_len); + MD5_Final(md5sum_val, &md5ctx); + RTMP_Log(RTMP_LOGDEBUG, "%s, md5(%s:%s:%s) =>", __FUNCTION__, + user.av_val, realm, r->Link.pubPasswd.av_val); + RTMP_LogHexString(RTMP_LOGDEBUG, md5sum_val, MD5_DIGEST_LENGTH); + hexenc(md5sum_val, MD5_DIGEST_LENGTH, hash1); + + /* hash2 = hexenc(md5(method + ":/" + app + "/" + appInstance)) */ + /* Extract appname + appinstance without query parameters */ + apptmp = r->Link.app; + ptr = strchr(apptmp.av_val, '?'); + if (ptr) + apptmp.av_len = ptr - apptmp.av_val; + + MD5_Init(&md5ctx); + MD5_Update(&md5ctx, method, sizeof(method)-1); + MD5_Update(&md5ctx, ":/", 2); + MD5_Update(&md5ctx, apptmp.av_val, apptmp.av_len); + MD5_Final(md5sum_val, &md5ctx); + RTMP_Log(RTMP_LOGDEBUG, "%s, md5(%s:/%.*s) =>", __FUNCTION__, + method, apptmp.av_len, apptmp.av_val); + RTMP_LogHexString(RTMP_LOGDEBUG, md5sum_val, MD5_DIGEST_LENGTH); + hexenc(md5sum_val, MD5_DIGEST_LENGTH, hash2); + + /* hash3 = hexenc(md5(hash1 + ":" + nonce + ":" + nchex + ":" + cnonce + ":" + qop + ":" + hash2)) */ + MD5_Init(&md5ctx); + MD5_Update(&md5ctx, hash1, HEXHASH_LEN); + MD5_Update(&md5ctx, ":", 1); + MD5_Update(&md5ctx, nonce.av_val, nonce.av_len); + MD5_Update(&md5ctx, ":", 1); + MD5_Update(&md5ctx, nchex, sizeof(nchex)-1); + MD5_Update(&md5ctx, ":", 1); + MD5_Update(&md5ctx, cnonce, sizeof(cnonce)-1); + MD5_Update(&md5ctx, ":", 1); + MD5_Update(&md5ctx, qop, sizeof(qop)-1); + MD5_Update(&md5ctx, ":", 1); + MD5_Update(&md5ctx, hash2, HEXHASH_LEN); + MD5_Final(md5sum_val, &md5ctx); + RTMP_Log(RTMP_LOGDEBUG, "%s, md5(%s:%s:%s:%s:%s:%s) =>", __FUNCTION__, + hash1, nonce.av_val, nchex, cnonce, qop, hash2); + RTMP_LogHexString(RTMP_LOGDEBUG, md5sum_val, MD5_DIGEST_LENGTH); + hexenc(md5sum_val, MD5_DIGEST_LENGTH, hash3); + + /* pubToken = &authmod=&user=&nonce=&cnonce=&nc=&response= */ + /* Append nonces and response to query string which already contains + * user + authmod */ + pubToken.av_val = malloc(64 + sizeof(authmod)-1 + user.av_len + nonce.av_len + sizeof(cnonce)-1 + sizeof(nchex)-1 + HEXHASH_LEN); + sprintf(pubToken.av_val, + "&nonce=%s&cnonce=%s&nc=%s&response=%s", + nonce.av_val, cnonce, nchex, hash3); + pubToken.av_len = strlen(pubToken.av_val); + RTMP_Log(RTMP_LOGDEBUG, "%s, pubToken2: %s", __FUNCTION__, pubToken.av_val); + r->Link.pFlags |= RTMP_PUB_RESP|RTMP_PUB_CLATE; + + free(orig_ptr); + } + else if(strstr(description->av_val, "?reason=authfail") != NULL) + { + RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed", __FUNCTION__); + r->Link.pFlags |= RTMP_PUB_CLEAN; + return 0; + } + else if(strstr(description->av_val, "?reason=nosuchuser") != NULL) + { + RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed: no such user", __FUNCTION__); + r->Link.pFlags |= RTMP_PUB_CLEAN; + return 0; + } + else + { + RTMP_Log(RTMP_LOGERROR, "%s, Authentication failed: unknown auth mode: %s", + __FUNCTION__, description->av_val); + r->Link.pFlags |= RTMP_PUB_CLEAN; + return 0; + } + + ptr = malloc(r->Link.app.av_len + pubToken.av_len); + strncpy(ptr, r->Link.app.av_val, r->Link.app.av_len); + strncpy(ptr + r->Link.app.av_len, pubToken.av_val, pubToken.av_len); + r->Link.app.av_len += pubToken.av_len; + if(r->Link.pFlags & RTMP_PUB_ALLOC) + free(r->Link.app.av_val); + r->Link.app.av_val = ptr; + + ptr = malloc(r->Link.tcUrl.av_len + pubToken.av_len); + strncpy(ptr, r->Link.tcUrl.av_val, r->Link.tcUrl.av_len); + strncpy(ptr + r->Link.tcUrl.av_len, pubToken.av_val, pubToken.av_len); + r->Link.tcUrl.av_len += pubToken.av_len; + if(r->Link.pFlags & RTMP_PUB_ALLOC) + free(r->Link.tcUrl.av_val); + r->Link.tcUrl.av_val = ptr; + + free(pubToken.av_val); + r->Link.pFlags |= RTMP_PUB_ALLOC; + + RTMP_Log(RTMP_LOGDEBUG, "%s, new app: %.*s tcUrl: %.*s playpath: %s", __FUNCTION__, + r->Link.app.av_len, r->Link.app.av_val, + r->Link.tcUrl.av_len, r->Link.tcUrl.av_val, + r->Link.playpath.av_val); + } + else + { + return 0; + } + return 1; +} +#endif + + +SAVC(onBWDone); +SAVC(onFCSubscribe); +SAVC(onFCUnsubscribe); +SAVC(_onbwcheck); +SAVC(_onbwdone); +SAVC(_error); +SAVC(close); +SAVC(code); +SAVC(level); +SAVC(description); +SAVC(onStatus); +SAVC(playlist_ready); +static const AVal av_NetStream_Failed = AVC("NetStream.Failed"); +static const AVal av_NetStream_Play_Failed = AVC("NetStream.Play.Failed"); +static const AVal av_NetStream_Play_StreamNotFound = +AVC("NetStream.Play.StreamNotFound"); +static const AVal av_NetConnection_Connect_InvalidApp = +AVC("NetConnection.Connect.InvalidApp"); +static const AVal av_NetStream_Play_Start = AVC("NetStream.Play.Start"); +static const AVal av_NetStream_Play_Complete = AVC("NetStream.Play.Complete"); +static const AVal av_NetStream_Play_Stop = AVC("NetStream.Play.Stop"); +static const AVal av_NetStream_Seek_Notify = AVC("NetStream.Seek.Notify"); +static const AVal av_NetStream_Pause_Notify = AVC("NetStream.Pause.Notify"); +static const AVal av_NetStream_Play_PublishNotify = +AVC("NetStream.Play.PublishNotify"); +static const AVal av_NetStream_Play_UnpublishNotify = +AVC("NetStream.Play.UnpublishNotify"); +static const AVal av_NetStream_Publish_Start = AVC("NetStream.Publish.Start"); +static const AVal av_NetConnection_Connect_Rejected = +AVC("NetConnection.Connect.Rejected"); + +/* Returns 0 for OK/Failed/error, 1 for 'Stop or Complete' */ +static int +HandleInvoke(RTMP *r, const char *body, unsigned int nBodySize) +{ + AMFObject obj; + AVal method; + double txn; + int ret = 0, nRes; + if (body[0] != 0x02) /* make sure it is a string method name we start with */ + { + RTMP_Log(RTMP_LOGWARNING, "%s, Sanity failed. no string method in invoke packet", + __FUNCTION__); + return 0; + } + + nRes = AMF_Decode(&obj, body, nBodySize, FALSE); + if (nRes < 0) + { + RTMP_Log(RTMP_LOGERROR, "%s, error decoding invoke packet", __FUNCTION__); + return 0; + } + + AMF_Dump(&obj); + AMFProp_GetString(AMF_GetProp(&obj, NULL, 0), &method); + txn = AMFProp_GetNumber(AMF_GetProp(&obj, NULL, 1)); + RTMP_Log(RTMP_LOGDEBUG, "%s, server invoking <%s>", __FUNCTION__, method.av_val); + + if (AVMATCH(&method, &av__result)) + { + AVal methodInvoked = {0}; + int i; + + for (i=0; im_numCalls; i++) { + if (r->m_methodCalls[i].num == (int)txn) { + methodInvoked = r->m_methodCalls[i].name; + AV_erase(r->m_methodCalls, &r->m_numCalls, i, FALSE); + break; + } + } + if (!methodInvoked.av_val) { + RTMP_Log(RTMP_LOGDEBUG, "%s, received result id %f without matching request", + __FUNCTION__, txn); + goto leave; + } + + RTMP_Log(RTMP_LOGDEBUG, "%s, received result for method call <%s>", __FUNCTION__, + methodInvoked.av_val); + + if (AVMATCH(&methodInvoked, &av_connect)) + { + if (r->Link.token.av_len) + { + AMFObjectProperty p; + if (RTMP_FindFirstMatchingProperty(&obj, &av_secureToken, &p)) + { + DecodeTEA(&r->Link.token, &p.p_vu.p_aval); + SendSecureTokenResponse(r, &p.p_vu.p_aval); + } + } + if (r->Link.protocol & RTMP_FEATURE_WRITE) + { + SendReleaseStream(r); + SendFCPublish(r); + } + else + { + RTMP_SendServerBW(r); + RTMP_SendCtrl(r, 3, 0, 300); + } + RTMP_SendCreateStream(r); + + if (!(r->Link.protocol & RTMP_FEATURE_WRITE)) + { + /* Authenticate on Justin.tv legacy servers before sending FCSubscribe */ + if (r->Link.usherToken.av_len) + SendUsherToken(r, &r->Link.usherToken); + /* Send the FCSubscribe if live stream or if subscribepath is set */ + if (r->Link.subscribepath.av_len) + SendFCSubscribe(r, &r->Link.subscribepath); + else if (r->Link.lFlags & RTMP_LF_LIVE) + SendFCSubscribe(r, &r->Link.playpath); + } + } + else if (AVMATCH(&methodInvoked, &av_createStream)) + { + r->m_stream_id = (int)AMFProp_GetNumber(AMF_GetProp(&obj, NULL, 3)); + + if (r->Link.protocol & RTMP_FEATURE_WRITE) + { + SendPublish(r); + } + else + { + if (r->Link.lFlags & RTMP_LF_PLST) + SendPlaylist(r); + SendPlay(r); + RTMP_SendCtrl(r, 3, r->m_stream_id, r->m_nBufferMS); + } + } + else if (AVMATCH(&methodInvoked, &av_play) || + AVMATCH(&methodInvoked, &av_publish)) + { + r->m_bPlaying = TRUE; + } + free(methodInvoked.av_val); + } + else if (AVMATCH(&method, &av_onBWDone)) + { + if (!r->m_nBWCheckCounter) + SendCheckBW(r); + } + else if (AVMATCH(&method, &av_onFCSubscribe)) + { + /* SendOnFCSubscribe(); */ + } + else if (AVMATCH(&method, &av_onFCUnsubscribe)) + { + RTMP_Close(r); + ret = 1; + } + else if (AVMATCH(&method, &av_ping)) + { + SendPong(r, txn); + } + else if (AVMATCH(&method, &av__onbwcheck)) + { + SendCheckBWResult(r, txn); + } + else if (AVMATCH(&method, &av__onbwdone)) + { + int i; + for (i = 0; i < r->m_numCalls; i++) + if (AVMATCH(&r->m_methodCalls[i].name, &av__checkbw)) + { + AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE); + break; + } + } + else if (AVMATCH(&method, &av__error)) + { +#ifdef CRYPTO + AVal methodInvoked = {0}; + int i; + + if (r->Link.protocol & RTMP_FEATURE_WRITE) + { + for (i=0; im_numCalls; i++) + { + if (r->m_methodCalls[i].num == txn) + { + methodInvoked = r->m_methodCalls[i].name; + AV_erase(r->m_methodCalls, &r->m_numCalls, i, FALSE); + break; + } + } + if (!methodInvoked.av_val) + { + RTMP_Log(RTMP_LOGDEBUG, "%s, received result id %f without matching request", + __FUNCTION__, txn); + goto leave; + } + + RTMP_Log(RTMP_LOGDEBUG, "%s, received error for method call <%s>", __FUNCTION__, + methodInvoked.av_val); + + if (AVMATCH(&methodInvoked, &av_connect)) + { + AMFObject obj2; + AVal code, level, description; + AMFProp_GetObject(AMF_GetProp(&obj, NULL, 3), &obj2); + AMFProp_GetString(AMF_GetProp(&obj2, &av_code, -1), &code); + AMFProp_GetString(AMF_GetProp(&obj2, &av_level, -1), &level); + AMFProp_GetString(AMF_GetProp(&obj2, &av_description, -1), &description); + RTMP_Log(RTMP_LOGDEBUG, "%s, error description: %s", __FUNCTION__, description.av_val); + /* if PublisherAuth returns 1, then reconnect */ + PublisherAuth(r, &description); + } + } + else + { + RTMP_Log(RTMP_LOGERROR, "rtmp server sent error"); + } + free(methodInvoked.av_val); +#else + RTMP_Log(RTMP_LOGERROR, "rtmp server sent error"); +#endif + } + else if (AVMATCH(&method, &av_close)) + { + RTMP_Log(RTMP_LOGERROR, "rtmp server requested close"); + RTMP_Close(r); +#ifdef CRYPTO + if ((r->Link.protocol & RTMP_FEATURE_WRITE) && + !(r->Link.pFlags & RTMP_PUB_CLEAN) && + ( !(r->Link.pFlags & RTMP_PUB_NAME) || + !(r->Link.pFlags & RTMP_PUB_RESP) || + (r->Link.pFlags & RTMP_PUB_CLATE) ) ) + { + /* clean later */ + if(r->Link.pFlags & RTMP_PUB_CLATE) + r->Link.pFlags |= RTMP_PUB_CLEAN; + RTMP_Log(RTMP_LOGERROR, "authenticating publisher"); + + if (!RTMP_Connect(r, NULL) || !RTMP_ConnectStream(r, 0)) + goto leave; + } +#endif + } + else if (AVMATCH(&method, &av_onStatus)) + { + AMFObject obj2; + AVal code, level; + AMFProp_GetObject(AMF_GetProp(&obj, NULL, 3), &obj2); + AMFProp_GetString(AMF_GetProp(&obj2, &av_code, -1), &code); + AMFProp_GetString(AMF_GetProp(&obj2, &av_level, -1), &level); + + RTMP_Log(RTMP_LOGDEBUG, "%s, onStatus: %s", __FUNCTION__, code.av_val); + if (AVMATCH(&code, &av_NetStream_Failed) + || AVMATCH(&code, &av_NetStream_Play_Failed) + || AVMATCH(&code, &av_NetStream_Play_StreamNotFound) + || AVMATCH(&code, &av_NetConnection_Connect_InvalidApp)) + { + r->m_stream_id = -1; + RTMP_Close(r); + RTMP_Log(RTMP_LOGERROR, "Closing connection: %s", code.av_val); + } + + else if (AVMATCH(&code, &av_NetStream_Play_Start) + || AVMATCH(&code, &av_NetStream_Play_PublishNotify)) + { + int i; + r->m_bPlaying = TRUE; + for (i = 0; i < r->m_numCalls; i++) + { + if (AVMATCH(&r->m_methodCalls[i].name, &av_play)) + { + AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE); + break; + } + } + } + + else if (AVMATCH(&code, &av_NetStream_Publish_Start)) + { + int i; + r->m_bPlaying = TRUE; + for (i = 0; i < r->m_numCalls; i++) + { + if (AVMATCH(&r->m_methodCalls[i].name, &av_publish)) + { + AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE); + break; + } + } + } + + /* Return 1 if this is a Play.Complete or Play.Stop */ + else if (AVMATCH(&code, &av_NetStream_Play_Complete) + || AVMATCH(&code, &av_NetStream_Play_Stop) + || AVMATCH(&code, &av_NetStream_Play_UnpublishNotify)) + { + RTMP_Close(r); + ret = 1; + } + + else if (AVMATCH(&code, &av_NetStream_Seek_Notify)) + { + r->m_read.flags &= ~RTMP_READ_SEEKING; + } + + else if (AVMATCH(&code, &av_NetStream_Pause_Notify)) + { + if (r->m_pausing == 1 || r->m_pausing == 2) + { + RTMP_SendPause(r, FALSE, r->m_pauseStamp); + r->m_pausing = 3; + } + } + } + else if (AVMATCH(&method, &av_playlist_ready)) + { + int i; + for (i = 0; i < r->m_numCalls; i++) + { + if (AVMATCH(&r->m_methodCalls[i].name, &av_set_playlist)) + { + AV_erase(r->m_methodCalls, &r->m_numCalls, i, TRUE); + break; + } + } + } + else + { + + } +leave: + AMF_Reset(&obj); + return ret; +} + +int +RTMP_FindFirstMatchingProperty(AMFObject *obj, const AVal *name, + AMFObjectProperty * p) +{ + int n; + /* this is a small object search to locate the "duration" property */ + for (n = 0; n < obj->o_num; n++) + { + AMFObjectProperty *prop = AMF_GetProp(obj, NULL, n); + + if (AVMATCH(&prop->p_name, name)) + { + memcpy(p, prop, sizeof(*prop)); + return TRUE; + } + + if (prop->p_type == AMF_OBJECT || prop->p_type == AMF_ECMA_ARRAY) + { + if (RTMP_FindFirstMatchingProperty(&prop->p_vu.p_object, name, p)) + return TRUE; + } + } + return FALSE; +} + +/* Like above, but only check if name is a prefix of property */ +int +RTMP_FindPrefixProperty(AMFObject *obj, const AVal *name, + AMFObjectProperty * p) +{ + int n; + for (n = 0; n < obj->o_num; n++) + { + AMFObjectProperty *prop = AMF_GetProp(obj, NULL, n); + + if (prop->p_name.av_len > name->av_len && + !memcmp(prop->p_name.av_val, name->av_val, name->av_len)) + { + memcpy(p, prop, sizeof(*prop)); + return TRUE; + } + + if (prop->p_type == AMF_OBJECT) + { + if (RTMP_FindPrefixProperty(&prop->p_vu.p_object, name, p)) + return TRUE; + } + } + return FALSE; +} + +static int +DumpMetaData(AMFObject *obj) +{ + AMFObjectProperty *prop; + int n, len; + for (n = 0; n < obj->o_num; n++) + { + char str[256] = ""; + prop = AMF_GetProp(obj, NULL, n); + switch (prop->p_type) + { + case AMF_OBJECT: + case AMF_ECMA_ARRAY: + case AMF_STRICT_ARRAY: + if (prop->p_name.av_len) + RTMP_Log(RTMP_LOGINFO, "%.*s:", prop->p_name.av_len, prop->p_name.av_val); + DumpMetaData(&prop->p_vu.p_object); + break; + case AMF_NUMBER: + snprintf(str, 255, "%.2f", prop->p_vu.p_number); + break; + case AMF_BOOLEAN: + snprintf(str, 255, "%s", + prop->p_vu.p_number != 0. ? "TRUE" : "FALSE"); + break; + case AMF_STRING: + len = snprintf(str, 255, "%.*s", prop->p_vu.p_aval.av_len, + prop->p_vu.p_aval.av_val); + if (len >= 1 && str[len-1] == '\n') + str[len-1] = '\0'; + break; + case AMF_DATE: + snprintf(str, 255, "timestamp:%.2f", prop->p_vu.p_number); + break; + default: + snprintf(str, 255, "INVALID TYPE 0x%02x", + (unsigned char)prop->p_type); + } + if (str[0] && prop->p_name.av_len) + { + RTMP_Log(RTMP_LOGINFO, " %-22.*s%s", prop->p_name.av_len, + prop->p_name.av_val, str); + } + } + return FALSE; +} + +SAVC(onMetaData); +SAVC(duration); +SAVC(video); +SAVC(audio); + +static int +HandleMetadata(RTMP *r, char *body, unsigned int len) +{ + /* allright we get some info here, so parse it and print it */ + /* also keep duration or filesize to make a nice progress bar */ + + AMFObject obj; + AVal metastring; + int ret = FALSE; + + int nRes = AMF_Decode(&obj, body, len, FALSE); + if (nRes < 0) + { + RTMP_Log(RTMP_LOGERROR, "%s, error decoding meta data packet", __FUNCTION__); + return FALSE; + } + + AMF_Dump(&obj); + AMFProp_GetString(AMF_GetProp(&obj, NULL, 0), &metastring); + + if (AVMATCH(&metastring, &av_onMetaData)) + { + AMFObjectProperty prop; + /* Show metadata */ + RTMP_Log(RTMP_LOGINFO, "Metadata:"); + DumpMetaData(&obj); + if (RTMP_FindFirstMatchingProperty(&obj, &av_duration, &prop)) + { + r->m_fDuration = prop.p_vu.p_number; + /*RTMP_Log(RTMP_LOGDEBUG, "Set duration: %.2f", m_fDuration); */ + } + /* Search for audio or video tags */ + if (RTMP_FindPrefixProperty(&obj, &av_video, &prop)) + r->m_read.dataType |= 1; + if (RTMP_FindPrefixProperty(&obj, &av_audio, &prop)) + r->m_read.dataType |= 4; + ret = TRUE; + } + AMF_Reset(&obj); + return ret; +} + +static void +HandleChangeChunkSize(RTMP *r, const RTMPPacket *packet) +{ + if (packet->m_nBodySize >= 4) + { + r->m_inChunkSize = AMF_DecodeInt32(packet->m_body); + RTMP_Log(RTMP_LOGDEBUG, "%s, received: chunk size change to %d", __FUNCTION__, + r->m_inChunkSize); + } +} + +static void +HandleAudio(RTMP *r, const RTMPPacket *packet) +{ +} + +static void +HandleVideo(RTMP *r, const RTMPPacket *packet) +{ +} + +static void +HandleCtrl(RTMP *r, const RTMPPacket *packet) +{ + short nType = -1; + unsigned int tmp; + if (packet->m_body && packet->m_nBodySize >= 2) + nType = AMF_DecodeInt16(packet->m_body); + RTMP_Log(RTMP_LOGDEBUG, "%s, received ctrl. type: %d, len: %d", __FUNCTION__, nType, + packet->m_nBodySize); + /*RTMP_LogHex(packet.m_body, packet.m_nBodySize); */ + + if (packet->m_nBodySize >= 6) + { + switch (nType) + { + case 0: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream Begin %d", __FUNCTION__, tmp); + break; + + case 1: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream EOF %d", __FUNCTION__, tmp); + if (r->m_pausing == 1) + r->m_pausing = 2; + break; + + case 2: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream Dry %d", __FUNCTION__, tmp); + break; + + case 4: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream IsRecorded %d", __FUNCTION__, tmp); + break; + + case 6: /* server ping. reply with pong. */ + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Ping %d", __FUNCTION__, tmp); + RTMP_SendCtrl(r, 0x07, tmp, 0); + break; + + /* FMS 3.5 servers send the following two controls to let the client + * know when the server has sent a complete buffer. I.e., when the + * server has sent an amount of data equal to m_nBufferMS in duration. + * The server meters its output so that data arrives at the client + * in realtime and no faster. + * + * The rtmpdump program tries to set m_nBufferMS as large as + * possible, to force the server to send data as fast as possible. + * In practice, the server appears to cap this at about 1 hour's + * worth of data. After the server has sent a complete buffer, and + * sends this BufferEmpty message, it will wait until the play + * duration of that buffer has passed before sending a new buffer. + * The BufferReady message will be sent when the new buffer starts. + * (There is no BufferReady message for the very first buffer; + * presumably the Stream Begin message is sufficient for that + * purpose.) + * + * If the network speed is much faster than the data bitrate, then + * there may be long delays between the end of one buffer and the + * start of the next. + * + * Since usually the network allows data to be sent at + * faster than realtime, and rtmpdump wants to download the data + * as fast as possible, we use this RTMP_LF_BUFX hack: when we + * get the BufferEmpty message, we send a Pause followed by an + * Unpause. This causes the server to send the next buffer immediately + * instead of waiting for the full duration to elapse. (That's + * also the purpose of the ToggleStream function, which rtmpdump + * calls if we get a read timeout.) + * + * Media player apps don't need this hack since they are just + * going to play the data in realtime anyway. It also doesn't work + * for live streams since they obviously can only be sent in + * realtime. And it's all moot if the network speed is actually + * slower than the media bitrate. + */ + case 31: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream BufferEmpty %d", __FUNCTION__, tmp); + if (!(r->Link.lFlags & RTMP_LF_BUFX)) + break; + if (!r->m_pausing) + { + r->m_pauseStamp = r->m_mediaChannel < r->m_channelsAllocatedIn ? + r->m_channelTimestamp[r->m_mediaChannel] : 0; + RTMP_SendPause(r, TRUE, r->m_pauseStamp); + r->m_pausing = 1; + } + else if (r->m_pausing == 2) + { + RTMP_SendPause(r, FALSE, r->m_pauseStamp); + r->m_pausing = 3; + } + break; + + case 32: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream BufferReady %d", __FUNCTION__, tmp); + break; + + default: + tmp = AMF_DecodeInt32(packet->m_body + 2); + RTMP_Log(RTMP_LOGDEBUG, "%s, Stream xx %d", __FUNCTION__, tmp); + break; + } + + } + + if (nType == 0x1A) + { + RTMP_Log(RTMP_LOGDEBUG, "%s, SWFVerification ping received: ", __FUNCTION__); + if (packet->m_nBodySize > 2 && packet->m_body[2] > 0x01) + { + RTMP_Log(RTMP_LOGERROR, + "%s: SWFVerification Type %d request not supported! Patches welcome...", + __FUNCTION__, packet->m_body[2]); + } +#ifdef CRYPTO + /*RTMP_LogHex(packet.m_body, packet.m_nBodySize); */ + + /* respond with HMAC SHA256 of decompressed SWF, key is the 30byte player key, also the last 30 bytes of the server handshake are applied */ + else if (r->Link.SWFSize) + { + RTMP_SendCtrl(r, 0x1B, 0, 0); + } + else + { + RTMP_Log(RTMP_LOGERROR, + "%s: Ignoring SWFVerification request, use --swfVfy!", + __FUNCTION__); + } +#else + RTMP_Log(RTMP_LOGERROR, + "%s: Ignoring SWFVerification request, no CRYPTO support!", + __FUNCTION__); +#endif + } +} + +static void +HandleServerBW(RTMP *r, const RTMPPacket *packet) +{ + r->m_nServerBW = AMF_DecodeInt32(packet->m_body); + RTMP_Log(RTMP_LOGDEBUG, "%s: server BW = %d", __FUNCTION__, r->m_nServerBW); +} + +static void +HandleClientBW(RTMP *r, const RTMPPacket *packet) +{ + r->m_nClientBW = AMF_DecodeInt32(packet->m_body); + if (packet->m_nBodySize > 4) + r->m_nClientBW2 = packet->m_body[4]; + else + r->m_nClientBW2 = -1; + RTMP_Log(RTMP_LOGDEBUG, "%s: client BW = %d %d", __FUNCTION__, r->m_nClientBW, + r->m_nClientBW2); +} + +static int +DecodeInt32LE(const char *data) +{ + unsigned char *c = (unsigned char *)data; + unsigned int val; + + val = (c[3] << 24) | (c[2] << 16) | (c[1] << 8) | c[0]; + return val; +} + +static int +EncodeInt32LE(char *output, int nVal) +{ + output[0] = nVal; + nVal >>= 8; + output[1] = nVal; + nVal >>= 8; + output[2] = nVal; + nVal >>= 8; + output[3] = nVal; + return 4; +} + +int +RTMP_ReadPacket(RTMP *r, RTMPPacket *packet) +{ + uint8_t hbuf[RTMP_MAX_HEADER_SIZE] = { 0 }; + char *header = (char *)hbuf; + int nSize, hSize, nToRead, nChunk; + int didAlloc = FALSE; + + RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d", __FUNCTION__, r->m_sb.sb_socket); + + if (ReadN(r, (char *)hbuf, 1) != 1) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header", __FUNCTION__); + return FALSE; + } + + packet->m_headerType = (hbuf[0] & 0xc0) >> 6; + packet->m_nChannel = (hbuf[0] & 0x3f); + header++; + if (packet->m_nChannel == 0) + { + if (ReadN(r, (char *)&hbuf[1], 1) != 1) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header 2nd byte", + __FUNCTION__); + return FALSE; + } + packet->m_nChannel = hbuf[1]; + packet->m_nChannel += 64; + header++; + } + else if (packet->m_nChannel == 1) + { + int tmp; + if (ReadN(r, (char *)&hbuf[1], 2) != 2) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header 3nd byte", + __FUNCTION__); + return FALSE; + } + tmp = (hbuf[2] << 8) + hbuf[1]; + packet->m_nChannel = tmp + 64; + RTMP_Log(RTMP_LOGDEBUG, "%s, m_nChannel: %0x", __FUNCTION__, packet->m_nChannel); + header += 2; + } + + nSize = packetSize[packet->m_headerType]; + + if (packet->m_nChannel >= r->m_channelsAllocatedIn) + { + int n = packet->m_nChannel + 10; + int *timestamp = realloc(r->m_channelTimestamp, sizeof(int) * n); + RTMPPacket **packets = realloc(r->m_vecChannelsIn, sizeof(RTMPPacket*) * n); + if (!timestamp) + free(r->m_channelTimestamp); + if (!packets) + free(r->m_vecChannelsIn); + r->m_channelTimestamp = timestamp; + r->m_vecChannelsIn = packets; + if (!timestamp || !packets) { + r->m_channelsAllocatedIn = 0; + return FALSE; + } + memset(r->m_channelTimestamp + r->m_channelsAllocatedIn, 0, sizeof(int) * (n - r->m_channelsAllocatedIn)); + memset(r->m_vecChannelsIn + r->m_channelsAllocatedIn, 0, sizeof(RTMPPacket*) * (n - r->m_channelsAllocatedIn)); + r->m_channelsAllocatedIn = n; + } + + if (nSize == RTMP_LARGE_HEADER_SIZE) /* if we get a full header the timestamp is absolute */ + packet->m_hasAbsTimestamp = TRUE; + + else if (nSize < RTMP_LARGE_HEADER_SIZE) + { /* using values from the last message of this channel */ + if (r->m_vecChannelsIn[packet->m_nChannel]) + memcpy(packet, r->m_vecChannelsIn[packet->m_nChannel], + sizeof(RTMPPacket)); + } + + nSize--; + + if (nSize > 0 && ReadN(r, header, nSize) != nSize) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header. type: %x", + __FUNCTION__, (unsigned int)hbuf[0]); + return FALSE; + } + + hSize = nSize + (header - (char *)hbuf); + + if (nSize >= 3) + { + packet->m_nTimeStamp = AMF_DecodeInt24(header); + + /*RTMP_Log(RTMP_LOGDEBUG, "%s, reading RTMP packet chunk on channel %x, headersz %i, timestamp %i, abs timestamp %i", __FUNCTION__, packet.m_nChannel, nSize, packet.m_nTimeStamp, packet.m_hasAbsTimestamp); */ + + if (nSize >= 6) + { + packet->m_nBodySize = AMF_DecodeInt24(header + 3); + packet->m_nBytesRead = 0; + RTMPPacket_Free(packet); + + if (nSize > 6) + { + packet->m_packetType = header[6]; + + if (nSize == 11) + packet->m_nInfoField2 = DecodeInt32LE(header + 7); + } + } + if (packet->m_nTimeStamp == 0xffffff) + { + if (ReadN(r, header + nSize, 4) != 4) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read extended timestamp", + __FUNCTION__); + return FALSE; + } + packet->m_nTimeStamp = AMF_DecodeInt32(header + nSize); + hSize += 4; + } + } + + RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)hbuf, hSize); + + if (packet->m_nBodySize > 0 && packet->m_body == NULL) + { + if (!RTMPPacket_Alloc(packet, packet->m_nBodySize)) + { + RTMP_Log(RTMP_LOGDEBUG, "%s, failed to allocate packet", __FUNCTION__); + return FALSE; + } + didAlloc = TRUE; + packet->m_headerType = (hbuf[0] & 0xc0) >> 6; + } + + nToRead = packet->m_nBodySize - packet->m_nBytesRead; + nChunk = r->m_inChunkSize; + if (nToRead < nChunk) + nChunk = nToRead; + + /* Does the caller want the raw chunk? */ + if (packet->m_chunk) + { + packet->m_chunk->c_headerSize = hSize; + memcpy(packet->m_chunk->c_header, hbuf, hSize); + packet->m_chunk->c_chunk = packet->m_body + packet->m_nBytesRead; + packet->m_chunk->c_chunkSize = nChunk; + } + + if (ReadN(r, packet->m_body + packet->m_nBytesRead, nChunk) != nChunk) + { + RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet body. len: %u", + __FUNCTION__, packet->m_nBodySize); + return FALSE; + } + + RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)packet->m_body + packet->m_nBytesRead, nChunk); + + packet->m_nBytesRead += nChunk; + + /* keep the packet as ref for other packets on this channel */ + if (!r->m_vecChannelsIn[packet->m_nChannel]) + r->m_vecChannelsIn[packet->m_nChannel] = malloc(sizeof(RTMPPacket)); + memcpy(r->m_vecChannelsIn[packet->m_nChannel], packet, sizeof(RTMPPacket)); + + if (RTMPPacket_IsReady(packet)) + { + /* make packet's timestamp absolute */ + if (!packet->m_hasAbsTimestamp) + packet->m_nTimeStamp += r->m_channelTimestamp[packet->m_nChannel]; /* timestamps seem to be always relative!! */ + + r->m_channelTimestamp[packet->m_nChannel] = packet->m_nTimeStamp; + + /* reset the data from the stored packet. we keep the header since we may use it later if a new packet for this channel */ + /* arrives and requests to re-use some info (small packet header) */ + r->m_vecChannelsIn[packet->m_nChannel]->m_body = NULL; + r->m_vecChannelsIn[packet->m_nChannel]->m_nBytesRead = 0; + r->m_vecChannelsIn[packet->m_nChannel]->m_hasAbsTimestamp = FALSE; /* can only be false if we reuse header */ + } + else + { + packet->m_body = NULL; /* so it won't be erased on free */ + } + + return TRUE; +} + +#ifndef CRYPTO +static int +HandShake(RTMP *r, int FP9HandShake) +{ + int i; + uint32_t uptime, suptime; + int bMatch; + char type; + char clientbuf[RTMP_SIG_SIZE + 1], *clientsig = clientbuf + 1; + char serversig[RTMP_SIG_SIZE]; + + clientbuf[0] = 0x03; /* not encrypted */ + + uptime = htonl(RTMP_GetTime()); + memcpy(clientsig, &uptime, 4); + + memset(&clientsig[4], 0, 4); + +#ifdef _DEBUG + for (i = 8; i < RTMP_SIG_SIZE; i++) + clientsig[i] = 0xff; +#else + for (i = 8; i < RTMP_SIG_SIZE; i++) + clientsig[i] = (char)(rand() & 255); +#endif + + if (!WriteN(r, clientbuf, RTMP_SIG_SIZE + 1)) + return FALSE; + + if (ReadN(r, &type, 1) != 1) /* 0x03 or 0x06 */ + return FALSE; + + RTMP_Log(RTMP_LOGDEBUG, "%s: Type Answer : %02X", __FUNCTION__, type); + + if (type != clientbuf[0]) + RTMP_Log(RTMP_LOGWARNING, "%s: Type mismatch: client sent %d, server answered %d", + __FUNCTION__, clientbuf[0], type); + + if (ReadN(r, serversig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return FALSE; + + /* decode server response */ + + memcpy(&suptime, serversig, 4); + suptime = ntohl(suptime); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Server Uptime : %d", __FUNCTION__, suptime); + RTMP_Log(RTMP_LOGDEBUG, "%s: FMS Version : %d.%d.%d.%d", __FUNCTION__, + serversig[4], serversig[5], serversig[6], serversig[7]); + + /* 2nd part of handshake */ + if (!WriteN(r, serversig, RTMP_SIG_SIZE)) + return FALSE; + + if (ReadN(r, serversig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return FALSE; + + bMatch = (memcmp(serversig, clientsig, RTMP_SIG_SIZE) == 0); + if (!bMatch) + { + RTMP_Log(RTMP_LOGWARNING, "%s, client signature does not match!", __FUNCTION__); + } + return TRUE; +} + +static int +SHandShake(RTMP *r) +{ + int i; + char serverbuf[RTMP_SIG_SIZE + 1], *serversig = serverbuf + 1; + char clientsig[RTMP_SIG_SIZE]; + uint32_t uptime; + int bMatch; + + if (ReadN(r, serverbuf, 1) != 1) /* 0x03 or 0x06 */ + return FALSE; + + RTMP_Log(RTMP_LOGDEBUG, "%s: Type Request : %02X", __FUNCTION__, serverbuf[0]); + + if (serverbuf[0] != 3) + { + RTMP_Log(RTMP_LOGERROR, "%s: Type unknown: client sent %02X", + __FUNCTION__, serverbuf[0]); + return FALSE; + } + + uptime = htonl(RTMP_GetTime()); + memcpy(serversig, &uptime, 4); + + memset(&serversig[4], 0, 4); +#ifdef _DEBUG + for (i = 8; i < RTMP_SIG_SIZE; i++) + serversig[i] = 0xff; +#else + for (i = 8; i < RTMP_SIG_SIZE; i++) + serversig[i] = (char)(rand() & 255); +#endif + + if (!WriteN(r, serverbuf, RTMP_SIG_SIZE + 1)) + return FALSE; + + if (ReadN(r, clientsig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return FALSE; + + /* decode client response */ + + memcpy(&uptime, clientsig, 4); + uptime = ntohl(uptime); + + RTMP_Log(RTMP_LOGDEBUG, "%s: Client Uptime : %d", __FUNCTION__, uptime); + RTMP_Log(RTMP_LOGDEBUG, "%s: Player Version: %d.%d.%d.%d", __FUNCTION__, + clientsig[4], clientsig[5], clientsig[6], clientsig[7]); + + /* 2nd part of handshake */ + if (!WriteN(r, clientsig, RTMP_SIG_SIZE)) + return FALSE; + + if (ReadN(r, clientsig, RTMP_SIG_SIZE) != RTMP_SIG_SIZE) + return FALSE; + + bMatch = (memcmp(serversig, clientsig, RTMP_SIG_SIZE) == 0); + if (!bMatch) + { + RTMP_Log(RTMP_LOGWARNING, "%s, client signature does not match!", __FUNCTION__); + } + return TRUE; +} +#endif + +int +RTMP_SendChunk(RTMP *r, RTMPChunk *chunk) +{ + int wrote; + char hbuf[RTMP_MAX_HEADER_SIZE]; + + RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d, size=%d", __FUNCTION__, r->m_sb.sb_socket, + chunk->c_chunkSize); + RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)chunk->c_header, chunk->c_headerSize); + if (chunk->c_chunkSize) + { + char *ptr = chunk->c_chunk - chunk->c_headerSize; + RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)chunk->c_chunk, chunk->c_chunkSize); + /* save header bytes we're about to overwrite */ + memcpy(hbuf, ptr, chunk->c_headerSize); + memcpy(ptr, chunk->c_header, chunk->c_headerSize); + wrote = WriteN(r, ptr, chunk->c_headerSize + chunk->c_chunkSize); + memcpy(ptr, hbuf, chunk->c_headerSize); + } + else + wrote = WriteN(r, chunk->c_header, chunk->c_headerSize); + return wrote; +} + +RTMPResult +RTMP_SendPacket(RTMP *r, RTMPPacket *packet, int queue) +{ + const RTMPPacket *prevPacket; + uint32_t last = 0; + int nSize; + int hSize, cSize; + char *header, *hptr, *hend, hbuf[RTMP_MAX_HEADER_SIZE], c; + uint32_t t; + char *buffer, *tbuf = NULL, *toff = NULL; + int nChunkSize; + int tlen; + + if (packet->m_nChannel >= r->m_channelsAllocatedOut) + { + int n = packet->m_nChannel + 10; + RTMPPacket **packets = realloc(r->m_vecChannelsOut, sizeof(RTMPPacket*) * n); + if (!packets) { + free(r->m_vecChannelsOut); + r->m_vecChannelsOut = NULL; + r->m_channelsAllocatedOut = 0; + return RTMP_ERROR_MEM_ALLOC_FAIL; + } + r->m_vecChannelsOut = packets; + memset(r->m_vecChannelsOut + r->m_channelsAllocatedOut, 0, sizeof(RTMPPacket*) * (n - r->m_channelsAllocatedOut)); + r->m_channelsAllocatedOut = n; + } + + prevPacket = r->m_vecChannelsOut[packet->m_nChannel]; + if (prevPacket && packet->m_headerType != RTMP_PACKET_SIZE_LARGE) + { + /* compress a bit by using the prev packet's attributes */ + if (prevPacket->m_nBodySize == packet->m_nBodySize + && prevPacket->m_packetType == packet->m_packetType + && packet->m_headerType == RTMP_PACKET_SIZE_MEDIUM) + packet->m_headerType = RTMP_PACKET_SIZE_SMALL; + + if (prevPacket->m_nTimeStamp == packet->m_nTimeStamp + && packet->m_headerType == RTMP_PACKET_SIZE_SMALL) + packet->m_headerType = RTMP_PACKET_SIZE_MINIMUM; + last = prevPacket->m_nTimeStamp; + } + + if (packet->m_headerType > 3) /* sanity */ + { + RTMP_Log(RTMP_LOGERROR, "sanity failed!! trying to send header of type: 0x%02x.", + (unsigned char)packet->m_headerType); + return RTMP_ERROR_SANITY_FAIL; + } + + nSize = packetSize[packet->m_headerType]; + hSize = nSize; cSize = 0; + t = packet->m_nTimeStamp - last; + + if (packet->m_body) + { + header = packet->m_body - nSize; + hend = packet->m_body; + } + else + { + header = hbuf + 6; + hend = hbuf + sizeof(hbuf); + } + + if (packet->m_nChannel > 319) + cSize = 2; + else if (packet->m_nChannel > 63) + cSize = 1; + if (cSize) + { + header -= cSize; + hSize += cSize; + } + + if (nSize > 1 && t >= 0xffffff) + { + header -= 4; + hSize += 4; + } + + hptr = header; + c = packet->m_headerType << 6; + switch (cSize) + { + case 0: + c |= packet->m_nChannel; + break; + case 1: + break; + case 2: + c |= 1; + break; + } + *hptr++ = c; + if (cSize) + { + int tmp = packet->m_nChannel - 64; + *hptr++ = tmp & 0xff; + if (cSize == 2) + *hptr++ = tmp >> 8; + } + + if (nSize > 1) + { + hptr = AMF_EncodeInt24(hptr, hend, t > 0xffffff ? 0xffffff : t); + } + + if (nSize > 4) + { + hptr = AMF_EncodeInt24(hptr, hend, packet->m_nBodySize); + *hptr++ = packet->m_packetType; + } + + if (nSize > 8) + hptr += EncodeInt32LE(hptr, packet->m_nInfoField2); + + if (nSize > 1 && t >= 0xffffff) + hptr = AMF_EncodeInt32(hptr, hend, t); + + nSize = packet->m_nBodySize; + buffer = packet->m_body; + nChunkSize = r->m_outChunkSize; + + RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d, size=%d", __FUNCTION__, r->m_sb.sb_socket, + nSize); + /* send all chunks in one HTTP request */ + if (r->Link.protocol & RTMP_FEATURE_HTTP) + { + int chunks = (nSize+nChunkSize-1) / nChunkSize; + if (chunks > 1) + { + tlen = chunks * (cSize + 1) + nSize + hSize; + tbuf = malloc(tlen); + if (!tbuf) { + return RTMP_ERROR_MEM_ALLOC_FAIL; + } + toff = tbuf; + } + } + while (nSize + hSize) + { + int wrote; + + if (nSize < nChunkSize) + nChunkSize = nSize; + + RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)header, hSize); + RTMP_LogHexString(RTMP_LOGDEBUG2, (uint8_t *)buffer, nChunkSize); + if (tbuf) + { + memcpy(toff, header, nChunkSize + hSize); + toff += nChunkSize + hSize; + } + else + { + wrote = WriteN(r, header, nChunkSize + hSize); + if (!wrote) { + return RTMP_ERROR_SEND_PACKET_FAIL; + } + } + nSize -= nChunkSize; + buffer += nChunkSize; + hSize = 0; + + if (nSize > 0) + { + header = buffer - 1; + hSize = 1; + if (cSize) + { + header -= cSize; + hSize += cSize; + } + *header = (0xc0 | c); + if (cSize) + { + int tmp = packet->m_nChannel - 64; + header[1] = tmp & 0xff; + if (cSize == 2) + header[2] = tmp >> 8; + } + } + } + if (tbuf) + { + int wrote = WriteN(r, tbuf, toff-tbuf); + free(tbuf); + tbuf = NULL; + if (!wrote) { + return RTMP_ERROR_SEND_PACKET_FAIL; + } + } + + /* we invoked a remote method */ + if (packet->m_packetType == RTMP_PACKET_TYPE_INVOKE) + { + AVal method; + char *ptr; + ptr = packet->m_body + 1; + AMF_DecodeString(ptr, &method); + RTMP_Log(RTMP_LOGDEBUG, "Invoking %s", method.av_val); + /* keep it in call queue till result arrives */ + if (queue) { + int txn; + ptr += 3 + method.av_len; + txn = (int)AMF_DecodeNumber(ptr); + AV_queue(&r->m_methodCalls, &r->m_numCalls, &method, txn); + } + } + + if (!r->m_vecChannelsOut[packet->m_nChannel]) + r->m_vecChannelsOut[packet->m_nChannel] = malloc(sizeof(RTMPPacket)); + memcpy(r->m_vecChannelsOut[packet->m_nChannel], packet, sizeof(RTMPPacket)); + return RTMP_SUCCESS; +} + +int +RTMP_Serve(RTMP *r) +{ + return SHandShake(r); +} + +void +RTMP_Close(RTMP *r) +{ + int i; + + if (RTMP_IsConnected(r)) + { + if (r->m_stream_id > 0) + { + i = r->m_stream_id; + r->m_stream_id = 0; + if ((r->Link.protocol & RTMP_FEATURE_WRITE)) + SendFCUnpublish(r); + SendDeleteStream(r, i); + } + if (r->m_clientID.av_val) + { + HTTP_Post(r, RTMPT_CLOSE, "", 1); + free(r->m_clientID.av_val); + r->m_clientID.av_val = NULL; + r->m_clientID.av_len = 0; + } + RTMPSockBuf_Close(&r->m_sb); + } + + r->m_stream_id = -1; + r->m_sb.sb_socket = -1; + r->m_nBWCheckCounter = 0; + r->m_nBytesIn = 0; + r->m_nBytesInSent = 0; + + if (r->m_read.flags & RTMP_READ_HEADER) { + free(r->m_read.buf); + r->m_read.buf = NULL; + } + r->m_read.dataType = 0; + r->m_read.flags = 0; + r->m_read.status = 0; + r->m_read.nResumeTS = 0; + r->m_read.nIgnoredFrameCounter = 0; + r->m_read.nIgnoredFlvFrameCounter = 0; + + r->m_write.m_nBytesRead = 0; + RTMPPacket_Free(&r->m_write); + + for (i = 0; i < r->m_channelsAllocatedIn; i++) + { + if (r->m_vecChannelsIn[i]) + { + RTMPPacket_Free(r->m_vecChannelsIn[i]); + free(r->m_vecChannelsIn[i]); + r->m_vecChannelsIn[i] = NULL; + } + } + free(r->m_vecChannelsIn); + r->m_vecChannelsIn = NULL; + free(r->m_channelTimestamp); + r->m_channelTimestamp = NULL; + r->m_channelsAllocatedIn = 0; + for (i = 0; i < r->m_channelsAllocatedOut; i++) + { + if (r->m_vecChannelsOut[i]) + { + free(r->m_vecChannelsOut[i]); + r->m_vecChannelsOut[i] = NULL; + } + } + free(r->m_vecChannelsOut); + r->m_vecChannelsOut = NULL; + r->m_channelsAllocatedOut = 0; + AV_clear(r->m_methodCalls, r->m_numCalls); + r->m_methodCalls = NULL; + r->m_numCalls = 0; + r->m_numInvokes = 0; + + r->m_bPlaying = FALSE; + r->m_sb.sb_size = 0; + + r->m_msgCounter = 0; + r->m_resplen = 0; + r->m_unackd = 0; + + if (r->Link.lFlags & RTMP_LF_FTCU) + { + free(r->Link.tcUrl.av_val); + r->Link.tcUrl.av_val = NULL; + r->Link.lFlags ^= RTMP_LF_FTCU; + } + +#ifdef CRYPTO + if (!(r->Link.protocol & RTMP_FEATURE_WRITE) || (r->Link.pFlags & RTMP_PUB_CLEAN)) + { + free(r->Link.playpath0.av_val); + r->Link.playpath0.av_val = NULL; + } + if ((r->Link.protocol & RTMP_FEATURE_WRITE) && + (r->Link.pFlags & RTMP_PUB_CLEAN) && + (r->Link.pFlags & RTMP_PUB_ALLOC)) + { + free(r->Link.app.av_val); + r->Link.app.av_val = NULL; + free(r->Link.tcUrl.av_val); + r->Link.tcUrl.av_val = NULL; + } + if (r->Link.dh) + { + MDH_free(r->Link.dh); + r->Link.dh = NULL; + } + if (r->Link.rc4keyIn) + { + RC4_free(r->Link.rc4keyIn); + r->Link.rc4keyIn = NULL; + } + if (r->Link.rc4keyOut) + { + RC4_free(r->Link.rc4keyOut); + r->Link.rc4keyOut = NULL; + } +#else + free(r->Link.playpath0.av_val); + r->Link.playpath0.av_val = NULL; +#endif +} + +int +RTMPSockBuf_Fill(RTMPSockBuf *sb) +{ + int nBytes; + + if (!sb->sb_size) + sb->sb_start = sb->sb_buf; + + while (1) + { + nBytes = sizeof(sb->sb_buf) - 1 - sb->sb_size - (sb->sb_start - sb->sb_buf); +#if defined(CRYPTO) && !defined(NO_SSL) + if (sb->sb_ssl) + { + nBytes = TLS_read(sb->sb_ssl, sb->sb_start + sb->sb_size, nBytes); + } + else +#endif + { + nBytes = recv(sb->sb_socket, sb->sb_start + sb->sb_size, nBytes, 0); + } + if (nBytes != -1) + { + sb->sb_size += nBytes; + } + else + { + int sockerr = GetSockError(); + RTMP_Log(RTMP_LOGDEBUG, "%s, recv returned %d. GetSockError(): %d (%s)", + __FUNCTION__, nBytes, sockerr, strerror(sockerr)); + if (sockerr == EINTR && !RTMP_ctrlC) + continue; + + if (sockerr == EWOULDBLOCK || sockerr == EAGAIN) + { + sb->sb_timedout = TRUE; + nBytes = 0; + } + } + break; + } + + return nBytes; +} + +int +RTMPSockBuf_Send(RTMPSockBuf *sb, const char *buf, int len) +{ + int rc; + +#ifdef _DEBUG + fwrite(buf, 1, len, netstackdump); +#endif + +#if defined(CRYPTO) && !defined(NO_SSL) + if (sb->sb_ssl) + { + rc = TLS_write(sb->sb_ssl, buf, len); + } + else +#endif + { + rc = send(sb->sb_socket, buf, len, 0); + } + return rc; +} + +int +RTMPSockBuf_Close(RTMPSockBuf *sb) +{ +#if defined(CRYPTO) && !defined(NO_SSL) + if (sb->sb_ssl) + { + TLS_shutdown(sb->sb_ssl); + TLS_close(sb->sb_ssl); + sb->sb_ssl = NULL; + } +#endif + if (sb->sb_socket != -1) + return closesocket(sb->sb_socket); + return 0; +} + +#define HEX2BIN(a) (((a)&0x40)?((a)&0xf)+9:((a)&0xf)) + +static void +DecodeTEA(AVal *key, AVal *text) +{ + uint32_t *v, k[4] = { 0 }, u; + uint32_t z, y, sum = 0, e, DELTA = 0x9e3779b9; + int32_t p, q; + int i, n; + unsigned char *ptr, *out; + + /* prep key: pack 1st 16 chars into 4 LittleEndian ints */ + ptr = (unsigned char *)key->av_val; + u = 0; + n = 0; + v = k; + p = key->av_len > 16 ? 16 : key->av_len; + for (i = 0; i < p; i++) + { + u |= ptr[i] << (n * 8); + if (n == 3) + { + *v++ = u; + u = 0; + n = 0; + } + else + { + n++; + } + } + /* any trailing chars */ + if (u) + *v = u; + + /* prep text: hex2bin, multiples of 4 */ + n = (text->av_len + 7) / 8; + out = malloc(n * 8); + ptr = (unsigned char *)text->av_val; + v = (uint32_t *) out; + for (i = 0; i < n; i++) + { + u = (HEX2BIN(ptr[0]) << 4) + HEX2BIN(ptr[1]); + u |= ((HEX2BIN(ptr[2]) << 4) + HEX2BIN(ptr[3])) << 8; + u |= ((HEX2BIN(ptr[4]) << 4) + HEX2BIN(ptr[5])) << 16; + u |= ((HEX2BIN(ptr[6]) << 4) + HEX2BIN(ptr[7])) << 24; + *v++ = u; + ptr += 8; + } + v = (uint32_t *) out; + + /* http://www.movable-type.co.uk/scripts/tea-block.html */ +#define MX (((z>>5)^(y<<2)) + ((y>>3)^(z<<4))) ^ ((sum^y) + (k[(p&3)^e]^z)); + z = v[n - 1]; + y = v[0]; + q = 6 + 52 / n; + sum = q * DELTA; + while (sum != 0) + { + e = sum >> 2 & 3; + for (p = n - 1; p > 0; p--) + z = v[p - 1], y = v[p] -= MX; + z = v[n - 1]; + y = v[0] -= MX; + sum -= DELTA; + } + + text->av_len /= 2; + memcpy(text->av_val, out, text->av_len); + free(out); +} + +static int +HTTP_Post(RTMP *r, RTMPTCmd cmd, const char *buf, int len) +{ + char hbuf[512]; + int hlen = snprintf(hbuf, sizeof(hbuf), "POST /%s%s/%d HTTP/1.1\r\n" + "Host: %.*s:%d\r\n" + "Accept: */*\r\n" + "User-Agent: Shockwave Flash\r\n" + "Connection: Keep-Alive\r\n" + "Cache-Control: no-cache\r\n" + "Content-type: application/x-fcs\r\n" + "Content-length: %d\r\n\r\n", RTMPT_cmds[cmd], + r->m_clientID.av_val ? r->m_clientID.av_val : "", + r->m_msgCounter, r->Link.hostname.av_len, r->Link.hostname.av_val, + r->Link.port, len); + RTMPSockBuf_Send(&r->m_sb, hbuf, hlen); + hlen = RTMPSockBuf_Send(&r->m_sb, buf, len); + r->m_msgCounter++; + r->m_unackd++; + return hlen; +} + +static int +HTTP_read(RTMP *r, int fill) +{ + char *ptr; + int hlen; + +restart: + if (fill) + RTMPSockBuf_Fill(&r->m_sb); + if (r->m_sb.sb_size < 13) { + if (fill) + goto restart; + return -2; + } + if (strncmp(r->m_sb.sb_start, "HTTP/1.1 200 ", 13)) + return -1; + r->m_sb.sb_start[r->m_sb.sb_size] = '\0'; + if (!strstr(r->m_sb.sb_start, "\r\n\r\n")) { + if (fill) + goto restart; + return -2; + } + + ptr = r->m_sb.sb_start + sizeof("HTTP/1.1 200"); + while ((ptr = strstr(ptr, "Content-"))) { + if (!strncasecmp(ptr+8, "length:", 7)) break; + ptr += 8; + } + if (!ptr) + return -1; + hlen = atoi(ptr+16); + ptr = strstr(ptr+16, "\r\n\r\n"); + if (!ptr) + return -1; + ptr += 4; + if (ptr + (r->m_clientID.av_val ? 1 : hlen) > r->m_sb.sb_start + r->m_sb.sb_size) + { + if (fill) + goto restart; + return -2; + } + r->m_sb.sb_size -= ptr - r->m_sb.sb_start; + r->m_sb.sb_start = ptr; + r->m_unackd--; + + if (!r->m_clientID.av_val) + { + r->m_clientID.av_len = hlen; + r->m_clientID.av_val = malloc(hlen+1); + if (!r->m_clientID.av_val) + return -1; + r->m_clientID.av_val[0] = '/'; + memcpy(r->m_clientID.av_val+1, ptr, hlen-1); + r->m_clientID.av_val[hlen] = 0; + r->m_sb.sb_size = 0; + } + else + { + r->m_polling = *ptr++; + r->m_resplen = hlen - 1; + r->m_sb.sb_start++; + r->m_sb.sb_size--; + } + return 0; +} + +#define MAX_IGNORED_FRAMES 50 + +/* Read from the stream until we get a media packet. + * Returns -3 if Play.Close/Stop, -2 if fatal error, -1 if no more media + * packets, 0 if ignorable error, >0 if there is a media packet + */ +static int +Read_1_Packet(RTMP *r, char *buf, unsigned int buflen) +{ + uint32_t prevTagSize = 0; + int rtnGetNextMediaPacket = 0, ret = RTMP_ERROR_CONNECTION_LOST; + RTMPPacket packet = { 0 }; + int recopy = FALSE; + unsigned int size; + char *ptr, *pend; + uint32_t nTimeStamp = 0; + unsigned int len; + + rtnGetNextMediaPacket = RTMP_GetNextMediaPacket(r, &packet); + while (rtnGetNextMediaPacket) + { + char *packetBody = packet.m_body; + unsigned int nPacketLen = packet.m_nBodySize; + + /* Set status as RTMP_READ_COMPLETE if this was completed nicely with + * invoke message Play.Stop or Play.Complete and return RTMP_READ_DONE. + */ + if (rtnGetNextMediaPacket == 2) + { + RTMP_Log(RTMP_LOGDEBUG, + "Got Play.Complete or Play.Stop from server. " + "Assuming stream is complete"); + r->m_read.status = RTMP_READ_COMPLETE; + ret = RTMP_READ_DONE; + break; + } + + r->m_read.dataType |= (((packet.m_packetType == RTMP_PACKET_TYPE_AUDIO) << 2) | + (packet.m_packetType == RTMP_PACKET_TYPE_VIDEO)); + + if (packet.m_packetType == RTMP_PACKET_TYPE_VIDEO && nPacketLen <= 5) + { + RTMP_Log(RTMP_LOGDEBUG, "ignoring too small video packet: size: %d", + nPacketLen); + r->m_read.status = RTMP_READ_IGNORE; + ret = RTMP_SUCCESS; + break; + } + if (packet.m_packetType == RTMP_PACKET_TYPE_AUDIO && nPacketLen <= 1) + { + RTMP_Log(RTMP_LOGDEBUG, "ignoring too small audio packet: size: %d", + nPacketLen); + r->m_read.status = RTMP_READ_IGNORE; + ret = RTMP_SUCCESS; + break; + } + + if (r->m_read.flags & RTMP_READ_SEEKING) + { + r->m_read.status = RTMP_READ_IGNORE; + ret = RTMP_SUCCESS; + break; + } +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, "type: %02X, size: %d, TS: %d ms, abs TS: %d", + packet.m_packetType, nPacketLen, packet.m_nTimeStamp, + packet.m_hasAbsTimestamp); + if (packet.m_packetType == RTMP_PACKET_TYPE_VIDEO) + RTMP_Log(RTMP_LOGDEBUG, "frametype: %02X", (*packetBody & 0xf0)); +#endif + + if (r->m_read.flags & RTMP_READ_RESUME) + { + /* check the header if we get one */ + if (packet.m_nTimeStamp == 0) + { + if (r->m_read.nMetaHeaderSize > 0 + && packet.m_packetType == RTMP_PACKET_TYPE_INFO) + { + AMFObject metaObj; + int nRes = + AMF_Decode(&metaObj, packetBody, nPacketLen, FALSE); + if (nRes >= 0) + { + AVal metastring; + AMFProp_GetString(AMF_GetProp(&metaObj, NULL, 0), + &metastring); + + if (AVMATCH(&metastring, &av_onMetaData)) + { + /* compare */ + if ((r->m_read.nMetaHeaderSize != nPacketLen) || + (memcmp + (r->m_read.metaHeader, packetBody, + r->m_read.nMetaHeaderSize) != 0)) + { + r->m_read.status = RTMP_READ_ERROR; + ret = RTMP_ERROR_READ_CORRUPT_STREAM; + } + } + AMF_Reset(&metaObj); + if (r->m_read.status == RTMP_READ_ERROR) + break; + } + } + + /* check first keyframe to make sure we got the right position + * in the stream! (the first non ignored frame) + */ + if (r->m_read.nInitialFrameSize > 0) + { + /* video or audio data */ + if (packet.m_packetType == r->m_read.initialFrameType + && r->m_read.nInitialFrameSize == nPacketLen) + { + /* we don't compare the sizes since the packet can + * contain several FLV packets, just make sure the + * first frame is our keyframe (which we are going + * to rewrite) + */ + if (memcmp + (r->m_read.initialFrame, packetBody, + r->m_read.nInitialFrameSize) == 0) + { + RTMP_Log(RTMP_LOGDEBUG, "Checked keyframe successfully!"); + r->m_read.flags |= RTMP_READ_GOTKF; + /* ignore it! (what about audio data after it? it is + * handled by ignoring all 0ms frames, see below) + */ + r->m_read.status = RTMP_READ_IGNORE; + ret = RTMP_SUCCESS; + break; + } + } + + /* hande FLV streams, even though the server resends the + * keyframe as an extra video packet it is also included + * in the first FLV stream chunk and we have to compare + * it and filter it out !! + */ + if (packet.m_packetType == RTMP_PACKET_TYPE_FLASH_VIDEO) + { + /* basically we have to find the keyframe with the + * correct TS being nResumeTS + */ + unsigned int pos = 0; + uint32_t ts = 0; + + while (pos + 11 < nPacketLen) + { + /* size without header (11) and prevTagSize (4) */ + uint32_t dataSize = + AMF_DecodeInt24(packetBody + pos + 1); + ts = AMF_DecodeInt24(packetBody + pos + 4); + ts |= (packetBody[pos + 7] << 24); + +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, + "keyframe search: FLV Packet: type %02X, dataSize: %d, timeStamp: %d ms", + packetBody[pos], dataSize, ts); +#endif + /* ok, is it a keyframe?: + * well doesn't work for audio! + */ + if (packetBody[pos /*6928, test 0 */ ] == + r->m_read.initialFrameType + /* && (packetBody[11]&0xf0) == 0x10 */ ) + { + if (ts == r->m_read.nResumeTS) + { + RTMP_Log(RTMP_LOGDEBUG, + "Found keyframe with resume-keyframe timestamp!"); + if (r->m_read.nInitialFrameSize != dataSize + || memcmp(r->m_read.initialFrame, + packetBody + pos + 11, + r->m_read. + nInitialFrameSize) != 0) + { + RTMP_Log(RTMP_LOGERROR, + "FLV Stream: Keyframe doesn't match!"); + r->m_read.status = RTMP_READ_ERROR; + ret = RTMP_ERROR_KEYFRAME_TS_MISMATCH; + break; + } + r->m_read.flags |= RTMP_READ_GOTFLVK; + + /* skip this packet? + * check whether skippable: + */ + if (pos + 11 + dataSize + 4 > nPacketLen) + { + RTMP_Log(RTMP_LOGWARNING, + "Non skipable packet since it doesn't end with chunk, stream corrupt!"); + r->m_read.status = RTMP_READ_ERROR; + ret = RTMP_ERROR_READ_CORRUPT_STREAM; + break; + } + packetBody += (pos + 11 + dataSize + 4); + nPacketLen -= (pos + 11 + dataSize + 4); + + goto stopKeyframeSearch; + + } + else if (r->m_read.nResumeTS < ts) + { + /* the timestamp ts will only increase with + * further packets, wait for seek + */ + goto stopKeyframeSearch; + } + } + pos += (11 + dataSize + 4); + } + if (ts < r->m_read.nResumeTS) + { + RTMP_Log(RTMP_LOGERROR, + "First packet does not contain keyframe, all " + "timestamps are smaller than the keyframe " + "timestamp; probably the resume seek failed?"); + } + stopKeyframeSearch: + ; + if (!(r->m_read.flags & RTMP_READ_GOTFLVK)) + { + RTMP_Log(RTMP_LOGERROR, + "Couldn't find the seeked keyframe in this chunk!"); + r->m_read.status = RTMP_READ_IGNORE; + ret = RTMP_SUCCESS; + break; + } + } + } + } + + if (packet.m_nTimeStamp > 0 + && (r->m_read.flags & (RTMP_READ_GOTKF|RTMP_READ_GOTFLVK))) + { + /* another problem is that the server can actually change from + * 09/08 video/audio packets to an FLV stream or vice versa and + * our keyframe check will prevent us from going along with the + * new stream if we resumed. + * + * in this case set the 'found keyframe' variables to true. + * We assume that if we found one keyframe somewhere and were + * already beyond TS > 0 we have written data to the output + * which means we can accept all forthcoming data including the + * change between 08/09 <-> FLV packets + */ + r->m_read.flags |= (RTMP_READ_GOTKF|RTMP_READ_GOTFLVK); + } + + /* skip till we find our keyframe + * (seeking might put us somewhere before it) + */ + if (!(r->m_read.flags & RTMP_READ_GOTKF) && + packet.m_packetType != RTMP_PACKET_TYPE_FLASH_VIDEO) + { + RTMP_Log(RTMP_LOGWARNING, + "Stream does not start with requested frame, ignoring data... "); + r->m_read.nIgnoredFrameCounter++; + if (r->m_read.nIgnoredFrameCounter > MAX_IGNORED_FRAMES) + { + r->m_read.status = RTMP_READ_ERROR; /* fatal error, couldn't continue stream */ + ret = RTMP_ERROR_READ_CORRUPT_STREAM; + } + else + { + r->m_read.status = RTMP_READ_IGNORE; + ret = RTMP_SUCCESS; + } + break; + } + /* ok, do the same for FLV streams */ + if (!(r->m_read.flags & RTMP_READ_GOTFLVK) && + packet.m_packetType == RTMP_PACKET_TYPE_FLASH_VIDEO) + { + RTMP_Log(RTMP_LOGWARNING, + "Stream does not start with requested FLV frame, ignoring data... "); + r->m_read.nIgnoredFlvFrameCounter++; + if (r->m_read.nIgnoredFlvFrameCounter > MAX_IGNORED_FRAMES) + { + r->m_read.status = RTMP_READ_ERROR; + ret = RTMP_ERROR_READ_CORRUPT_STREAM; + } + else + { + r->m_read.status = RTMP_READ_IGNORE; + ret = RTMP_SUCCESS; + } + break; + } + + /* we have to ignore the 0ms frames since these are the first + * keyframes; we've got these so don't mess around with multiple + * copies sent by the server to us! (if the keyframe is found at a + * later position there is only one copy and it will be ignored by + * the preceding if clause) + */ + if (!(r->m_read.flags & RTMP_READ_NO_IGNORE) && + packet.m_packetType != RTMP_PACKET_TYPE_FLASH_VIDEO) + { + /* exclude type RTMP_PACKET_TYPE_FLASH_VIDEO since it can + * contain several FLV packets + */ + if (packet.m_nTimeStamp == 0) + { + r->m_read.status = RTMP_READ_IGNORE; + ret = RTMP_SUCCESS; + break; + } + else + { + /* stop ignoring packets */ + r->m_read.flags |= RTMP_READ_NO_IGNORE; + } + } + } + + /* calculate packet size and allocate slop buffer if necessary */ + size = nPacketLen + + ((packet.m_packetType == RTMP_PACKET_TYPE_AUDIO + || packet.m_packetType == RTMP_PACKET_TYPE_VIDEO + || packet.m_packetType == RTMP_PACKET_TYPE_INFO) ? 11 : 0) + + (packet.m_packetType != RTMP_PACKET_TYPE_FLASH_VIDEO ? 4 : 0); + + if (size + 4 > buflen) + { + /* the extra 4 is for the case of an FLV stream without a last + * prevTagSize (we need extra 4 bytes to append it) */ + r->m_read.buf = malloc(size + 4); + if (r->m_read.buf == 0) + { + RTMP_Log(RTMP_LOGERROR, "Couldn't allocate memory!"); + r->m_read.status = RTMP_READ_ERROR; /* fatal error */ + ret = RTMP_ERROR_MEM_ALLOC_FAIL; + break; + } + recopy = TRUE; + ptr = r->m_read.buf; + } + else + { + ptr = buf; + } + pend = ptr + size + 4; + + /* use to return timestamp of last processed packet */ + + /* audio (0x08), video (0x09) or metadata (0x12) packets : + * construct 11 byte header then add rtmp packet's data */ + if (packet.m_packetType == RTMP_PACKET_TYPE_AUDIO + || packet.m_packetType == RTMP_PACKET_TYPE_VIDEO + || packet.m_packetType == RTMP_PACKET_TYPE_INFO) + { + nTimeStamp = r->m_read.nResumeTS + packet.m_nTimeStamp; + prevTagSize = 11 + nPacketLen; + + *ptr = packet.m_packetType; + ptr++; + ptr = AMF_EncodeInt24(ptr, pend, nPacketLen); + +#if 0 + if(packet.m_packetType == RTMP_PACKET_TYPE_VIDEO) { + + /* H264 fix: */ + if((packetBody[0] & 0x0f) == 7) { /* CodecId = H264 */ + uint8_t packetType = *(packetBody+1); + + uint32_t ts = AMF_DecodeInt24(packetBody+2); /* composition time */ + int32_t cts = (ts+0xff800000)^0xff800000; + RTMP_Log(RTMP_LOGDEBUG, "cts : %d\n", cts); + + nTimeStamp -= cts; + /* get rid of the composition time */ + CRTMP::EncodeInt24(packetBody+2, 0); + } + RTMP_Log(RTMP_LOGDEBUG, "VIDEO: nTimeStamp: 0x%08X (%d)\n", nTimeStamp, nTimeStamp); + } +#endif + + ptr = AMF_EncodeInt24(ptr, pend, nTimeStamp); + *ptr = (char)((nTimeStamp & 0xFF000000) >> 24); + ptr++; + + /* stream id */ + ptr = AMF_EncodeInt24(ptr, pend, 0); + } + + memcpy(ptr, packetBody, nPacketLen); + len = nPacketLen; + + /* correct tagSize and obtain timestamp if we have an FLV stream */ + if (packet.m_packetType == RTMP_PACKET_TYPE_FLASH_VIDEO) + { + unsigned int pos = 0; + int delta; + + /* grab first timestamp and see if it needs fixing */ + nTimeStamp = AMF_DecodeInt24(packetBody + 4); + nTimeStamp |= (packetBody[7] << 24); + delta = packet.m_nTimeStamp - nTimeStamp + r->m_read.nResumeTS; + + while (pos + 11 < nPacketLen) + { + /* size without header (11) and without prevTagSize (4) */ + uint32_t dataSize = AMF_DecodeInt24(packetBody + pos + 1); + nTimeStamp = AMF_DecodeInt24(packetBody + pos + 4); + nTimeStamp |= (packetBody[pos + 7] << 24); + + if (delta) + { + nTimeStamp += delta; + AMF_EncodeInt24(ptr+pos+4, pend, nTimeStamp); + ptr[pos+7] = nTimeStamp>>24; + } + + /* set data type */ + r->m_read.dataType |= (((*(packetBody + pos) == 0x08) << 2) | + (*(packetBody + pos) == 0x09)); + + if (pos + 11 + dataSize + 4 > nPacketLen) + { + if (pos + 11 + dataSize > nPacketLen) + { + RTMP_Log(RTMP_LOGERROR, + "Wrong data size (%u), stream corrupted, aborting!", + dataSize); + r->m_read.status = RTMP_READ_ERROR; + ret = RTMP_ERROR_STREAM_BAD_DATASIZE; + break; + } + RTMP_Log(RTMP_LOGWARNING, "No tagSize found, appending!"); + + /* we have to append a last tagSize! */ + prevTagSize = dataSize + 11; + AMF_EncodeInt32(ptr + pos + 11 + dataSize, pend, + prevTagSize); + size += 4; + len += 4; + } + else + { + prevTagSize = + AMF_DecodeInt32(packetBody + pos + 11 + dataSize); + +#ifdef _DEBUG + RTMP_Log(RTMP_LOGDEBUG, + "FLV Packet: type %02X, dataSize: %lu, tagSize: %lu, timeStamp: %lu ms", + (unsigned char)packetBody[pos], dataSize, prevTagSize, + nTimeStamp); +#endif + + if (prevTagSize != (dataSize + 11)) + { +#ifdef _DEBUG + RTMP_Log(RTMP_LOGWARNING, + "Tag and data size are not consitent, writing tag size according to dataSize+11: %d", + dataSize + 11); +#endif + + prevTagSize = dataSize + 11; + AMF_EncodeInt32(ptr + pos + 11 + dataSize, pend, + prevTagSize); + } + } + + pos += prevTagSize + 4; /*(11+dataSize+4); */ + } + } + ptr += len; + + if (packet.m_packetType != RTMP_PACKET_TYPE_FLASH_VIDEO) + { + /* FLV tag packets contain their own prevTagSize */ + AMF_EncodeInt32(ptr, pend, prevTagSize); + } + + /* In non-live this nTimeStamp can contain an absolute TS. + * Update ext timestamp with this absolute offset in non-live mode + * otherwise report the relative one + */ + /* RTMP_Log(RTMP_LOGDEBUG, "type: %02X, size: %d, pktTS: %dms, TS: %dms, bLiveStream: %d", packet.m_packetType, nPacketLen, packet.m_nTimeStamp, nTimeStamp, r->Link.lFlags & RTMP_LF_LIVE); */ + r->m_read.timestamp = (r->Link.lFlags & RTMP_LF_LIVE) ? packet.m_nTimeStamp : nTimeStamp; + + ret = size; + break; + } + + if (rtnGetNextMediaPacket) + RTMPPacket_Free(&packet); + + if (recopy) + { + len = ret > buflen ? buflen : ret; + memcpy(buf, r->m_read.buf, len); + r->m_read.bufpos = r->m_read.buf + len; + r->m_read.buflen = ret - len; + } + return ret; +} + +static const char flvHeader[] = { 'F', 'L', 'V', 0x01, + 0x00, /* 0x04 == audio, 0x01 == video */ + 0x00, 0x00, 0x00, 0x09, + 0x00, 0x00, 0x00, 0x00 +}; + +#define HEADERBUF (128*1024) +int +RTMP_Read(RTMP *r, char *buf, int size) +{ + int nRead = 0, total = 0; + + /* first time thru */ + if (!(r->m_read.flags & RTMP_READ_HEADER)) + { + if (!(r->m_read.flags & RTMP_READ_RESUME)) + { + char *mybuf = malloc(HEADERBUF), *end = mybuf + HEADERBUF; + int cnt = 0; + r->m_read.buf = mybuf; + r->m_read.buflen = HEADERBUF; + + memcpy(mybuf, flvHeader, sizeof(flvHeader)); + r->m_read.buf += sizeof(flvHeader); + r->m_read.buflen -= sizeof(flvHeader); + cnt += sizeof(flvHeader); + + while (r->m_read.timestamp == 0) + { + nRead = Read_1_Packet(r, r->m_read.buf, r->m_read.buflen); + if (nRead < RTMP_SUCCESS) + { + free(mybuf); + r->m_read.buf = NULL; + r->m_read.buflen = 0; + if (r->m_read.status == RTMP_READ_ERROR) + { + SetSockError(EINVAL); + } + return nRead; + } + /* buffer overflow, fix buffer and give up */ + if (r->m_read.buf < mybuf || r->m_read.buf > end) { + mybuf = realloc(mybuf, cnt + nRead); + memcpy(mybuf+cnt, r->m_read.buf, nRead); + free(r->m_read.buf); + r->m_read.buf = mybuf+cnt+nRead; + break; + } + cnt += nRead; + r->m_read.buf += nRead; + r->m_read.buflen -= nRead; + if (r->m_read.dataType == 5) + break; + } + mybuf[4] = r->m_read.dataType; + r->m_read.buflen = r->m_read.buf - mybuf; + r->m_read.buf = mybuf; + r->m_read.bufpos = mybuf; + } + r->m_read.flags |= RTMP_READ_HEADER; + } + + if ((r->m_read.flags & RTMP_READ_SEEKING) && r->m_read.buf) + { + /* drop whatever's here */ + free(r->m_read.buf); + r->m_read.buf = NULL; + r->m_read.bufpos = NULL; + r->m_read.buflen = 0; + } + + /* If there's leftover data buffered, use it up */ + if (r->m_read.buf) + { + nRead = r->m_read.buflen; + if (nRead > size) + nRead = size; + memcpy(buf, r->m_read.bufpos, nRead); + r->m_read.buflen -= nRead; + if (!r->m_read.buflen) + { + free(r->m_read.buf); + r->m_read.buf = NULL; + r->m_read.bufpos = NULL; + } + else + { + r->m_read.bufpos += nRead; + } + buf += nRead; + total += nRead; + size -= nRead; + } + + while (size > 0 && (nRead = Read_1_Packet(r, buf, size)) >= 0) + { + /* We should get the number of bytes read, RTMP_SUCCESS means we read a packet to be ignored + * and the read status would be RTMP_READ_IGNORE + */ + if (nRead == RTMP_SUCCESS) continue; + buf += nRead; + total += nRead; + size -= nRead; + break; + } + if (nRead < RTMP_SUCCESS) + r->m_read.status = RTMP_READ_ERROR; + + if (size < 0) + total += size; + return total; +} + +static const AVal av_setDataFrame = AVC("@setDataFrame"); + +int +RTMP_Write(RTMP *r, const char *buf, int size) +{ + RTMPPacket *pkt = &r->m_write; + char *pend, *enc; + int s2 = size, ret, num; + + pkt->m_nChannel = 0x04; /* source channel */ + pkt->m_nInfoField2 = r->m_stream_id; + + while (s2) + { + if (!pkt->m_nBytesRead) + { + if (size < 11) { + /* FLV pkt too small */ + return RTMP_ERROR_PACKET_TOO_SMALL; + } + + if (buf[0] == 'F' && buf[1] == 'L' && buf[2] == 'V') + { + buf += 13; + s2 -= 13; + } + + pkt->m_packetType = *buf++; + pkt->m_nBodySize = AMF_DecodeInt24(buf); + buf += 3; + pkt->m_nTimeStamp = AMF_DecodeInt24(buf); + buf += 3; + pkt->m_nTimeStamp |= *buf++ << 24; + buf += 3; + s2 -= 11; + + if (((pkt->m_packetType == RTMP_PACKET_TYPE_AUDIO + || pkt->m_packetType == RTMP_PACKET_TYPE_VIDEO) && + !pkt->m_nTimeStamp) || pkt->m_packetType == RTMP_PACKET_TYPE_INFO) + { + pkt->m_headerType = RTMP_PACKET_SIZE_LARGE; + if (pkt->m_packetType == RTMP_PACKET_TYPE_INFO) + pkt->m_nBodySize += 16; + } + else + { + pkt->m_headerType = RTMP_PACKET_SIZE_MEDIUM; + } + + if (!RTMPPacket_Alloc(pkt, pkt->m_nBodySize)) + { + RTMP_Log(RTMP_LOGDEBUG, "%s, failed to allocate packet", __FUNCTION__); + return RTMP_ERROR_MEM_ALLOC_FAIL; + } + enc = pkt->m_body; + pend = enc + pkt->m_nBodySize; + if (pkt->m_packetType == RTMP_PACKET_TYPE_INFO) + { + enc = AMF_EncodeString(enc, pend, &av_setDataFrame); + pkt->m_nBytesRead = enc - pkt->m_body; + } + } + else + { + enc = pkt->m_body + pkt->m_nBytesRead; + } + num = pkt->m_nBodySize - pkt->m_nBytesRead; + if (num > s2) + num = s2; + memcpy(enc, buf, num); + pkt->m_nBytesRead += num; + s2 -= num; + buf += num; + if (pkt->m_nBytesRead == pkt->m_nBodySize) + { + ret = RTMP_SendPacket(r, pkt, FALSE); + RTMPPacket_Free(pkt); + pkt->m_nBytesRead = 0; + if (ret != RTMP_SUCCESS) { + return ret; + } + buf += 4; + s2 -= 4; + if (s2 < 0) + break; + } + } + return size+s2; +} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/rtmp.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/rtmp.h new file mode 100644 index 0000000..07bd240 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/rtmp.h @@ -0,0 +1,425 @@ +#ifndef __RTMP_H__ +#define __RTMP_H__ +/* + * Copyright (C) 2005-2008 Team XBMC + * http://www.xbmc.org + * Copyright (C) 2008-2009 Andrej Stepanchuk + * Copyright (C) 2009-2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#if !defined(NO_CRYPTO) && !defined(CRYPTO) +#define CRYPTO +#endif + +#include +#include +#include + +#include "amf.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define RTMP_LIB_VERSION 0x020300 /* 2.3 */ + +#define RTMP_FEATURE_HTTP 0x01 +#define RTMP_FEATURE_ENC 0x02 +#define RTMP_FEATURE_SSL 0x04 +#define RTMP_FEATURE_MFP 0x08 /* not yet supported */ +#define RTMP_FEATURE_WRITE 0x10 /* publish, not play */ +#define RTMP_FEATURE_HTTP2 0x20 /* server-side rtmpt */ + +#define RTMP_PROTOCOL_UNDEFINED -1 +#define RTMP_PROTOCOL_RTMP 0 +#define RTMP_PROTOCOL_RTMPE RTMP_FEATURE_ENC +#define RTMP_PROTOCOL_RTMPT RTMP_FEATURE_HTTP +#define RTMP_PROTOCOL_RTMPS RTMP_FEATURE_SSL +#define RTMP_PROTOCOL_RTMPTE (RTMP_FEATURE_HTTP|RTMP_FEATURE_ENC) +#define RTMP_PROTOCOL_RTMPTS (RTMP_FEATURE_HTTP|RTMP_FEATURE_SSL) +#define RTMP_PROTOCOL_RTMFP RTMP_FEATURE_MFP + +#define RTMP_DEFAULT_CHUNKSIZE 128 + +/* needs to fit largest number of bytes recv() may return */ +#define RTMP_BUFFER_CACHE_SIZE (16*1024) + +#define RTMP_CHANNELS 65600 + + extern const char RTMPProtocolStringsLower[][7]; + extern const AVal RTMP_DefaultFlashVer; + extern int RTMP_ctrlC; + + uint32_t RTMP_GetTime(void); + +/* RTMP_PACKET_TYPE_... 0x00 */ +#define RTMP_PACKET_TYPE_CHUNK_SIZE 0x01 +/* RTMP_PACKET_TYPE_... 0x02 */ +#define RTMP_PACKET_TYPE_BYTES_READ_REPORT 0x03 +#define RTMP_PACKET_TYPE_CONTROL 0x04 +#define RTMP_PACKET_TYPE_SERVER_BW 0x05 +#define RTMP_PACKET_TYPE_CLIENT_BW 0x06 +/* RTMP_PACKET_TYPE_... 0x07 */ +#define RTMP_PACKET_TYPE_AUDIO 0x08 +#define RTMP_PACKET_TYPE_VIDEO 0x09 +/* RTMP_PACKET_TYPE_... 0x0A */ +/* RTMP_PACKET_TYPE_... 0x0B */ +/* RTMP_PACKET_TYPE_... 0x0C */ +/* RTMP_PACKET_TYPE_... 0x0D */ +/* RTMP_PACKET_TYPE_... 0x0E */ +#define RTMP_PACKET_TYPE_FLEX_STREAM_SEND 0x0F +#define RTMP_PACKET_TYPE_FLEX_SHARED_OBJECT 0x10 +#define RTMP_PACKET_TYPE_FLEX_MESSAGE 0x11 +#define RTMP_PACKET_TYPE_INFO 0x12 +#define RTMP_PACKET_TYPE_SHARED_OBJECT 0x13 +#define RTMP_PACKET_TYPE_INVOKE 0x14 +/* RTMP_PACKET_TYPE_... 0x15 */ +#define RTMP_PACKET_TYPE_FLASH_VIDEO 0x16 + +#define RTMP_MAX_HEADER_SIZE 18 + +#define RTMP_PACKET_SIZE_LARGE 0 +#define RTMP_PACKET_SIZE_MEDIUM 1 +#define RTMP_PACKET_SIZE_SMALL 2 +#define RTMP_PACKET_SIZE_MINIMUM 3 + + typedef enum RTMPResult_ { + RTMP_SUCCESS = 0, + RTMP_READ_DONE = -1, + RTMP_ERROR_OPEN_ALLOC = -2, + RTMP_ERROR_OPEN_CONNECT_STREAM = -3, + RTMP_ERROR_UNKNOWN_RTMP_OPTION = -4, + RTMP_ERROR_UNKNOWN_RTMP_AMF_TYPE = -5, + RTMP_ERROR_DNS_NOT_REACHABLE = -6, + RTMP_ERROR_SOCKET_CONNECT_FAIL = -7, + RTMP_ERROR_SOCKS_NEGOTIATION_FAIL = -8, + RTMP_ERROR_SOCKET_CREATE_FAIL = -9, + RTMP_ERROR_NO_SSL_TLS_SUPP = -10, + RTMP_ERROR_HANDSHAKE_CONNECT_FAIL = -11, + RTMP_ERROR_HANDSHAKE_FAIL = -12, + RTMP_ERROR_CONNECT_FAIL = -13, + RTMP_ERROR_CONNECTION_LOST = -14, + RTMP_ERROR_KEYFRAME_TS_MISMATCH = -15, + RTMP_ERROR_READ_CORRUPT_STREAM = -16, + RTMP_ERROR_MEM_ALLOC_FAIL = -17, + RTMP_ERROR_STREAM_BAD_DATASIZE = -18, + RTMP_ERROR_PACKET_TOO_SMALL = -19, + RTMP_ERROR_SEND_PACKET_FAIL = -20, + RTMP_ERROR_AMF_ENCODE_FAIL = -21, + RTMP_ERROR_URL_MISSING_PROTOCOL = -22, + RTMP_ERROR_URL_MISSING_HOSTNAME = -23, + RTMP_ERROR_URL_INCORRECT_PORT = -24, + RTMP_ERROR_IGNORED = -25, + RTMP_ERROR_GENERIC = -26, + RTMP_ERROR_SANITY_FAIL = -27, + } RTMPResult; + + typedef struct RTMPChunk + { + int c_headerSize; + int c_chunkSize; + char *c_chunk; + char c_header[RTMP_MAX_HEADER_SIZE]; + } RTMPChunk; + + typedef struct RTMPPacket + { + uint8_t m_headerType; + uint8_t m_packetType; + uint8_t m_hasAbsTimestamp; /* timestamp absolute or relative? */ + int m_nChannel; + uint32_t m_nTimeStamp; /* timestamp */ + int32_t m_nInfoField2; /* last 4 bytes in a long header */ + uint32_t m_nBodySize; + uint32_t m_nBytesRead; + RTMPChunk *m_chunk; + char *m_body; + } RTMPPacket; + + typedef struct RTMPSockBuf + { + int sb_socket; + int sb_size; /* number of unprocessed bytes in buffer */ + char *sb_start; /* pointer into sb_pBuffer of next byte to process */ + char sb_buf[RTMP_BUFFER_CACHE_SIZE]; /* data read from socket */ + int sb_timedout; + void *sb_ssl; + } RTMPSockBuf; + + void RTMPPacket_Reset(RTMPPacket *p); + void RTMPPacket_Dump(RTMPPacket *p); + int RTMPPacket_Alloc(RTMPPacket *p, int nSize); + void RTMPPacket_Free(RTMPPacket *p); + +#define RTMPPacket_IsReady(a) ((a)->m_nBytesRead == (a)->m_nBodySize) + + typedef struct RTMP_LNK + { + AVal hostname; + AVal sockshost; + + AVal playpath0; /* parsed from URL */ + AVal playpath; /* passed in explicitly */ + AVal tcUrl; + AVal swfUrl; + AVal pageUrl; + AVal app; + AVal auth; + AVal flashVer; + AVal subscribepath; + AVal usherToken; + AVal token; + AVal pubUser; + AVal pubPasswd; + AMFObject extras; + int edepth; + + int seekTime; + int stopTime; + +#define RTMP_LF_AUTH 0x0001 /* using auth param */ +#define RTMP_LF_LIVE 0x0002 /* stream is live */ +#define RTMP_LF_SWFV 0x0004 /* do SWF verification */ +#define RTMP_LF_PLST 0x0008 /* send playlist before play */ +#define RTMP_LF_BUFX 0x0010 /* toggle stream on BufferEmpty msg */ +#define RTMP_LF_FTCU 0x0020 /* free tcUrl on close */ + int lFlags; + + int swfAge; + + int protocol; + int receiveTimeoutInMs; + int sendTimeoutInMs; + +#define RTMP_PUB_NAME 0x0001 /* send login to server */ +#define RTMP_PUB_RESP 0x0002 /* send salted password hash */ +#define RTMP_PUB_ALLOC 0x0004 /* allocated data for new tcUrl & app */ +#define RTMP_PUB_CLEAN 0x0008 /* need to free allocated data for newer tcUrl & app at exit */ +#define RTMP_PUB_CLATE 0x0010 /* late clean tcUrl & app at exit */ + int pFlags; + + unsigned short socksport; + unsigned short port; + +#ifdef CRYPTO +#define RTMP_SWF_HASHLEN 32 + void *dh; /* for encryption */ + void *rc4keyIn; + void *rc4keyOut; + + uint32_t SWFSize; + uint8_t SWFHash[RTMP_SWF_HASHLEN]; + char SWFVerificationResponse[RTMP_SWF_HASHLEN+10]; +#endif + } RTMP_LNK; + + /* state for read() wrapper */ + typedef struct RTMP_READ + { + char *buf; + char *bufpos; + unsigned int buflen; + uint32_t timestamp; + uint8_t dataType; + uint8_t flags; +#define RTMP_READ_HEADER 0x01 +#define RTMP_READ_RESUME 0x02 +#define RTMP_READ_NO_IGNORE 0x04 +#define RTMP_READ_GOTKF 0x08 +#define RTMP_READ_GOTFLVK 0x10 +#define RTMP_READ_SEEKING 0x20 + int8_t status; +#define RTMP_READ_COMPLETE -3 +#define RTMP_READ_ERROR -2 +#define RTMP_READ_EOF -1 +#define RTMP_READ_IGNORE 0 + + /* if bResume == TRUE */ + uint8_t initialFrameType; + uint32_t nResumeTS; + char *metaHeader; + char *initialFrame; + uint32_t nMetaHeaderSize; + uint32_t nInitialFrameSize; + uint32_t nIgnoredFrameCounter; + uint32_t nIgnoredFlvFrameCounter; + } RTMP_READ; + + typedef struct RTMP_METHOD + { + AVal name; + int num; + } RTMP_METHOD; + + typedef struct RTMP + { + int m_inChunkSize; + int m_outChunkSize; + int m_nBWCheckCounter; + int m_nBytesIn; + int m_nBytesInSent; + int m_nBufferMS; + int m_stream_id; /* returned in _result from createStream */ + int m_mediaChannel; + uint32_t m_mediaStamp; + uint32_t m_pauseStamp; + int m_pausing; + int m_nServerBW; + int m_nClientBW; + uint8_t m_nClientBW2; + uint8_t m_bPlaying; + uint8_t m_bSendEncoding; + uint8_t m_bSendCounter; + + int m_numInvokes; + int m_numCalls; + RTMP_METHOD *m_methodCalls; /* remote method calls queue */ + + int m_channelsAllocatedIn; + int m_channelsAllocatedOut; + RTMPPacket **m_vecChannelsIn; + RTMPPacket **m_vecChannelsOut; + int *m_channelTimestamp; /* abs timestamp of last packet */ + + double m_fAudioCodecs; /* audioCodecs for the connect packet */ + double m_fVideoCodecs; /* videoCodecs for the connect packet */ + double m_fEncoding; /* AMF0 or AMF3 */ + + double m_fDuration; /* duration of stream in seconds */ + + int m_msgCounter; /* RTMPT stuff */ + int m_polling; + int m_resplen; + int m_unackd; + AVal m_clientID; + + RTMP_READ m_read; + RTMPPacket m_write; + RTMPSockBuf m_sb; + RTMP_LNK Link; + } RTMP; + + int RTMP_ParseURL(const char *url, int *protocol, AVal *host, + unsigned int *port, AVal *playpath, AVal *app); + + void RTMP_ParsePlaypath(AVal *in, AVal *out); + void RTMP_SetBufferMS(RTMP *r, int size); + void RTMP_UpdateBufferMS(RTMP *r); + + int RTMP_SetOpt(RTMP *r, const AVal *opt, AVal *arg); + RTMPResult RTMP_SetupURL(RTMP *r, char *url); + void RTMP_SetupStream(RTMP *r, int protocol, + AVal *hostname, + unsigned int port, + AVal *sockshost, + AVal *playpath, + AVal *tcUrl, + AVal *swfUrl, + AVal *pageUrl, + AVal *app, + AVal *auth, + AVal *swfSHA256Hash, + uint32_t swfSize, + AVal *flashVer, + AVal *subscribepath, + AVal *usherToken, + int dStart, + int dStop, int bLiveStream, long int timeoutInMs); + + RTMPResult RTMP_Connect(RTMP *r, RTMPPacket *cp); + struct sockaddr; + RTMPResult RTMP_Connect0(RTMP *r, struct sockaddr *svc); + RTMPResult RTMP_Connect1(RTMP *r, RTMPPacket *cp); + int RTMP_Serve(RTMP *r); + int RTMP_TLS_Accept(RTMP *r, void *ctx); + + int RTMP_ReadPacket(RTMP *r, RTMPPacket *packet); + RTMPResult RTMP_SendPacket(RTMP *r, RTMPPacket *packet, int queue); + int RTMP_SendChunk(RTMP *r, RTMPChunk *chunk); + int RTMP_IsConnected(RTMP *r); + int RTMP_Socket(RTMP *r); + int RTMP_IsTimedout(RTMP *r); + double RTMP_GetDuration(RTMP *r); + int RTMP_ToggleStream(RTMP *r); + + RTMPResult RTMP_ConnectStream(RTMP *r, int seekTime); + RTMPResult RTMP_ReconnectStream(RTMP *r, int seekTime); + void RTMP_DeleteStream(RTMP *r); + int RTMP_GetNextMediaPacket(RTMP *r, RTMPPacket *packet); + int RTMP_ClientPacket(RTMP *r, RTMPPacket *packet); + + void RTMP_Init(RTMP *r); + void RTMP_Close(RTMP *r); + RTMP *RTMP_Alloc(void); + void RTMP_Free(RTMP *r); + void RTMP_EnableWrite(RTMP *r); + + void *RTMP_TLS_AllocServerContext(const char* cert, const char* key); + void RTMP_TLS_FreeServerContext(void *ctx); + + int RTMP_LibVersion(void); + void RTMP_UserInterrupt(void); /* user typed Ctrl-C */ + + RTMPResult RTMP_SendCtrl(RTMP *r, short nType, unsigned int nObject, + unsigned int nTime); + + /* caller probably doesn't know current timestamp, should + * just use RTMP_Pause instead + */ + RTMPResult RTMP_SendPause(RTMP *r, int DoPause, int dTime); + RTMPResult RTMP_Pause(RTMP *r, int DoPause); + + int RTMP_FindFirstMatchingProperty(AMFObject *obj, const AVal *name, + AMFObjectProperty * p); + + int RTMPSockBuf_Fill(RTMPSockBuf *sb); + int RTMPSockBuf_Send(RTMPSockBuf *sb, const char *buf, int len); + int RTMPSockBuf_Close(RTMPSockBuf *sb); + + RTMPResult RTMP_SendCreateStream(RTMP *r); + RTMPResult RTMP_SendSeek(RTMP *r, int dTime); + RTMPResult RTMP_SendServerBW(RTMP *r); + RTMPResult RTMP_SendClientBW(RTMP *r); + void RTMP_DropRequest(RTMP *r, int i, int freeit); + /* + * RTMP_Read returns + * 1. the number of bytes read in case there was no error. + * 2. an error value from RTMPResult if there was an error. + * 3. RTMP_READ_DONE in case the stream has ended. + */ + int RTMP_Read(RTMP *r, char *buf, int size); + /* + * RTMP_Write returns + * 1. the number of bytes written in case there was no error. + * 2. an error value from RTMPResult if there was an error, + */ + int RTMP_Write(RTMP *r, const char *buf, int size); + +/* hashswf.c */ + int RTMP_HashSWF(const char *url, unsigned int *size, unsigned char *hash, + int age); + +#ifdef __cplusplus +}; +#endif + +#endif diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/rtmp_sys.h b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/rtmp_sys.h new file mode 100644 index 0000000..85d7e53 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/librtmp/rtmp_sys.h @@ -0,0 +1,139 @@ +#ifndef __RTMP_SYS_H__ +#define __RTMP_SYS_H__ +/* + * Copyright (C) 2010 Howard Chu + * + * This file is part of librtmp. + * + * librtmp is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1, + * or (at your option) any later version. + * + * librtmp 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 Lesser General Public License + * along with librtmp see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * http://www.gnu.org/copyleft/lgpl.html + */ + +#ifdef _WIN32 + +#include +#include + +#ifdef _MSC_VER /* MSVC */ +#define snprintf _snprintf +#define strcasecmp stricmp +#define strncasecmp strnicmp +#define vsnprintf _vsnprintf +#endif + +#define GetSockError() WSAGetLastError() +#define SetSockError(e) WSASetLastError(e) +#define setsockopt(a,b,c,d,e) (setsockopt)(a,b,c,(const char *)d,(int)e) +#define EWOULDBLOCK WSAETIMEDOUT /* we don't use nonblocking, but we do use timeouts */ +#define sleep(n) Sleep(n*1000) +#define msleep(n) Sleep(n) +#define SET_RCVTIMEO(tv,s) int tv = s*1000 +#else /* !_WIN32 */ +#include +#include +#include +#include +#include +#include +#include +#include +#define GetSockError() errno +#define SetSockError(e) errno = e +#undef closesocket +#define closesocket(s) close(s) +#define msleep(n) usleep(n*1000) +#define SET_RCVTIMEO(tv,s) struct timeval tv = {s,0} +#endif + +#include "rtmp.h" + +#ifdef USE_POLARSSL +#include +#include +#include +#include +#if POLARSSL_VERSION_NUMBER < 0x01010000 +#define havege_random havege_rand +#endif +#if POLARSSL_VERSION_NUMBER >= 0x01020000 +#define SSL_SET_SESSION(S,resume,timeout,ctx) ssl_set_session(S,ctx) +#else +#define SSL_SET_SESSION(S,resume,timeout,ctx) ssl_set_session(S,resume,timeout,ctx) +#endif +typedef struct tls_ctx { + havege_state hs; + ssl_session ssn; +} tls_ctx; +typedef struct tls_server_ctx { + havege_state *hs; + x509_cert cert; + rsa_context key; + ssl_session ssn; + const char *dhm_P, *dhm_G; +} tls_server_ctx; + +#define TLS_CTX tls_ctx * +#define TLS_client(ctx,s) s = malloc(sizeof(ssl_context)); ssl_init(s);\ + ssl_set_endpoint(s, SSL_IS_CLIENT); ssl_set_authmode(s, SSL_VERIFY_NONE);\ + ssl_set_rng(s, havege_random, &ctx->hs);\ + ssl_set_ciphersuites(s, ssl_default_ciphersuites);\ + SSL_SET_SESSION(s, 1, 600, &ctx->ssn) +#define TLS_server(ctx,s) s = malloc(sizeof(ssl_context)); ssl_init(s);\ + ssl_set_endpoint(s, SSL_IS_SERVER); ssl_set_authmode(s, SSL_VERIFY_NONE);\ + ssl_set_rng(s, havege_random, ((tls_server_ctx*)ctx)->hs);\ + ssl_set_ciphersuites(s, ssl_default_ciphersuites);\ + SSL_SET_SESSION(s, 1, 600, &((tls_server_ctx*)ctx)->ssn);\ + ssl_set_own_cert(s, &((tls_server_ctx*)ctx)->cert, &((tls_server_ctx*)ctx)->key);\ + ssl_set_dh_param(s, ((tls_server_ctx*)ctx)->dhm_P, ((tls_server_ctx*)ctx)->dhm_G) +#define TLS_setfd(s,fd) ssl_set_bio(s, net_recv, &fd, net_send, &fd) +#define TLS_connect(s) ssl_handshake(s) +#define TLS_accept(s) ssl_handshake(s) +#define TLS_read(s,b,l) ssl_read(s,(unsigned char *)b,l) +#define TLS_write(s,b,l) ssl_write(s,(unsigned char *)b,l) +#define TLS_shutdown(s) ssl_close_notify(s) +#define TLS_close(s) ssl_free(s); free(s) + +#elif defined(USE_GNUTLS) +#include +typedef struct tls_ctx { + gnutls_certificate_credentials_t cred; + gnutls_priority_t prios; +} tls_ctx; +#define TLS_CTX tls_ctx * +#define TLS_client(ctx,s) gnutls_init((gnutls_session_t *)(&s), GNUTLS_CLIENT); gnutls_priority_set(s, ctx->prios); gnutls_credentials_set(s, GNUTLS_CRD_CERTIFICATE, ctx->cred) +#define TLS_server(ctx,s) gnutls_init((gnutls_session_t *)(&s), GNUTLS_SERVER); gnutls_priority_set_direct(s, "NORMAL", NULL); gnutls_credentials_set(s, GNUTLS_CRD_CERTIFICATE, ctx) +#define TLS_setfd(s,fd) gnutls_transport_set_ptr(s, (gnutls_transport_ptr_t)(long)fd) +#define TLS_connect(s) gnutls_handshake(s) +#define TLS_accept(s) gnutls_handshake(s) +#define TLS_read(s,b,l) gnutls_record_recv(s,b,l) +#define TLS_write(s,b,l) gnutls_record_send(s,b,l) +#define TLS_shutdown(s) gnutls_bye(s, GNUTLS_SHUT_RDWR) +#define TLS_close(s) gnutls_deinit(s) + +#else /* USE_OPENSSL */ +#define TLS_CTX SSL_CTX * +#define TLS_client(ctx,s) s = SSL_new(ctx) +#define TLS_server(ctx,s) s = SSL_new(ctx) +#define TLS_setfd(s,fd) SSL_set_fd(s,fd) +#define TLS_connect(s) SSL_connect(s) +#define TLS_accept(s) SSL_accept(s) +#define TLS_read(s,b,l) SSL_read(s,b,l) +#define TLS_write(s,b,l) SSL_write(s,b,l) +#define TLS_shutdown(s) SSL_shutdown(s) +#define TLS_close(s) SSL_free(s) + +#endif +#endif diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/cpp/rtmpmuxer.c b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/rtmpmuxer.c new file mode 100644 index 0000000..ebc2e7f --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/cpp/rtmpmuxer.c @@ -0,0 +1,73 @@ +#include +#include +#include + +#include "flvmuxer/xiecc_rtmp.h" + + +/** + * if it returns bigger than 0 it is successful + */ +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_open(JNIEnv* env, jobject thiz, jstring url_, + jint video_width, jint video_height) { + const char *url = (*env)->GetStringUTFChars(env, url_, NULL); + + int result = rtmp_open_for_write(url, video_width, video_height); + + (*env)->ReleaseStringUTFChars(env, url_, url); + return result; +} + +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_writeAudio(JNIEnv* env, jobject thiz, jbyteArray data_, + jint offset, jint length, jlong timestamp) { + jbyte *data = (*env)->GetByteArrayElements(env, data_, NULL); + + jint result = rtmp_sender_write_audio_frame(&data[offset], length, timestamp, 0); + + (*env)->ReleaseByteArrayElements(env, data_, data, JNI_ABORT); + return result; +} + +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_writeVideo(JNIEnv* env, jobject thiz, jbyteArray data_, + jint offset, jint length, jlong timestamp) { + jbyte *data = (*env)->GetByteArrayElements(env, data_, NULL); + + jint result = rtmp_sender_write_video_frame(&data[offset], length, timestamp, 0, 0); + + (*env)->ReleaseByteArrayElements(env, data_, data, JNI_ABORT); + + return result; +} + +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_close(JNIEnv* env, jobject thiz) { + rtmp_close(); + + return 0; + +} + +JNIEXPORT jboolean JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_isConnected(JNIEnv* env, jobject thiz) { + return rtmp_is_connected() ? true : false; +} + +JNIEXPORT jint JNICALL +Java_io_antmedia_rtmp_1client_RTMPMuxer_read(JNIEnv* env, jobject thiz, jbyteArray data_, + jint offset, jint size) { + + char* data = malloc(size); + + int readCount = rtmp_read_date(data, size); + + if (readCount > 0) { + (*env)->SetByteArrayRegion(env, data_, offset, readCount, data); // copy + } + free(data); + + return readCount; + +} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/java/io/antmedia/rtmp_client/RTMPMuxer.java b/player-rtmp-native/third_party/rtmp-client/src/main/java/io/antmedia/rtmp_client/RTMPMuxer.java new file mode 100644 index 0000000..9b1c4c0 --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/java/io/antmedia/rtmp_client/RTMPMuxer.java @@ -0,0 +1,54 @@ +package io.antmedia.rtmp_client; + +/** + * Created by faraklit on 08.02.2016. + */ +public class RTMPMuxer { + + static { + System.loadLibrary("rtmp-jni"); + } + + public native int open(String url, int video_width, int video_height); + + /** + * write h264 nal units + * @param data + * @param offset + * @param length + * @param timestamp + * @return 0 if it writes network successfully + * -1 if it could not write + */ + public native int writeVideo(byte[] data, int offset, int length, long timestamp); + + /** + * Write raw aac data + * @param data + * @param offset + * @param length + * @param timestamp + * @return 0 if it writes network successfully + * -1 if it could not write + */ + public native int writeAudio(byte[] data, int offset, int length, long timestamp); + + + public native int read(byte[] data, int offset, int size); + + public native int close(); + + + public native void write_flv_header(boolean is_have_audio, boolean is_have_video); + + public native void file_open(String filename); + + public native void file_close(); + + /** + * + * @return 1 if it is connected + * 0 if it is not connected + */ + public native boolean isConnected(); +} diff --git a/player-rtmp-native/third_party/rtmp-client/src/main/java/io/antmedia/rtmp_client/RtmpClient.java b/player-rtmp-native/third_party/rtmp-client/src/main/java/io/antmedia/rtmp_client/RtmpClient.java new file mode 100644 index 0000000..2e967ea --- /dev/null +++ b/player-rtmp-native/third_party/rtmp-client/src/main/java/io/antmedia/rtmp_client/RtmpClient.java @@ -0,0 +1,355 @@ +package io.antmedia.rtmp_client; + +import java.io.IOException; + +/** + * Created by faraklit on 01.01.2016. + */ +public class RtmpClient { + + static { + System.loadLibrary("rtmp-jni"); + } + + + /** + * RTMP read has received an EOF or READ_COMPLETE from the server + */ + public final static int RTMP_READ_DONE = -1; + + /** + * No error + */ + private final static int RTMP_SUCCESS = 0; + + private final static int TIMEOUT_IN_MS = 10000; + private long rtmpPointer = 0; + + /** Socket send timeout value in milliseconds */ + private int sendTimeoutInMs = TIMEOUT_IN_MS; + /** Socket receive timeout value in seconds */ + private int receiveTimeoutInMs = TIMEOUT_IN_MS; + + public static class RtmpIOException extends IOException { + + /** + * RTMP client could not allocate memory for rtmp context structure + */ + public final static int OPEN_ALLOC = -2; + + /** + * RTMP client could not open the stream on server + */ + public final static int OPEN_CONNECT_STREAM = -3; + + /** + * Received an unknown option from the RTMP server + */ + public final static int UNKNOWN_RTMP_OPTION = -4; + + /** + * RTMP server sent a packet with unknown AMF type + */ + public final static int UNKNOWN_RTMP_AMF_TYPE = -5; + + /** + * DNS server is not reachable + */ + public final static int DNS_NOT_REACHABLE = -6; + + /** + * Could not establish a socket connection to the server + */ + public final static int SOCKET_CONNECT_FAIL = -7; + + /** + * SOCKS negotiation failed + */ + public final static int SOCKS_NEGOTIATION_FAIL = -8; + + /** + * Could not create a socket to connect to RTMP server + */ + public final static int SOCKET_CREATE_FAIL = -9; + + /** + * SSL connection requested but not supported by the client + */ + public final static int NO_SSL_TLS_SUPP = -10; + + /** + * Could not connect to the server for handshake + */ + public final static int HANDSHAKE_CONNECT_FAIL = -11; + + /** + * Handshake with the server failed + */ + public final static int HANDSHAKE_FAIL = -12; + + /** + * RTMP server connection failed + */ + public final static int RTMP_CONNECT_FAIL = -13; + + /** + * Connection to the server lost + */ + public final static int CONNECTION_LOST = -14; + + /** + * Received an unexpected timestamp from the server + */ + public final static int RTMP_KEYFRAME_TS_MISMATCH = -15; + + /** + * The RTMP stream received is corrupted + */ + public final static int RTMP_READ_CORRUPT_STREAM = -16; + + /** + * Memory allocation failed + */ + public final static int RTMP_MEM_ALLOC_FAIL = -17; + + /** + * Stream indicated a bad datasize, could be corrupted + */ + public final static int RTMP_STREAM_BAD_DATASIZE = -18; + + /** + * RTMP packet received is too small + */ + public final static int RTMP_PACKET_TOO_SMALL = -19; + + /** + * Could not send packet to RTMP server + */ + public final static int RTMP_SEND_PACKET_FAIL = -20; + + /** + * AMF Encode failed while preparing a packet + */ + public final static int RTMP_AMF_ENCODE_FAIL = -21; + + /** + * Missing a :// in the URL + */ + public final static int URL_MISSING_PROTOCOL = -22; + + /** + * Hostname is missing in the URL + */ + public final static int URL_MISSING_HOSTNAME = -23; + + /** + * The port number indicated in the URL is wrong + */ + public final static int URL_INCORRECT_PORT = -24; + + /** + * Error code used by JNI to return after throwing an exception + */ + public final static int RTMP_IGNORED = -25; + + /** + * RTMP client has encountered an unexpected error + */ + public final static int RTMP_GENERIC_ERROR = -26; + + /** + * A sanity check failed in the RTMP client + */ + public final static int RTMP_SANITY_FAIL = -27; + + public final int errorCode; + + public RtmpIOException(int errorCode) { + super("RTMP error: " + errorCode); + this.errorCode = errorCode; + } + + } + + /** + * Sets the socket's send timeout value + * @param sendTimeoutInMs + * The send timeout value for the rtmp socket in milliseconds. + * Parameter expects a non-zero positive integer and will reset timeout to the default value + * (10000 ms) if zero or a negative integer is passed. + * */ + public void setSendTimeout(int sendTimeoutInMs) { + if (sendTimeoutInMs > 0) { + this.sendTimeoutInMs = sendTimeoutInMs; + } else { + this.sendTimeoutInMs = TIMEOUT_IN_MS; + } + } + + /** + * Sets the socket's receive timeout value + * @param receiveTimeoutInMs + * The receive timeout value for the rtmp socket in milliseconds. + * Parameter expects a non-zero positive integer and will reset timeout to the default value + * (10000 ms) if zero or a negative integer is passed. + * */ + public void setReceiveTimeout(int receiveTimeoutInMs) { + if (receiveTimeoutInMs > 0) { + this.receiveTimeoutInMs = receiveTimeoutInMs; + } else { + this.receiveTimeoutInMs = TIMEOUT_IN_MS; + } + } + + /** + * opens the rtmp url + * @param url + * url of the stream + * @param isPublishMode + * if this is an publication it is true, + * if connection is for getting stream it is false + * @throws RtmpIOException if open fails + */ + public void open(String url, boolean isPublishMode) throws RtmpIOException { + rtmpPointer = nativeAlloc(); + if (rtmpPointer == 0) { + throw new RtmpIOException(RtmpIOException.OPEN_ALLOC); + } + int result = nativeOpen(url, isPublishMode, rtmpPointer, sendTimeoutInMs, + receiveTimeoutInMs); + if (result != RTMP_SUCCESS) { + rtmpPointer = 0; + throw new RtmpIOException(result); + } + } + + private native long nativeAlloc(); + + /** + * opens the rtmp url + * @param url + * url of the stream + * @param isPublishMode + * if this is an publication it is true, + * if connection is for getting stream it is false + * @return return a minus value if it fails + * returns + + * + * returns {@link #RTMP_SUCCESS} if it is successful, throws RtmpIOException if it is failed + */ + private native int nativeOpen(String url, boolean isPublishMode, long rtmpPointer, + int sendTimeoutInMs, int receiveTimeoutInMs); + + /** + * read data from rtmp connection + * + * @param data + * buffer that will be filled + * @param offset + * offset to read data + * @param size + * size of the data to be read + * @return + * number of bytes to be read + * + * if it returns {@link #RTMP_READ_DONE}, it means stream is complete + * and close function can be called. + * + * + * @throws RtmpIOException if connection to server is lost + * @throws IllegalStateException if call to {@link #open(String, boolean)} was unsuccessful or + * missing + */ + public int read(byte[] data, int offset, int size) throws RtmpIOException, IllegalStateException { + int ret = nativeRead(data, offset, size, rtmpPointer); + if (ret < RTMP_SUCCESS && ret != RTMP_READ_DONE) { + throw new RtmpIOException(ret); + } + return ret; + } + + private native int nativeRead(byte[] data, int offset, int size, long rtmpPointer) throws IllegalStateException; + + /** + * Sends data to server + * @param data + * The data to write to server + * @return number of bytes written + * @throws RtmpIOException if connection to server is lost + * @throws IllegalStateException if call to {@link #open(String, boolean)} was unsuccessful or + * missing + */ + public int write(byte[] data) throws RtmpIOException, IllegalStateException { + return write(data, 0, data.length); + } + + /** + * Sends data to server + * @param data + * data to write to server + * @param offset + * The offset from where data will be accessed to write to server + * @param size + * The number of bytes to write to server + * @return number of bytes written + * @throws RtmpIOException if connection to server is lost + * @throws IllegalStateException if call to {@link #open(String, boolean)} was unsuccessful or + * missing + */ + public int write(byte[] data, int offset, int size) throws RtmpIOException, IllegalStateException { + int ret = nativeWrite(data, offset, size, rtmpPointer); + if (ret < RTMP_SUCCESS) { + throw new RtmpIOException(ret); + } + return ret; + } + + private native int nativeWrite(byte[] data, int offset, int size, long rtmpPointer) throws IllegalStateException; + + + /** + * @param pause + * if pause is true then stream is going to be paused + * + * If pause is false, it unpauses the stream and it is ready to to play again + * + * @return true if it is successful else returns false + * @throws RtmpIOException if connection is lost + * @throws IllegalStateException if call to {@link #open(String, boolean)} was unsuccessful or + * missing + */ + public boolean pause(boolean pause) throws RtmpIOException, IllegalStateException { + int ret = nativePause(pause, rtmpPointer); + if (ret != RTMP_SUCCESS) { + throw new RtmpIOException(ret); + } + return true; + } + private native int nativePause(boolean pause, long rtmpPointer) throws IllegalStateException; + + + + /** + * + * @return true if it is connected + * false if it is not connected + */ + public boolean isConnected() { + return nativeIsConnected(rtmpPointer); + } + + private native boolean nativeIsConnected(long rtmpPointer); + + /** + * + * closes the connection. Don't forget to call + */ + public void close() { + nativeClose(rtmpPointer); + rtmpPointer = 0; + } + + private native void nativeClose(long rtmpPointer); + +} diff --git a/player-telemetry/build.gradle.kts b/player-telemetry/build.gradle.kts new file mode 100644 index 0000000..413d501 --- /dev/null +++ b/player-telemetry/build.gradle.kts @@ -0,0 +1,10 @@ +plugins { + kotlin("jvm") + `java-library` +} + +kotlin { jvmToolchain(17) } + +dependencies { + api(project(":player-api")) +} diff --git a/player-telemetry/src/main/kotlin/com/ttstd/player/telemetry/PlaybackTelemetry.kt b/player-telemetry/src/main/kotlin/com/ttstd/player/telemetry/PlaybackTelemetry.kt new file mode 100644 index 0000000..43e6784 --- /dev/null +++ b/player-telemetry/src/main/kotlin/com/ttstd/player/telemetry/PlaybackTelemetry.kt @@ -0,0 +1,44 @@ +package com.ttstd.player.telemetry + +import com.ttstd.player.api.* +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.* + +/** 接收结构化数据;sink 应快速返回,上传由业务队列处理,不能阻塞播放器。 */ +fun interface TelemetrySink { fun record(name: String, attributes: Map) } + +/** 不上传 URI/headers。会话标识由业务给出,不使用媒体地址充当标识。 + * 流可能丢弃诊断事件,不用于计费。close 后停止采集,不释放播放器。 + */ +class PlaybackTelemetry( + engine: PlayerEngine, + scope: CoroutineScope, + sessionId: String, + sink: TelemetrySink, +) : AutoCloseable { + private val job = SupervisorJob(scope.coroutineContext[Job]) + private val collector = CoroutineScope(scope.coroutineContext + job) + init { + fun record(name: String, attrs: Map = emptyMap()) { + // 业务 sink 异常不得终止采集或影响播放。 + runCatching { sink.record(name, attrs + mapOf("sessionId" to sessionId, "engine" to engine.capabilities.engineName)) } + } + collector.launch(start = CoroutineStart.UNDISPATCHED) { + engine.events.collect { event -> + when (event) { + PlaybackEvent.FirstFrame -> record("first_frame") + PlaybackEvent.Ended -> record("ended") + is PlaybackEvent.Error -> record("error", mapOf("code" to event.error.code)) + is PlaybackEvent.DecoderChanged -> record("decoder", mapOf("type" to event.type.name, "name" to event.name, "hardware" to (event.isHardware?.toString() ?: "unknown"))) + is PlaybackEvent.DroppedFrames -> record("dropped_frames", mapOf("count" to "${event.count}", "elapsedMs" to "${event.elapsedMs}")) + is PlaybackEvent.StartupTime -> record("startup", mapOf("elapsedMs" to "${event.elapsedMs}")) + is PlaybackEvent.VideoSize -> record("video_size", mapOf("width" to "${event.width}", "height" to "${event.height}")) + } + } + } + collector.launch(start = CoroutineStart.UNDISPATCHED) { + engine.state.map { it.phase }.distinctUntilChanged().collect { record("phase", mapOf("value" to it.name)) } + } + } + override fun close() { job.cancel() } +} diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..d0b7c2d --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,39 @@ +pluginManagement { + repositories { + google(); mavenCentral(); gradlePluginPortal() + maven("https://jitpack.io") + maven("https://maven.google.com") + maven("https://developer.huawei.com/repo/") + maven("https://developer.hihonor.com/repo") + maven("https://maven.aliyun.com/repository/central") + maven("https://maven.aliyun.com/repository/jcenter") + maven("https://maven.aliyun.com/repository/public") + maven("https://maven.aliyun.com/repository/google") + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + // 与 ElderlyDialer 保持同一公共仓库集合;可选镜像仍优先用于离线受限环境。 + providers.gradleProperty("dependencyMirror").orNull?.let { maven(it) } + google() + mavenCentral() + maven("https://jitpack.io") + maven("https://maven.google.com") + maven("https://developer.huawei.com/repo/") + maven("https://developer.hihonor.com/repo") + maven("https://maven.aliyun.com/repository/central") + maven("https://maven.aliyun.com/repository/jcenter") + maven("https://maven.aliyun.com/repository/public") + maven("https://maven.aliyun.com/repository/google") + } +} +rootProject.name = "TTVideoPlayer" +include(":player-api", ":player-core", ":player-android-api", ":player-media3", ":player-render-android", ":player-lifecycle", ":player-telemetry", ":app-demo") +include(":player-media3-source") +include(":player-rtmp-native") + +include(":library-api", ":library-http", ":library-webdav", ":library-smb", ":library-jellyfin", ":library-storage", ":player-cast-api", ":player-cast-dlna", ":player-cast-relay", ":player-cast-google") +include(":library-media3") + +include(":app") diff --git a/tools/app_smoke_server.py b/tools/app_smoke_server.py new file mode 100644 index 0000000..eca3aee --- /dev/null +++ b/tools/app_smoke_server.py @@ -0,0 +1,102 @@ +"""仅供模拟器手工验收的 WebDAV fixture;固定虚构账号 demo/demo-pass。 + +运行:python tools/app_smoke_server.py --root build/smoke/media +Android 模拟器地址:http://10.0.2.2:18765/dav/ +仅绑定本机回环,不用于生产。主媒体 demo.mp4 可用 ffmpeg testsrc2 生成。 +""" +import argparse +import base64 +import re +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import unquote, quote, urlsplit +from xml.sax.saxutils import escape + + +class Handler(BaseHTTPRequestHandler): + def authorized(self): + if self.headers.get("Authorization") == "Basic " + base64.b64encode(b"demo:demo-pass").decode(): + return True + self.send_response(401) + self.send_header("WWW-Authenticate", 'Basic realm="TTVideoPlayer smoke"') + self.send_header("Content-Length", "0") + self.end_headers() + return False + + def do_PROPFIND(self): + if not self.authorized(): + return + # 消费 request body,避免 keep-alive 的下一个请求被误解析。 + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + names = [None] + sorted(p.name for p in self.server.root.iterdir() if p.is_file()) + responses = [] + for name in names: + href = "/dav/" + (quote(name) if name else "") + collection = "" if name is None else "" + size = (self.server.root / name).stat().st_size if name else 0 + responses.append(f'{escape(href)}' + f'{escape(name or "dav")}' + f'{collection}{size}' + '"smoke-v1"HTTP/1.1 200 OK' + '') + body = ('' + "".join(responses) + '').encode() + self.send_response(207) + self.send_header("Content-Type", "application/xml; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_HEAD(self): + self.file(False) + + def do_GET(self): + self.file(True) + + def file(self, body): + if not self.authorized(): + return + request = unquote(urlsplit(self.path).path) + path = (self.server.root / request.removeprefix("/dav/")).resolve() + if not request.startswith("/dav/") or path.parent != self.server.root or not path.is_file(): + self.send_error(404) + return + size = path.stat().st_size + start, end = 0, size - 1 + match = re.fullmatch(r"bytes=(\d+)-(\d*)", self.headers.get("Range", "")) + if match: + start = int(match[1]) + end = min(int(match[2]), end) if match[2] else end + if start > end: + self.send_response(416) + self.send_header("Content-Range", f"bytes */{size}") + self.end_headers() + return + self.send_response(206 if match else 200) + self.send_header("Content-Type", "video/mp4" if path.suffix == ".mp4" else "application/x-subrip") + self.send_header("Accept-Ranges", "bytes") + self.send_header("Content-Length", str(end - start + 1)) + if match: + self.send_header("Content-Range", f"bytes {start}-{end}/{size}") + self.end_headers() + if body: + try: + with path.open("rb") as stream: + stream.seek(start) + remaining = end - start + 1 + while remaining: + data = stream.read(min(65536, remaining)) + if not data: + break + self.wfile.write(data) + remaining -= len(data) + except (BrokenPipeError, ConnectionResetError): + pass + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + args = parser.parse_args() + server = ThreadingHTTPServer(("127.0.0.1", 18765), Handler) + server.root = args.root.resolve() + server.serve_forever() diff --git a/tools/verify_apk_native.py b/tools/verify_apk_native.py new file mode 100644 index 0000000..7ae0e75 --- /dev/null +++ b/tools/verify_apk_native.py @@ -0,0 +1,44 @@ +"""检查 APK 中 native ELF 的 LOAD 对齐与 ZIP 存储对齐,不代替设备加载测试。 + +用法:python tools/verify_apk_native.py path/to/demo.apk +无需第三方 Python 依赖;构建产物有误时返回非零状态。 +""" +import struct +import sys +import zipfile +from pathlib import Path + + +def verify(apk: Path) -> None: + abis = set() + with zipfile.ZipFile(apk) as archive, apk.open("rb") as raw: + for entry in archive.infolist(): + if not entry.filename.endswith(".so"): + continue + data = archive.read(entry) + assert data[:4] == b"\x7fELF", entry.filename + is64 = data[4] == 2 + endian = "<" if data[5] == 1 else ">" + offset = struct.unpack_from(endian + ("Q" if is64 else "I"), data, 32 if is64 else 28)[0] + size, count = struct.unpack_from(endian + "HH", data, 54 if is64 else 42) + alignments = [] + for index in range(count): + header = offset + index * size + if struct.unpack_from(endian + "I", data, header)[0] == 1: + alignment = struct.unpack_from(endian + ("Q" if is64 else "I"), data, header + (48 if is64 else 28))[0] + assert alignment >= 16384, f"ELF alignment {alignment}: {entry.filename}" + alignments.append(alignment) + assert alignments, entry.filename + if entry.compress_type == zipfile.ZIP_STORED: + raw.seek(entry.header_offset + 26) + name_len, extra_len = struct.unpack("