static void encode_hdr(lua_State *L, amf_buf *buf, int ver) { if(!lua_istable(L, -1)) { luaL_error(L, "invalid header structure, must be a dense table"); } /* name */ lua_rawgeti(L, -1, 1); size_t len; const char *name = lua_tolstring(L, -1, &len); amf_buf_append_u16(buf, (uint16_t)len); if (len > 0) amf_buf_append(buf, name, (uint16_t)len); lua_pop(L, 1); /* must understand */ lua_rawgeti(L, -1, 2); int mu = lua_toboolean(L, -1); amf_buf_append_char(buf, (char)mu); lua_pop(L, 1); /* content length */ amf_buf_append_u32(buf, (uint32_t)0); lua_rawgeti(L, -1, 3); lua_newtable(L); amf0_encode(L, buf, (ver == 3), -2, lua_gettop(L)); lua_pop(L, 2); /* pops the obj and ref table */ }
static int lua_amf_buffer_write_int32(lua_State *L) { amf_buf *b = luaL_checkudata(L, 1, "amf_buffer"); int32_t i = luaL_checkint(L, 2); amf_buf_append_u32(b, i); return 0; }
static void amf0_encode_table_as_array(amf_buf *buf, lua_State *L, int idx, int ridx, int len) { amf_buf_append_char(buf, AMF0_STRICT_ARRAY); amf_buf_append_u32(buf, (uint32_t)len); // array count for (int i = 1; i <= len; i++) { lua_pushinteger(L, i); lua_gettable(L, idx); amf0_encode(L, buf, 0, -1, ridx); lua_pop(L, 1); } }
static void encode_body(lua_State *L, amf_buf *buf, int ver) { if(!lua_istable(L, -1)) { luaL_error(L, "invalid body structure, must be a dense table"); } size_t len; const char *uri; /* target uri */ lua_rawgeti(L, -1, 1); uri = lua_tolstring(L, -1, &len); amf_buf_append_u16(buf, (uint16_t)len); if (len > 0) { amf_buf_append(buf, uri, (uint16_t)len); printf("target: %s\n", uri); } lua_pop(L, 1); /* response uri */ lua_rawgeti(L, -1, 2); uri = lua_tolstring(L, -1, &len); amf_buf_append_u16(buf, (uint16_t)len); if (len > 0) { amf_buf_append(buf, uri, (uint16_t)len); printf("response: %s\n", uri); } lua_pop(L, 1); /* content length */ amf_buf_append_u32(buf, (uint32_t)0); lua_rawgeti(L, -1, 3); lua_newtable(L); amf0_encode(L, buf, (ver == 3), -2, lua_gettop(L)); lua_pop(L, 2); /* pops the obj and ref table */ }
static void amf0_encode_string(amf_buf *b, const char *s, size_t len) { uint16_t u16; uint32_t u32; if (len < UINT16_MAX) { u16 = (uint16_t)len; amf_buf_append_char(b, AMF0_STRING); amf_buf_append_u16(b, u16); amf_buf_append(b, s, u16); } else { // long string if (len > UINT32_MAX) { len = UINT32_MAX; } u32 = (uint32_t)len; amf_buf_append_char(b, AMF0_L_STRING); amf_buf_append_u32(b, u32); amf_buf_append(b, s, u32); } }