Amf0Util.java 1.94 KB
package com.genersoft.iot.vmp.jtt1078.rtmp;

import io.netty.buffer.ByteBuf;
import java.util.Map;

/**
 * AMF0 编码工具类
 */
public class Amf0Util {

    // AMF0 Markers
    public static final byte NUMBER = 0x00;
    public static final byte BOOLEAN = 0x01;
    public static final byte STRING = 0x02;
    public static final byte OBJECT = 0x03;
    public static final byte NULL = 0x05;
    public static final byte ECMA_ARRAY = 0x08;
    public static final byte OBJECT_END = 0x09;

    public static void writeString(ByteBuf out, String str) {
        out.writeByte(STRING);
        writeStringBare(out, str);
    }

    // 不带 Marker 的字符串(用于 Object 的 Key)
    public static void writeStringBare(ByteBuf out, String str) {
        if (str == null) str = "";
        byte[] bytes = str.getBytes();
        out.writeShort(bytes.length);
        out.writeBytes(bytes);
    }

    public static void writeNumber(ByteBuf out, double num) {
        out.writeByte(NUMBER);
        out.writeLong(Double.doubleToLongBits(num));
    }

    public static void writeBoolean(ByteBuf out, boolean val) {
        out.writeByte(BOOLEAN);
        out.writeByte(val ? 1 : 0);
    }

    public static void writeNull(ByteBuf out) {
        out.writeByte(NULL);
    }

    public static void writeObject(ByteBuf out, Map<String, Object> props) {
        out.writeByte(OBJECT);
        if (props != null) {
            for (Map.Entry<String, Object> entry : props.entrySet()) {
                writeStringBare(out, entry.getKey());
                Object val = entry.getValue();
                if (val instanceof String) writeString(out, (String) val);
                else if (val instanceof Number) writeNumber(out, ((Number) val).doubleValue());
                else if (val instanceof Boolean) writeBoolean(out, (Boolean) val);
                else writeNull(out);
            }
        }
        // Object End Marker (00 00 09)
        out.writeMedium(0x000009);
    }
}