# Livestream Support

The Firework Android SDK provides comprehensive livestream features including live broadcasts, replays, trailers, interactive chat, polls, questions, and giveaways. This guide covers livestream setup, configuration, and usage.

## Overview

The `FireworkSdk.livestream` object provides access to all livestream-related functionality. Through this interface, you can:

* Handle user interactions during livestreams
* Manage chat and username display
* Respond to links clicked within livestream content
* Configure livestream-specific UI elements
* Handle giveaways, polls, and questions

## Livestream Content Types

The SDK supports three types of livestream content:

### 1. Livestream/Restream/VideoToLive

Real-time streaming content with interactive features:

* Live chat
* Real-time polls and questions
* Giveaways and promotions
* Interactive product links

### 2. Livestream Replays

Recorded livestream content that can be played on-demand:

* Preserved chat messages
* Historical poll results
* Recorded interactions
* Full shopping integration

### 3. Trailers

Preview content for upcoming livestreams:

* Countdown timer
* Calendar reminder integration
* Teaser content
* Schedule information

## Prerequisites

* Firework SDK properly initialized (see [Getting Started](/firework-for-developers/android-sdk/integration-guide/getting-started.md))
* Livestream features enabled for your Client ID
* Livestream dependency added to your project

## Installation

### Add Livestream Dependency

Add the livestream player dependency to your `build.gradle.kts`:

```kotlin
dependencies {
    // Core Firework SDK
    implementation(platform("com.firework:firework-bom:$fireworkBomVersion"))
    implementation("com.firework:sdk")
    
    // Image loader (recommended: Glide)
    implementation("com.firework.external.imageloading:glide")
    
    // Livestream support (only add when needed)
    implementation("com.firework.external.livestream:singleHostPlayer")
}
```

**Note:** Only add the livestream dependency when you need livestream features. It's not required for regular video playback.

## SDK Configuration

### Initialize with Livestream Support

Configure the SDK with livestream player initializer in your Application class:

```kotlin
import android.app.Application
import com.firework.sdk.FireworkSdk
import com.firework.sdk.FireworkSdkConfig
import com.firework.sdk.FireworkInitError
import com.firework.imageloading.glide.GlideImageLoaderFactory
import com.firework.external.livestream.singlehost.SingleHostLivestreamPlayerInitializer

class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
        
        // Build SDK configuration with livestream support
        val config = FireworkSdkConfig.Builder(context = this)
            .clientId("YOUR_CLIENT_ID")
            .imageLoader(GlideImageLoaderFactory.createInstance(context = this))
            .addLivestreamPlayerInitializer(SingleHostLivestreamPlayerInitializer())
            .build()
        
        // Use the latest livestream player version (V2 - recommended)
        FireworkSdk.setLivestreamPlayerVersion(FwLivestreamPlayerVersion.V2)
        
        // Initialize SDK
        FireworkSdk.init(
            fireworkSdkConfig = config,
            onSuccess = {
                setupLivestreamCallbacks()
            },
            onError = { error ->
                // Handle initialization error
            }
        )
    }
    
    private fun setupLivestreamCallbacks() {
        // Configure livestream callbacks here
        // See Livestream Callbacks section below
    }
}
```

**Important:** Call `setLivestreamPlayerVersion()` before `FireworkSdk.init()`.

## Livestream Features

### Link Handling

Handle links clicked within livestream content (e.g., product links, external URLs):

```kotlin
FireworkSdk.livestream.setOnLinkClickListener { link ->
    // Open link in browser or handle deep link
    openUrl(link)
    true // Return true if handled, false to let SDK handle
}
```

### User Interactions

Handle interactive features like polls, questions, and giveaways:

```kotlin
FireworkSdk.livestream.setOnInteractionListener { interaction ->
    when (interaction) {
        is QuestionInteraction -> {
            // User submitted an answer to a question
            Log.d("Livestream", "Question: ${interaction.question}")
            Log.d("Livestream", "Answer: ${interaction.answer}")
        }
        is PollInteraction -> {
            // User voted in a poll
            Log.d("Livestream", "Poll: ${interaction.pollId}")
            Log.d("Livestream", "Option: ${interaction.selectedOption}")
        }
        is GiveawayInteraction -> {
            // User joined a giveaway
            Log.d("Livestream", "Giveaway: ${interaction.giveawayId}")
        }
    }
}
```

### Chat Management

Manage user display names in livestream chat:

```kotlin
// Update username
FireworkSdk.livestream.updateUsername(
    username = "JohnDoe",
    onSuccess = {
        Log.d("Livestream", "Username updated successfully")
    },
    onError = { error ->
        Log.e("Livestream", "Failed to update username: ${error.message}")
    }
)

// Get current username
val currentUsername = FireworkSdk.livestream.getUsername()

// Configure username display settings
FireworkSdk.livestream.updateUsernameConfiguration(
    UsernameConfiguration(
        isEditable = true,  // Allow users to edit their username
        isHidden = false    // Show username in chat
    )
)
```

### Giveaway Terms and Conditions

Handle clicks on giveaway terms and conditions:

```kotlin
FireworkSdk.livestream.setOnGiveawayTermsAndConditionsClickListener { url ->
    // Open T&C page
    openUrl(url)
}
```

### Username Update Listener

Listen for username change requests from users:

```kotlin
FireworkSdk.livestream.setOnUpdateUsernameListener { newUsername, onComplete ->
    // Validate username with your backend
    if (isValidUsername(newUsername)) {
        // Accept the username
        onComplete(true)
    } else {
        // Reject the username
        onComplete(false)
        showError("Username not available")
    }
}
```

## Display Livestream Content

Livestream content can be displayed using any Firework widget:

### Video Feed with Livestream

```kotlin
val viewOptions = viewOptions {
    baseOptions {
        feedResource(FeedResource.Discovery) // Can include livestream content
    }
}

val videoFeedView = findViewById<FwVideoFeedView>(R.id.videoFeedView)
videoFeedView.init(viewOptions)
```

### StoryBlock with Livestream

```kotlin
val viewOptions = viewOptions {
    baseOptions {
        feedResource(FeedResource.Channel(channelId = "your_channel_id"))
    }
    storyBlockOptions {
        enableAutoPlay(true)
    }
}

val storyBlock = findViewById<FwStoryBlockView>(R.id.storyBlock)
storyBlock.init(supportFragmentManager, lifecycle, viewOptions)
```

### Direct Fullscreen Player

```kotlin
val viewOptions = viewOptions {
    baseOptions {
        feedResource(FeedResource.Discovery)
    }
}

FireworkSdk.startPlayer(viewOptions)
```

## Livestream Player Configuration

### Countdown Timer

Display a countdown timer for upcoming livestreams:

```kotlin
val viewOptions = viewOptions {
    playerOptions {
        livestreamCountDownOption(
            LivestreamCountDownOption.Builder()
                .isHidden(false) // Show countdown
                .theme(Theme.DARK) // or Theme.LIGHT
                .build()
        )
    }
}
```

Users can tap the countdown to set a calendar reminder for the livestream.

**Note:** Calendar reminders require calendar permissions in AndroidManifest.xml:

```xml
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
```

### Player Version

Use V2 for the latest livestream features:

```kotlin
// Set before SDK initialization
FireworkSdk.setLivestreamPlayerVersion(FwLivestreamPlayerVersion.V2)
```

**V2 Benefits:**

* Improved performance and stability
* Better error handling
* Enhanced interactive features
* Active support and updates

## Complete Integration Example

```kotlin
class MyApp : Application() {

    override fun onCreate() {
        super.onCreate()
        
        // Configure livestream player version
        FireworkSdk.setLivestreamPlayerVersion(FwLivestreamPlayerVersion.V2)
        
        // Build configuration
        val config = FireworkSdkConfig.Builder(context = this)
            .clientId("YOUR_CLIENT_ID")
            .imageLoader(GlideImageLoaderFactory.createInstance(context = this))
            .addLivestreamPlayerInitializer(SingleHostLivestreamPlayerInitializer())
            .build()
        
        // Initialize SDK
        FireworkSdk.init(
            fireworkSdkConfig = config,
            onSuccess = {
                setupLivestreamFeatures()
            }
        )
    }
    
    private fun setupLivestreamFeatures() {
        // Link handling
        FireworkSdk.livestream.setOnLinkClickListener { link ->
            openBrowser(link)
            true
        }
        
        // Interaction handling
        FireworkSdk.livestream.setOnInteractionListener { interaction ->
            when (interaction) {
                is QuestionInteraction -> handleQuestion(interaction)
                is PollInteraction -> handlePoll(interaction)
                is GiveawayInteraction -> handleGiveaway(interaction)
            }
        }
        
        // Giveaway T&C
        FireworkSdk.livestream.setOnGiveawayTermsAndConditionsClickListener { url ->
            openBrowser(url)
        }
        
        // Username updates
        FireworkSdk.livestream.setOnUpdateUsernameListener { newUsername, onComplete ->
            validateUsername(newUsername) { isValid ->
                onComplete(isValid)
            }
        }
        
        // Configure username display
        FireworkSdk.livestream.updateUsernameConfiguration(
            UsernameConfiguration(
                isEditable = true,
                isHidden = false
            )
        )
    }
}
```

## Important Notes

* Livestream dependency should only be added when needed
* Always use V2 player version for latest features
* Set player version before SDK initialization
* Livestream chat and some features only work in fullscreen mode (not in StoryBlock compact mode)
* Calendar reminders require appropriate Android permissions
* Return `true` from link click listener if you handle the link, `false` to let SDK handle it

## Troubleshooting

### Livestream Not Playing

**Issue:** Livestream content doesn't play or shows an error.

**Solutions:**

1. Verify livestream dependency is added:

   ```kotlin
   implementation("com.firework.external.livestream:singleHostPlayer")
   ```
2. Ensure `SingleHostLivestreamPlayerInitializer()` is added to SDK config
3. Confirm `setLivestreamPlayerVersion()` is called before `init()`
4. Check that livestream features are enabled for your Client ID

### Missing Chat or Interactive Features

**Issue:** Chat, polls, or other interactive features not visible.

**Solutions:**

1. Ensure you're using V2 player version
2. For StoryBlock, ensure you're in fullscreen mode (tap fullscreen icon)
3. Verify livestream is actually live (not a trailer or replay without interactions)

## Related Documentation

### Detailed Guides

* [Livestream Callbacks](/firework-for-developers/android-sdk/integration-guide/livestream/livestream-callbacks.md) - Complete callback API reference
* [Livestream Chat](/firework-for-developers/android-sdk/integration-guide/livestream/livestream-chat.md) - Chat management and username configuration

### Related Features

* [Getting Started](/firework-for-developers/android-sdk/integration-guide/getting-started.md) - SDK initialization
* [Video Player Configuration](/firework-for-developers/android-sdk/integration-guide/video-player.md) - Player customization
* [Configure Video Feed](/firework-for-developers/android-sdk/integration-guide/configure-video-feed.md) - Video feed setup
* [StoryBlock Integration](/firework-for-developers/android-sdk/integration-guide/storyblock.md) - StoryBlock widget
* [FireworkSdk API Reference](/firework-for-developers/android-sdk/integration-guide/firework-sdk-api.md) - Complete API documentation

## API Summary

| Method                                           | Description                        |
| ------------------------------------------------ | ---------------------------------- |
| `setOnLinkClickListener()`                       | Handle link clicks in livestream   |
| `setOnInteractionListener()`                     | Handle polls, questions, giveaways |
| `setOnGiveawayTermsAndConditionsClickListener()` | Handle T\&C clicks                 |
| `setOnUpdateUsernameListener()`                  | Listen for username updates        |
| `updateUsername()`                               | Update user's display name         |
| `getUsername()`                                  | Get current username               |
| `updateUsernameConfiguration()`                  | Configure username settings        |

For complete API details, see [FireworkSdk API Reference](/firework-for-developers/android-sdk/integration-guide/firework-sdk-api.md#livestream-features).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.firework.com/firework-for-developers/android-sdk/integration-guide/livestream.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
