@Override
    public void run() {

        while (active) {
            RtmpPacket rtmpPacket = writeQueue.poll();
            // Write all queued RTMP packets
            while (rtmpPacket != null) {
                try {
                    final ChunkStreamInfo chunkStreamInfo = rtmpSessionInfo.getChunkStreamInfo(rtmpPacket.getHeader().getChunkStreamId());
                    chunkStreamInfo.setPrevHeaderTx(rtmpPacket.getHeader());
                    L.d("WriteThread: writing packet: " + rtmpPacket);
                    rtmpPacket.writeTo(out, rtmpSessionInfo.getChunkSize(), chunkStreamInfo);
                    System.out.println("writethread wrote packet: "+rtmpPacket+", size: "+rtmpPacket.getHeader().getPacketLength());
                    if (rtmpPacket instanceof Command) {
                        rtmpSessionInfo.addInvokedCommand(((Command) rtmpPacket).getTransactionId(), ((Command) rtmpPacket).getCommandName());
                    }
                } catch (IOException ex) {
                    L.e("WriteThread: Caught IOException during write loop, shutting down", ex);
                    active = false;
                }
                rtmpPacket = writeQueue.poll();
            }
            try {
                out.flush();
            } catch (IOException ex) {
                L.e("WriteThread: Caught IOException while flushing stream, shutting down", ex);
                active = false;
                continue;
            }
            // Wait for next command
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException ex) {
                    L.w("WriteThread: Interrupted", ex);
                }
            }
        }
        // Close outputstream
        try {
            out.close();
        } catch (Exception ex) {
            L.w("WriteThread: Failed to close outputstream", ex);
        }
        L.d("WriteThread: exiting");
        if (threadController != null) {
            threadController.threadHasExited(this);
        }
    }