void cpu_loop(CPUMIPSState *env) { target_siginfo_t info; int trapnr, ret; unsigned int syscall_num; for(;;) { trapnr = cpu_mips_exec(env); switch(trapnr) { case EXCP_SYSCALL: syscall_num = env->active_tc.gpr[2] - 4000; env->active_tc.PC += 4; if (syscall_num >= sizeof(mips_syscall_args)) { ret = -ENOSYS; } else { int nb_args; abi_ulong sp_reg; abi_ulong arg5 = 0, arg6 = 0, arg7 = 0, arg8 = 0; nb_args = mips_syscall_args[syscall_num]; sp_reg = env->active_tc.gpr[29]; switch (nb_args) { /* these arguments are taken from the stack */ /* FIXME - what to do if get_user() fails? */ case 8: get_user_ual(arg8, sp_reg + 28); case 7: get_user_ual(arg7, sp_reg + 24); case 6: get_user_ual(arg6, sp_reg + 20); case 5: get_user_ual(arg5, sp_reg + 16); default: ret = do_syscall(env, env->active_tc.gpr[2], env->active_tc.gpr[4], env->active_tc.gpr[5], env->active_tc.gpr[6], env->active_tc.gpr[7], arg5, arg6/*, arg7, arg8*/); if ((unsigned int)ret >= (unsigned int)(-1133)) { env->active_tc.gpr[7] = 1; /* error flag */ ret = -ret; } else { env->active_tc.gpr[7] = 0; /* error flag */ env->active_tc.gpr[2] = ret; case EXCP_TLBL: case EXCP_TLBS: info.si_signo = TARGET_SIGSEGV; info.si_errno = 0; /* XXX: check env->error_code */ info.si_code = TARGET_SEGV_MAPERR; info._sifields._sigfault._addr = env->CP0_BadVAddr; queue_signal(env, info.si_signo, &info); case EXCP_CpU: case EXCP_RI: info.si_signo = TARGET_SIGILL; info.si_errno = 0; info.si_code = 0; queue_signal(env, info.si_signo, &info); case EXCP_INTERRUPT: /* just indicate that signals should be handled asap */ case EXCP_DEBUG: { int sig; sig = gdb_handlesig (env, TARGET_SIGTRAP); if (sig) { info.si_signo = sig; info.si_errno = 0; info.si_code = TARGET_TRAP_BRKPT; queue_signal(env, info.si_signo, &info); default: // error: fprintf(stderr, "qemu: unhandled CPU exception 0x%x - aborting\n", trapnr); cpu_dump_state(env, stderr, fprintf, 0); abort(); process_pending_signals(env);


static int tmv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { TMVContext *tmv = s->priv_data; int64_t pos; if (stream_index) return -1; pos = timestamp * (tmv->audio_chunk_size + tmv->video_chunk_size + tmv->padding); avio_seek(s->pb, pos + TMV_HEADER_SIZE, SEEK_SET); tmv->stream_index = 0; return 0; }


static void bonito_ldma_writel(void *opaque, hwaddr addr, uint64_t val, unsigned size) { PCIBonitoState *s = opaque; ((uint32_t *)(&s->bonldma))[addr/sizeof(uint32_t)] = val & 0xffffffff;


static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, int *tp_index, Jpeg2000CodingStyle *codsty, Jpeg2000ResLevel *rlevel, int precno, int layno, uint8_t *expn, int numgbits) { int bandno, cblkno, ret, nb_code_blocks; int cwsno; if (layno < rlevel->band[0].prec[precno].decoded_layers) return 0; rlevel->band[0].prec[precno].decoded_layers = layno + 1; if (bytestream2_get_bytes_left(&s->g) == 0 && s->bit_index == 8) { if (*tp_index < FF_ARRAY_ELEMS(tile->tile_part) - 1) { s->g = tile->tile_part[++(*tp_index)].tpg; } } if (bytestream2_peek_be32(&s->g) == JPEG2000_SOP_FIXED_BYTES) bytestream2_skip(&s->g, JPEG2000_SOP_BYTE_LENGTH); if (!(ret = get_bits(s, 1))) { jpeg2000_flush(s); return 0; } else if (ret < 0) return ret; for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; int incl, newpasses, llen; if (cblk->npasses) incl = get_bits(s, 1); else incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno; if (!incl) continue; else if (incl < 0) return incl; if (!cblk->npasses) { int v = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + cblkno, 100); if (v < 0 || v > 30) { av_log(s->avctx, AV_LOG_ERROR, "nonzerobits %d invalid or unsupported\n", v); return AVERROR_INVALIDDATA; } cblk->nonzerobits = v; } if ((newpasses = getnpasses(s)) < 0) return newpasses; av_assert2(newpasses > 0); if (cblk->npasses + newpasses >= JPEG2000_MAX_PASSES) { avpriv_request_sample(s->avctx, "Too many passes"); return AVERROR_PATCHWELCOME; } if ((llen = getlblockinc(s)) < 0) return llen; if (cblk->lblock + llen + av_log2(newpasses) > 16) { avpriv_request_sample(s->avctx, "Block with length beyond 16 bits"); return AVERROR_PATCHWELCOME; } cblk->lblock += llen; cblk->nb_lengthinc = 0; cblk->nb_terminationsinc = 0; do { int newpasses1 = 0; while (newpasses1 < newpasses) { newpasses1 ++; if (needs_termination(codsty->cblk_style, cblk->npasses + newpasses1 - 1)) { cblk->nb_terminationsinc ++; break; } } if ((ret = get_bits(s, av_log2(newpasses1) + cblk->lblock)) < 0) return ret; if (ret > sizeof(cblk->data)) { avpriv_request_sample(s->avctx, "Block with lengthinc greater than %"SIZE_SPECIFIER"", sizeof(cblk->data)); return AVERROR_PATCHWELCOME; } cblk->lengthinc[cblk->nb_lengthinc++] = ret; cblk->npasses += newpasses1; newpasses -= newpasses1; } while(newpasses); } } jpeg2000_flush(s); if (codsty->csty & JPEG2000_CSTY_EPH) { if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH) bytestream2_skip(&s->g, 2); else av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found. instead %X\n", bytestream2_peek_be32(&s->g)); } for (bandno = 0; bandno < rlevel->nbands; bandno++) { Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width; for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) { Jpeg2000Cblk *cblk = prec->cblk + cblkno; for (cwsno = 0; cwsno < cblk->nb_lengthinc; cwsno ++) { if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc[cwsno] || sizeof(cblk->data) < cblk->length + cblk->lengthinc[cwsno] + 4 ) { av_log(s->avctx, AV_LOG_ERROR, "Block length %"PRIu16" or lengthinc %d is too large, left %d\n", cblk->length, cblk->lengthinc[cwsno], bytestream2_get_bytes_left(&s->g)); return AVERROR_INVALIDDATA; } bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc[cwsno]); cblk->length += cblk->lengthinc[cwsno]; cblk->lengthinc[cwsno] = 0; if (cblk->nb_terminationsinc) { cblk->nb_terminationsinc--; cblk->nb_terminations++; cblk->data[cblk->length++] = 0xFF; cblk->data[cblk->length++] = 0xFF; cblk->data_start[cblk->nb_terminations] = cblk->length; } } } } return 0; }


static void curses_refresh(DisplayChangeListener *dcl) { int chr, nextchr, keysym, keycode, keycode_alt; curses_winch_check(); if (invalidate) { clear(); refresh(); curses_calc_pad(); graphic_hw_invalidate(NULL); invalidate = 0; } graphic_hw_text_update(NULL, screen); nextchr = ERR; while (1) { /* while there are any pending key strokes to process */ if (nextchr == ERR) chr = getch(); else { chr = nextchr; nextchr = ERR; } if (chr == ERR) break; #ifdef KEY_RESIZE /* this shouldn't occur when we use a custom SIGWINCH handler */ if (chr == KEY_RESIZE) { clear(); refresh(); curses_calc_pad(); curses_update(dcl, 0, 0, width, height); continue; } #endif keycode = curses2keycode[chr]; keycode_alt = 0; /* alt key */ if (keycode == 1) { nextchr = getch(); if (nextchr != ERR) { chr = nextchr; keycode_alt = ALT; keycode = curses2keycode[nextchr]; nextchr = ERR; if (keycode != -1) { keycode |= ALT; /* process keys reserved for qemu */ if (keycode >= QEMU_KEY_CONSOLE0 && keycode < QEMU_KEY_CONSOLE0 + 9) { erase(); wnoutrefresh(stdscr); console_select(keycode - QEMU_KEY_CONSOLE0); invalidate = 1; continue; } } } } if (kbd_layout) { keysym = -1; if (chr < CURSES_KEYS) keysym = curses2keysym[chr]; if (keysym == -1) { if (chr < ' ') { keysym = chr + '@'; if (keysym >= 'A' && keysym <= 'Z') keysym += 'a' - 'A'; keysym |= KEYSYM_CNTRL; } else keysym = chr; } keycode = keysym2scancode(kbd_layout, keysym & KEYSYM_MASK); if (keycode == 0) continue; keycode |= (keysym & ~KEYSYM_MASK) >> 16; keycode |= keycode_alt; } if (keycode == -1) continue; if (qemu_console_is_graphic(NULL)) { /* since terminals don't know about key press and release * events, we need to emit both for each key received */ if (keycode & SHIFT) { qemu_input_event_send_key_number(NULL, SHIFT_CODE, true); qemu_input_event_send_key_delay(0); } if (keycode & CNTRL) { qemu_input_event_send_key_number(NULL, CNTRL_CODE, true); qemu_input_event_send_key_delay(0); } if (keycode & ALT) { qemu_input_event_send_key_number(NULL, ALT_CODE, true); qemu_input_event_send_key_delay(0); } if (keycode & ALTGR) { qemu_input_event_send_key_number(NULL, GREY | ALT_CODE, true); qemu_input_event_send_key_delay(0); } qemu_input_event_send_key_number(NULL, keycode & KEY_MASK, true); qemu_input_event_send_key_delay(0); qemu_input_event_send_key_number(NULL, keycode & KEY_MASK, false); qemu_input_event_send_key_delay(0); if (keycode & ALTGR) { qemu_input_event_send_key_number(NULL, GREY | ALT_CODE, false); qemu_input_event_send_key_delay(0); } if (keycode & ALT) { qemu_input_event_send_key_number(NULL, ALT_CODE, false); qemu_input_event_send_key_delay(0); } if (keycode & CNTRL) { qemu_input_event_send_key_number(NULL, CNTRL_CODE, false); qemu_input_event_send_key_delay(0); } if (keycode & SHIFT) { qemu_input_event_send_key_number(NULL, SHIFT_CODE, false); qemu_input_event_send_key_delay(0); } } else { keysym = curses2qemu[chr]; if (keysym == -1) keysym = chr; kbd_put_keysym(keysym); } } }


static int64_t read_ts(char **line, int *duration) { int64_t start, end; if (sscanf(*line, "%"SCNd64",%"SCNd64, &start, &end) == 2) { *line += strcspn(*line, "\"") + 1; *duration = end - start; return start; } return AV_NOPTS_VALUE; }


static void raven_class_init(ObjectClass *klass, void *data) { PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); DeviceClass *dc = DEVICE_CLASS(klass); k->init = raven_init; k->vendor_id = PCI_VENDOR_ID_MOTOROLA; k->device_id = PCI_DEVICE_ID_MOTOROLA_RAVEN; k->revision = 0x00; k->class_id = PCI_CLASS_BRIDGE_HOST; dc->desc = "PReP Host Bridge - Motorola Raven"; dc->vmsd = &vmstate_raven; dc->no_user = 1; }


static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **errp) { int size; char *path; void *ptr; char name[32]; const VMStateDescription *vmsd; if (!pdev->romfile) return; if (strlen(pdev->romfile) == 0) return; if (!pdev->rom_bar) { /* * Load rom via fw_cfg instead of creating a rom bar, * for 0.11 compatibility. */ int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE); /* * Hot-plugged devices can't use the option ROM * if the rom bar is disabled. */ if (DEVICE(pdev)->hotplugged) { error_setg(errp, "Hot-plugged device without ROM bar" " can't have an option ROM"); return; } if (class == 0x0300) { rom_add_vga(pdev->romfile); } else { rom_add_option(pdev->romfile, -1); } return; } path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile); if (path == NULL) { path = g_strdup(pdev->romfile); } size = get_image_size(path); if (size < 0) { error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile); g_free(path); return; } else if (size == 0) { error_setg(errp, "romfile \"%s\" is empty", pdev->romfile); g_free(path); return; } size = pow2ceil(size); vmsd = qdev_get_vmsd(DEVICE(pdev)); if (vmsd) { snprintf(name, sizeof(name), "%s.rom", vmsd->name); } else { snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev))); } pdev->has_rom = true; memory_region_init_ram(&pdev->rom, OBJECT(pdev), name, size, &error_abort); vmstate_register_ram(&pdev->rom, &pdev->qdev); ptr = memory_region_get_ram_ptr(&pdev->rom); load_image(path, ptr); g_free(path); if (is_default_rom) { /* Only the default rom images will be patched (if needed). */ pci_patch_ids(pdev, ptr, size); } pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom); }


static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s) { AVStream *video_st = s->streams[0]; AVCodecParameters *video_par = s->streams[0]->codecpar; AVCodecParameters *audio_par = s->streams[1]->codecpar; int audio_rate = audio_par->sample_rate; // TODO: should be avg_frame_rate int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num); int audio_kbitrate = audio_par->bit_rate / 1000; int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate); avio_wb32(pb, 0x94); /* size */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "PROF"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x3); /* 3 sections ? */ avio_wb32(pb, 0x14); /* size */ ffio_wfourcc(pb, "FPRF"); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x2c); /* size */ ffio_wfourcc(pb, "APRF"); /* audio */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x2); /* TrackID */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0x20f); avio_wb32(pb, 0x0); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_rate); avio_wb32(pb, audio_par->channels); avio_wb32(pb, 0x34); /* size */ ffio_wfourcc(pb, "VPRF"); /* video */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x1); /* TrackID */ if (video_par->codec_id == AV_CODEC_ID_H264) { ffio_wfourcc(pb, "avc1"); avio_wb16(pb, 0x014D); avio_wb16(pb, 0x0015); } else { ffio_wfourcc(pb, "mp4v"); avio_wb16(pb, 0x0000); avio_wb16(pb, 0x0103); } avio_wb32(pb, 0x0); avio_wb32(pb, video_kbitrate); avio_wb32(pb, video_kbitrate); avio_wb32(pb, frame_rate); avio_wb32(pb, frame_rate); avio_wb16(pb, video_par->width); avio_wb16(pb, video_par->height); avio_wb32(pb, 0x010001); /* ? */ }


static char *spapr_phb_vfio_get_loc_code(sPAPRPHBState *sphb, PCIDevice *pdev) { char *path = NULL, *buf = NULL, *host = NULL; /* Get the PCI VFIO host id */ host = object_property_get_str(OBJECT(pdev), "host", NULL); if (!host) { goto err_out; } /* Construct the path of the file that will give us the DT location */ path = g_strdup_printf("/sys/bus/pci/devices/%s/devspec", host); g_free(host); if (!path || !g_file_get_contents(path, &buf, NULL, NULL)) { goto err_out; } g_free(path); /* Construct and read from host device tree the loc-code */ path = g_strdup_printf("/proc/device-tree%s/ibm,loc-code", buf); g_free(buf); if (!path || !g_file_get_contents(path, &buf, NULL, NULL)) { goto err_out; } return buf; err_out: g_free(path); return NULL; }


static inline void yuv2nv12XinC(int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize, int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize, uint8_t *dest, uint8_t *uDest, int dstW, int chrDstW, int dstFormat) { //FIXME Optimize (just quickly writen not opti..) int i; for (i=0; i<dstW; i++) { int val=1<<18; int j; for (j=0; j<lumFilterSize; j++) val += lumSrc[j][i] * lumFilter[j]; dest[i]= av_clip_uint8(val>>19); } if (!uDest) return; if (dstFormat == PIX_FMT_NV12) for (i=0; i<chrDstW; i++) { int u=1<<18; int v=1<<18; int j; for (j=0; j<chrFilterSize; j++) { u += chrSrc[j][i] * chrFilter[j]; v += chrSrc[j][i + 2048] * chrFilter[j]; } uDest[2*i]= av_clip_uint8(u>>19); uDest[2*i+1]= av_clip_uint8(v>>19); } else for (i=0; i<chrDstW; i++) { int u=1<<18; int v=1<<18; int j; for (j=0; j<chrFilterSize; j++) { u += chrSrc[j][i] * chrFilter[j]; v += chrSrc[j][i + 2048] * chrFilter[j]; } uDest[2*i]= av_clip_uint8(v>>19); uDest[2*i+1]= av_clip_uint8(u>>19); } }


static void nvme_process_db(NvmeCtrl *n, hwaddr addr, int val) { uint32_t qid; if (addr & ((1 << 2) - 1)) { return; } if (((addr - 0x1000) >> 2) & 1) { uint16_t new_head = val & 0xffff; int start_sqs; NvmeCQueue *cq; qid = (addr - (0x1000 + (1 << 2))) >> 3; if (nvme_check_cqid(n, qid)) { return; } cq = n->cq[qid]; if (new_head >= cq->size) { return; } start_sqs = nvme_cq_full(cq) ? 1 : 0; cq->head = new_head; if (start_sqs) { NvmeSQueue *sq; QTAILQ_FOREACH(sq, &cq->sq_list, entry) { timer_mod(sq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500); } timer_mod(cq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500); } if (cq->tail != cq->head) { nvme_isr_notify(n, cq); } } else { uint16_t new_tail = val & 0xffff; NvmeSQueue *sq; qid = (addr - 0x1000) >> 3; if (nvme_check_sqid(n, qid)) { return; } sq = n->sq[qid]; if (new_tail >= sq->size) { return; } sq->tail = new_tail; timer_mod(sq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500); } }


static void gen_storeq_reg(DisasContext *s, int rlow, int rhigh, TCGv_i64 val) { TCGv tmp; tmp = new_tmp(); tcg_gen_trunc_i64_i32(tmp, val); store_reg(s, rlow, tmp); tmp = new_tmp(); tcg_gen_shri_i64(val, val, 32); tcg_gen_trunc_i64_i32(tmp, val); store_reg(s, rhigh, tmp); }


static int ccid_bulk_in_copy_to_guest(USBCCIDState *s, uint8_t *data, int len) { int ret = 0; assert(len > 0); ccid_bulk_in_get(s); if (s->current_bulk_in != NULL) { ret = MIN(s->current_bulk_in->len - s->current_bulk_in->pos, len); memcpy(data, s->current_bulk_in->data + s->current_bulk_in->pos, ret); s->current_bulk_in->pos += ret; if (s->current_bulk_in->pos == s->current_bulk_in->len) { ccid_bulk_in_release(s); } } else { /* return when device has no data - usb 2.0 spec Table 8-4 */ ret = USB_RET_NAK; } if (ret > 0) { DPRINTF(s, D_MORE_INFO, "%s: %d/%d req/act to guest (BULK_IN)\n", __func__, len, ret); } if (ret != USB_RET_NAK && ret < len) { DPRINTF(s, 1, "%s: returning short (EREMOTEIO) %d < %d\n", __func__, ret, len); } return ret; }


static void lms_update(WmallDecodeCtx *s, int ich, int ilms, int16_t input, int16_t pred) { int16_t icoef; int recent = s->cdlms[ich][ilms].recent; int16_t range = 1 << (s->bits_per_sample - 1); int bps = s->bits_per_sample > 16 ? 4 : 2; // bytes per sample if (input > pred) { for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++) s->cdlms[ich][ilms].coefs[icoef] += s->cdlms[ich][ilms].lms_updates[icoef + recent]; } else { for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++) s->cdlms[ich][ilms].coefs[icoef] -= s->cdlms[ich][ilms].lms_updates[icoef]; // XXX: [icoef + recent] ? } s->cdlms[ich][ilms].recent--; s->cdlms[ich][ilms].lms_prevvalues[recent] = av_clip(input, -range, range - 1); if (input > pred) s->cdlms[ich][ilms].lms_updates[recent] = s->update_speed[ich]; else if (input < pred) s->cdlms[ich][ilms].lms_updates[recent] = -s->update_speed[ich]; /* XXX: spec says: cdlms[iCh][ilms].updates[iRecent + cdlms[iCh][ilms].order >> 4] >>= 2; lms_updates[iCh][ilms][iRecent + cdlms[iCh][ilms].order >> 3] >>= 1; Questions is - are cdlms[iCh][ilms].updates[] and lms_updates[][][] two seperate buffers? Here I've assumed that the two are same which makes more sense to me. */ s->cdlms[ich][ilms].lms_updates[recent + s->cdlms[ich][ilms].order >> 4] >>= 2; s->cdlms[ich][ilms].lms_updates[recent + s->cdlms[ich][ilms].order >> 3] >>= 1; /* XXX: recent + (s->cdlms[ich][ilms].order >> 4) ? */ if (s->cdlms[ich][ilms].recent == 0) { /* XXX: This memcpy()s will probably fail if a fixed 32-bit buffer is used. follow kshishkov's suggestion of using a union. */ memcpy(s->cdlms[ich][ilms].lms_prevvalues + s->cdlms[ich][ilms].order, s->cdlms[ich][ilms].lms_prevvalues, bps * s->cdlms[ich][ilms].order); memcpy(s->cdlms[ich][ilms].lms_updates + s->cdlms[ich][ilms].order, s->cdlms[ich][ilms].lms_updates, bps * s->cdlms[ich][ilms].order); s->cdlms[ich][ilms].recent = s->cdlms[ich][ilms].order; } }


static int create_filter(AVFilterContext **filt_ctx, AVFilterGraph *ctx, int index, const char *filt_name, const char *args, AVClass *log_ctx) { AVFilter *filt; char inst_name[30]; char tmp_args[256]; int ret; snprintf(inst_name, sizeof(inst_name), "Parsed filter %d %s", index, filt_name); filt = avfilter_get_by_name(filt_name); if (!filt) { av_log(log_ctx, AV_LOG_ERROR, "No such filter: '%s'\n", filt_name); return AVERROR(EINVAL); } ret = avfilter_open(filt_ctx, filt, inst_name); if (!*filt_ctx) { av_log(log_ctx, AV_LOG_ERROR, "Error creating filter '%s'\n", filt_name); return ret; } if ((ret = avfilter_graph_add_filter(ctx, *filt_ctx)) < 0) { avfilter_free(*filt_ctx); return ret; } if (!strcmp(filt_name, "scale") && !strstr(args, "flags")) { snprintf(tmp_args, sizeof(tmp_args), "%s:%s", args, ctx->scale_sws_opts); args = tmp_args; } if ((ret = avfilter_init_filter(*filt_ctx, args, NULL)) < 0) { av_log(log_ctx, AV_LOG_ERROR, "Error initializing filter '%s' with args '%s'\n", filt_name, args); return ret; } return 0; }


static void decode_mclms(WmallDecodeCtx *s) { s->mclms_order = (get_bits(&s->gb, 4) + 1) * 2; s->mclms_scaling = get_bits(&s->gb, 4); if(get_bits1(&s->gb)) { // mclms_send_coef int i; int send_coef_bits; int cbits = av_log2(s->mclms_scaling + 1); assert(cbits == my_log2(s->mclms_scaling + 1)); if(1 << cbits < s->mclms_scaling + 1) cbits++; send_coef_bits = (cbits ? get_bits(&s->gb, cbits) : 0) + 2; for(i = 0; i < s->mclms_order * s->num_channels * s->num_channels; i++) { s->mclms_coeffs[i] = get_bits(&s->gb, send_coef_bits); } for(i = 0; i < s->num_channels; i++) { int c; for(c = 0; c < i; c++) { s->mclms_coeffs_cur[i * s->num_channels + c] = get_bits(&s->gb, send_coef_bits); } } } }


static void ppc_spapr_init(ram_addr_t ram_size, const char *boot_device, const char *kernel_filename, const char *kernel_cmdline, const char *initrd_filename, const char *cpu_model) { PowerPCCPU *cpu; CPUPPCState *env; int i; MemoryRegion *sysmem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); target_phys_addr_t rma_alloc_size, rma_size; uint32_t initrd_base = 0; long kernel_size = 0, initrd_size = 0; long load_limit, rtas_limit, fw_size; long pteg_shift = 17; char *filename; spapr = g_malloc0(sizeof(*spapr)); QLIST_INIT(&spapr->phbs); cpu_ppc_hypercall = emulate_spapr_hypercall; /* Allocate RMA if necessary */ rma_alloc_size = kvmppc_alloc_rma("ppc_spapr.rma", sysmem); if (rma_alloc_size == -1) { hw_error("qemu: Unable to create RMA\n"); exit(1); } if (rma_alloc_size && (rma_alloc_size < ram_size)) { rma_size = rma_alloc_size; } else { rma_size = ram_size; } /* We place the device tree and RTAS just below either the top of the RMA, * or just below 2GB, whichever is lowere, so that it can be * processed with 32-bit real mode code if necessary */ rtas_limit = MIN(rma_size, 0x80000000); spapr->rtas_addr = rtas_limit - RTAS_MAX_SIZE; spapr->fdt_addr = spapr->rtas_addr - FDT_MAX_SIZE; load_limit = spapr->fdt_addr - FW_OVERHEAD; /* init CPUs */ if (cpu_model == NULL) { cpu_model = kvm_enabled() ? "host" : "POWER7"; } for (i = 0; i < smp_cpus; i++) { cpu = cpu_ppc_init(cpu_model); if (cpu == NULL) { fprintf(stderr, "Unable to find PowerPC CPU definition\n"); exit(1); } env = &cpu->env; /* Set time-base frequency to 512 MHz */ cpu_ppc_tb_init(env, TIMEBASE_FREQ); qemu_register_reset(spapr_cpu_reset, cpu); env->hreset_vector = 0x60; env->hreset_excp_prefix = 0; env->gpr[3] = env->cpu_index; } /* allocate RAM */ spapr->ram_limit = ram_size; if (spapr->ram_limit > rma_alloc_size) { ram_addr_t nonrma_base = rma_alloc_size; ram_addr_t nonrma_size = spapr->ram_limit - rma_alloc_size; memory_region_init_ram(ram, "ppc_spapr.ram", nonrma_size); vmstate_register_ram_global(ram); memory_region_add_subregion(sysmem, nonrma_base, ram); } /* allocate hash page table. For now we always make this 16mb, * later we should probably make it scale to the size of guest * RAM */ spapr->htab_size = 1ULL << (pteg_shift + 7); spapr->htab = qemu_memalign(spapr->htab_size, spapr->htab_size); for (env = first_cpu; env != NULL; env = env->next_cpu) { env->external_htab = spapr->htab; env->htab_base = -1; env->htab_mask = spapr->htab_size - 1; /* Tell KVM that we're in PAPR mode */ env->spr[SPR_SDR1] = (unsigned long)spapr->htab | ((pteg_shift + 7) - 18); env->spr[SPR_HIOR] = 0; if (kvm_enabled()) { kvmppc_set_papr(env); } } filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, "spapr-rtas.bin"); spapr->rtas_size = load_image_targphys(filename, spapr->rtas_addr, rtas_limit - spapr->rtas_addr); if (spapr->rtas_size < 0) { hw_error("qemu: could not load LPAR rtas '%s'\n", filename); exit(1); } if (spapr->rtas_size > RTAS_MAX_SIZE) { hw_error("RTAS too big ! 0x%lx bytes (max is 0x%x)\n", spapr->rtas_size, RTAS_MAX_SIZE); exit(1); } g_free(filename); /* Set up Interrupt Controller */ spapr->icp = xics_system_init(XICS_IRQS); spapr->next_irq = 16; /* Set up VIO bus */ spapr->vio_bus = spapr_vio_bus_init(); for (i = 0; i < MAX_SERIAL_PORTS; i++) { if (serial_hds[i]) { spapr_vty_create(spapr->vio_bus, serial_hds[i]); } } /* Set up PCI */ spapr_create_phb(spapr, "pci", SPAPR_PCI_BUID, SPAPR_PCI_MEM_WIN_ADDR, SPAPR_PCI_MEM_WIN_SIZE, SPAPR_PCI_IO_WIN_ADDR); for (i = 0; i < nb_nics; i++) { NICInfo *nd = &nd_table[i]; if (!nd->model) { nd->model = g_strdup("ibmveth"); } if (strcmp(nd->model, "ibmveth") == 0) { spapr_vlan_create(spapr->vio_bus, nd); } else { pci_nic_init_nofail(&nd_table[i], nd->model, NULL); } } for (i = 0; i <= drive_get_max_bus(IF_SCSI); i++) { spapr_vscsi_create(spapr->vio_bus); } if (rma_size < (MIN_RMA_SLOF << 20)) { fprintf(stderr, "qemu: pSeries SLOF firmware requires >= " "%ldM guest RMA (Real Mode Area memory)\n", MIN_RMA_SLOF); exit(1); } fprintf(stderr, "sPAPR memory map:\n"); fprintf(stderr, "RTAS : 0x%08lx..%08lx\n", (unsigned long)spapr->rtas_addr, (unsigned long)(spapr->rtas_addr + spapr->rtas_size - 1)); fprintf(stderr, "FDT : 0x%08lx..%08lx\n", (unsigned long)spapr->fdt_addr, (unsigned long)(spapr->fdt_addr + FDT_MAX_SIZE - 1)); if (kernel_filename) { uint64_t lowaddr = 0; kernel_size = load_elf(kernel_filename, translate_kernel_address, NULL, NULL, &lowaddr, NULL, 1, ELF_MACHINE, 0); if (kernel_size < 0) { kernel_size = load_image_targphys(kernel_filename, KERNEL_LOAD_ADDR, load_limit - KERNEL_LOAD_ADDR); } if (kernel_size < 0) { fprintf(stderr, "qemu: could not load kernel '%s'\n", kernel_filename); exit(1); } fprintf(stderr, "Kernel : 0x%08x..%08lx\n", KERNEL_LOAD_ADDR, KERNEL_LOAD_ADDR + kernel_size - 1); /* load initrd */ if (initrd_filename) { /* Try to locate the initrd in the gap between the kernel * and the firmware. Add a bit of space just in case */ initrd_base = (KERNEL_LOAD_ADDR + kernel_size + 0x1ffff) & ~0xffff; initrd_size = load_image_targphys(initrd_filename, initrd_base, load_limit - initrd_base); if (initrd_size < 0) { fprintf(stderr, "qemu: could not load initial ram disk '%s'\n", initrd_filename); exit(1); } fprintf(stderr, "Ramdisk : 0x%08lx..%08lx\n", (long)initrd_base, (long)(initrd_base + initrd_size - 1)); } else { initrd_base = 0; initrd_size = 0; } } filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, FW_FILE_NAME); fw_size = load_image_targphys(filename, 0, FW_MAX_SIZE); if (fw_size < 0) { hw_error("qemu: could not load LPAR rtas '%s'\n", filename); exit(1); } g_free(filename); fprintf(stderr, "Firmware load : 0x%08x..%08lx\n", 0, fw_size); fprintf(stderr, "Firmware runtime : 0x%08lx..%08lx\n", load_limit, (unsigned long)spapr->fdt_addr); spapr->entry_point = 0x100; /* SLOF will startup the secondary CPUs using RTAS */ for (env = first_cpu; env != NULL; env = env->next_cpu) { env->halted = 1; } /* Prepare the device tree */ spapr->fdt_skel = spapr_create_fdt_skel(cpu_model, rma_size, initrd_base, initrd_size, kernel_size, boot_device, kernel_cmdline, pteg_shift + 7); assert(spapr->fdt_skel != NULL); qemu_register_reset(spapr_reset, spapr); }


static av_cold int sonic_encode_init(AVCodecContext *avctx) { SonicContext *s = avctx->priv_data; PutBitContext pb; int i, version = 0; if (avctx->channels > MAX_CHANNELS) { av_log(avctx, AV_LOG_ERROR, "Only mono and stereo streams are supported by now\n"); return AVERROR(EINVAL); /* only stereo or mono for now */ } if (avctx->channels == 2) s->decorrelation = MID_SIDE; else s->decorrelation = 3; if (avctx->codec->id == AV_CODEC_ID_SONIC_LS) { s->lossless = 1; s->num_taps = 32; s->downsampling = 1; s->quantization = 0.0; } else { s->num_taps = 128; s->downsampling = 2; s->quantization = 1.0; } // max tap 2048 if ((s->num_taps < 32) || (s->num_taps > 1024) || ((s->num_taps>>5)<<5 != s->num_taps)) { av_log(avctx, AV_LOG_ERROR, "Invalid number of taps\n"); return AVERROR_INVALIDDATA; } // generate taps s->tap_quant = av_calloc(s->num_taps, sizeof(*s->tap_quant)); for (i = 0; i < s->num_taps; i++) s->tap_quant[i] = ff_sqrt(i+1); s->channels = avctx->channels; s->samplerate = avctx->sample_rate; s->block_align = 2048LL*s->samplerate/(44100*s->downsampling); s->frame_size = s->channels*s->block_align*s->downsampling; s->tail_size = s->num_taps*s->channels; s->tail = av_calloc(s->tail_size, sizeof(*s->tail)); if (!s->tail) return AVERROR(ENOMEM); s->predictor_k = av_calloc(s->num_taps, sizeof(*s->predictor_k) ); if (!s->predictor_k) return AVERROR(ENOMEM); for (i = 0; i < s->channels; i++) { s->coded_samples[i] = av_calloc(s->block_align, sizeof(**s->coded_samples)); if (!s->coded_samples[i]) return AVERROR(ENOMEM); } s->int_samples = av_calloc(s->frame_size, sizeof(*s->int_samples)); s->window_size = ((2*s->tail_size)+s->frame_size); s->window = av_calloc(s->window_size, sizeof(*s->window)); if (!s->window) return AVERROR(ENOMEM); avctx->extradata = av_mallocz(16); if (!avctx->extradata) return AVERROR(ENOMEM); init_put_bits(&pb, avctx->extradata, 16*8); put_bits(&pb, 2, version); // version if (version == 1) { put_bits(&pb, 2, s->channels); put_bits(&pb, 4, code_samplerate(s->samplerate)); } put_bits(&pb, 1, s->lossless); if (!s->lossless) put_bits(&pb, 3, SAMPLE_SHIFT); // XXX FIXME: sample precision put_bits(&pb, 2, s->decorrelation); put_bits(&pb, 2, s->downsampling); put_bits(&pb, 5, (s->num_taps >> 5)-1); // 32..1024 put_bits(&pb, 1, 0); // XXX FIXME: no custom tap quant table flush_put_bits(&pb); avctx->extradata_size = put_bits_count(&pb)/8; av_log(avctx, AV_LOG_INFO, "Sonic: ver: %d ls: %d dr: %d taps: %d block: %d frame: %d downsamp: %d\n", version, s->lossless, s->decorrelation, s->num_taps, s->block_align, s->frame_size, s->downsampling); avctx->frame_size = s->block_align*s->downsampling; return 0; }


int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma) { static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 }; static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 }; if (mode > 6U) { av_log(h->avctx, AV_LOG_ERROR, "out of range intra chroma pred mode at %d %d\n", h->mb_x, h->mb_y); return -1; } if (!(h->top_samples_available & 0x8000)) { mode = top[mode]; if (mode < 0) { av_log(h->avctx, AV_LOG_ERROR, "top block unavailable for requested intra mode at %d %d\n", h->mb_x, h->mb_y); return -1; } } if ((h->left_samples_available & 0x8080) != 0x8080) { mode = left[mode]; if (is_chroma && (h->left_samples_available & 0x8080)) { // mad cow disease mode, aka MBAFF + constrained_intra_pred mode = ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available & 0x8000)) + 2 * (mode == DC_128_PRED8x8); } if (mode < 0) { av_log(h->avctx, AV_LOG_ERROR, "left block unavailable for requested intra mode at %d %d\n", h->mb_x, h->mb_y); return -1; } } return mode; }


void audio_pcm_init_info (struct audio_pcm_info *info, audsettings_t *as) { int bits = 8, sign = 0, shift = 0; switch (as->fmt) { case AUD_FMT_S8: sign = 1; case AUD_FMT_U8: break; case AUD_FMT_S16: sign = 1; case AUD_FMT_U16: bits = 16; shift = 1; break; case AUD_FMT_S32: sign = 1; case AUD_FMT_U32: bits = 32; shift = 2; break; } info->freq = as->freq; info->bits = bits; info->sign = sign; info->nchannels = as->nchannels; info->shift = (as->nchannels == 2) + shift; info->align = (1 << info->shift) - 1; info->bytes_per_second = info->freq << info->shift; info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS); }


static void block_job_completed_txn_abort(BlockJob *job) { AioContext *ctx; BlockJobTxn *txn = job->txn; BlockJob *other_job, *next; if (txn->aborting) { /* * We are cancelled by another job, which will handle everything. */ return; } txn->aborting = true; /* We are the first failed job. Cancel other jobs. */ QLIST_FOREACH(other_job, &txn->jobs, txn_list) { ctx = blk_get_aio_context(other_job->blk); aio_context_acquire(ctx); } QLIST_FOREACH(other_job, &txn->jobs, txn_list) { if (other_job == job || other_job->completed) { /* Other jobs are "effectively" cancelled by us, set the status for * them; this job, however, may or may not be cancelled, depending * on the caller, so leave it. */ if (other_job != job) { block_job_cancel_async(other_job); } continue; } block_job_cancel_sync(other_job); assert(other_job->completed); } QLIST_FOREACH_SAFE(other_job, &txn->jobs, txn_list, next) { ctx = blk_get_aio_context(other_job->blk); block_job_completed_single(other_job); aio_context_release(ctx); } }


void isa_mmio_setup(MemoryRegion *mr, target_phys_addr_t size) { memory_region_init_io(mr, &isa_mmio_ops, NULL, "isa-mmio", size); }


int qio_channel_socket_dgram_sync(QIOChannelSocket *ioc, SocketAddressLegacy *localAddr, SocketAddressLegacy *remoteAddr, Error **errp) { int fd; trace_qio_channel_socket_dgram_sync(ioc, localAddr, remoteAddr); fd = socket_dgram(remoteAddr, localAddr, errp); if (fd < 0) { trace_qio_channel_socket_dgram_fail(ioc); return -1; } trace_qio_channel_socket_dgram_complete(ioc, fd); if (qio_channel_socket_set_fd(ioc, fd, errp) < 0) { close(fd); return -1; } return 0; }


static void dec_bit(DisasContext *dc) { TCGv t0, t1; unsigned int op; int mem_index = cpu_mmu_index(dc->env); op = dc->ir & ((1 << 9) - 1); switch (op) { case 0x21: /* src. */ t0 = tcg_temp_new(); LOG_DIS("src r%d r%d\n", dc->rd, dc->ra); tcg_gen_andi_tl(t0, cpu_R[dc->ra], 1); if (dc->rd) { t1 = tcg_temp_new(); read_carry(dc, t1); tcg_gen_shli_tl(t1, t1, 31); tcg_gen_shri_tl(cpu_R[dc->rd], cpu_R[dc->ra], 1); tcg_gen_or_tl(cpu_R[dc->rd], cpu_R[dc->rd], t1); tcg_temp_free(t1); } /* Update carry. */ write_carry(dc, t0); tcg_temp_free(t0); break; case 0x1: case 0x41: /* srl. */ t0 = tcg_temp_new(); LOG_DIS("srl r%d r%d\n", dc->rd, dc->ra); /* Update carry. */ tcg_gen_andi_tl(t0, cpu_R[dc->ra], 1); write_carry(dc, t0); tcg_temp_free(t0); if (dc->rd) { if (op == 0x41) tcg_gen_shri_tl(cpu_R[dc->rd], cpu_R[dc->ra], 1); else tcg_gen_sari_tl(cpu_R[dc->rd], cpu_R[dc->ra], 1); } break; case 0x60: LOG_DIS("ext8s r%d r%d\n", dc->rd, dc->ra); tcg_gen_ext8s_i32(cpu_R[dc->rd], cpu_R[dc->ra]); break; case 0x61: LOG_DIS("ext16s r%d r%d\n", dc->rd, dc->ra); tcg_gen_ext16s_i32(cpu_R[dc->rd], cpu_R[dc->ra]); break; case 0x64: case 0x66: case 0x74: case 0x76: /* wdc. */ LOG_DIS("wdc r%d\n", dc->ra); if ((dc->tb_flags & MSR_EE_FLAG) && mem_index == MMU_USER_IDX) { tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_PRIVINSN); t_gen_raise_exception(dc, EXCP_HW_EXCP); return; } break; case 0x68: /* wic. */ LOG_DIS("wic r%d\n", dc->ra); if ((dc->tb_flags & MSR_EE_FLAG) && mem_index == MMU_USER_IDX) { tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_PRIVINSN); t_gen_raise_exception(dc, EXCP_HW_EXCP); return; } break; case 0xe0: if ((dc->tb_flags & MSR_EE_FLAG) && (dc->env->pvr.regs[2] & PVR2_ILL_OPCODE_EXC_MASK) && !((dc->env->pvr.regs[2] & PVR2_USE_PCMP_INSTR))) { tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_ILLEGAL_OP); t_gen_raise_exception(dc, EXCP_HW_EXCP); } if (dc->env->pvr.regs[2] & PVR2_USE_PCMP_INSTR) { gen_helper_clz(cpu_R[dc->rd], cpu_R[dc->ra]); } break; case 0x1e0: /* swapb */ LOG_DIS("swapb r%d r%d\n", dc->rd, dc->ra); tcg_gen_bswap32_i32(cpu_R[dc->rd], cpu_R[dc->ra]); break; case 0x1e2: /*swaph */ LOG_DIS("swaph r%d r%d\n", dc->rd, dc->ra); tcg_gen_rotri_i32(cpu_R[dc->rd], cpu_R[dc->ra], 16); break; default: cpu_abort(dc->env, "unknown bit oc=%x op=%x rd=%d ra=%d rb=%d\n", dc->pc, op, dc->rd, dc->ra, dc->rb); break; } }


int memory_region_get_fd(MemoryRegion *mr) { if (mr->alias) { return memory_region_get_fd(mr->alias); } assert(mr->terminates); return qemu_get_ram_fd(mr->ram_addr & TARGET_PAGE_MASK); }


static void tcg_out_insn_3314(TCGContext *s, AArch64Insn insn, TCGReg r1, TCGReg r2, TCGReg rn, tcg_target_long ofs, bool pre, bool w) { insn |= 1u << 31; /* ext */ insn |= pre << 24; insn |= w << 23; assert(ofs >= -0x200 && ofs < 0x200 && (ofs & 7) == 0); insn |= (ofs & (0x7f << 3)) << (15 - 3); tcg_out32(s, insn | r2 << 10 | rn << 5 | r1); }


static void x86_cpuid_set_tsc_freq(Object *obj, Visitor *v, void *opaque, const char *name, Error **errp) { X86CPU *cpu = X86_CPU(obj); const int64_t min = 0; const int64_t max = INT_MAX; int64_t value; visit_type_int(v, &value, name, errp); if (error_is_set(errp)) { return; } if (value < min || value > max) { error_set(errp, QERR_PROPERTY_VALUE_OUT_OF_RANGE, "", name ? name : "null", value, min, max); return; } cpu->env.tsc_khz = value / 1000; }


static int cow_create(const char *filename, QemuOpts *opts, Error **errp) { struct cow_header_v2 cow_header; struct stat st; int64_t image_sectors = 0; char *image_filename = NULL; Error *local_err = NULL; int ret; BlockDriverState *cow_bs; /* Read out options */ image_sectors = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / 512; image_filename = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE); ret = bdrv_create_file(filename, opts, &local_err); if (ret < 0) { error_propagate(errp, local_err); goto exit; } cow_bs = NULL; ret = bdrv_open(&cow_bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err); if (ret < 0) { error_propagate(errp, local_err); goto exit; } memset(&cow_header, 0, sizeof(cow_header)); cow_header.magic = cpu_to_be32(COW_MAGIC); cow_header.version = cpu_to_be32(COW_VERSION); if (image_filename) { /* Note: if no file, we put a dummy mtime */ cow_header.mtime = cpu_to_be32(0); if (stat(image_filename, &st) != 0) { goto mtime_fail; } cow_header.mtime = cpu_to_be32(st.st_mtime); mtime_fail: pstrcpy(cow_header.backing_file, sizeof(cow_header.backing_file), image_filename); } cow_header.sectorsize = cpu_to_be32(512); cow_header.size = cpu_to_be64(image_sectors * 512); ret = bdrv_pwrite(cow_bs, 0, &cow_header, sizeof(cow_header)); if (ret < 0) { goto exit; } /* resize to include at least all the bitmap */ ret = bdrv_truncate(cow_bs, sizeof(cow_header) + ((image_sectors + 7) >> 3)); if (ret < 0) { goto exit; } exit: g_free(image_filename); bdrv_unref(cow_bs); return ret; }


static av_cold int check_format(AVCodecContext *avctx) { AVCodecParserContext *parser; uint8_t *pout; int psize; int index; H264Context *h; int ret = -1; /* init parser & parse file */ parser = av_parser_init(avctx->codec->id); if (!parser) { av_log(avctx, AV_LOG_ERROR, "Failed to open H.264 parser.\n"); goto final; } parser->flags = PARSER_FLAG_COMPLETE_FRAMES; index = av_parser_parse2(parser, avctx, &pout, &psize, NULL, 0, 0, 0, 0); if (index < 0) { av_log(avctx, AV_LOG_ERROR, "Failed to parse this file.\n"); goto release_parser; } /* check if support */ h = parser->priv_data; switch (h->sps.bit_depth_luma) { case 8: if (!CHROMA444(h) && !CHROMA422(h)) { // only this will H.264 decoder switch to hwaccel ret = 0; break; } default: av_log(avctx, AV_LOG_ERROR, "Unsupported file.\n"); } release_parser: av_parser_close(parser); final: return ret; }


static unsigned int dec_move_mr(DisasContext *dc) { int memsize = memsize_zz(dc); int insn_len; DIS(fprintf (logfile, "move.%c [$r%u%s, $r%u\n", memsize_char(memsize), dc->op1, dc->postinc ? "+]" : "]", dc->op2)); if (memsize == 4) { insn_len = dec_prep_move_m(dc, 0, 4, cpu_R[dc->op2]); cris_cc_mask(dc, CC_MASK_NZ); cris_update_cc_op(dc, CC_OP_MOVE, 4); cris_update_cc_x(dc); cris_update_result(dc, cpu_R[dc->op2]); } else { TCGv t0; t0 = tcg_temp_new(TCG_TYPE_TL); insn_len = dec_prep_move_m(dc, 0, memsize, t0); cris_cc_mask(dc, CC_MASK_NZ); cris_alu(dc, CC_OP_MOVE, cpu_R[dc->op2], cpu_R[dc->op2], t0, memsize); tcg_temp_free(t0); } do_postinc(dc, memsize); return insn_len; }


static int rtc_initfn(ISADevice *dev) { RTCState *s = DO_UPCAST(RTCState, dev, dev); int base = 0x70; int isairq = 8; isa_init_irq(dev, &s->irq, isairq); s->cmos_data[RTC_REG_A] = 0x26; s->cmos_data[RTC_REG_B] = 0x02; s->cmos_data[RTC_REG_C] = 0x00; s->cmos_data[RTC_REG_D] = 0x80; rtc_set_date_from_host(s); s->periodic_timer = qemu_new_timer(rtc_clock, rtc_periodic_timer, s); #ifdef TARGET_I386 if (rtc_td_hack) s->coalesced_timer = qemu_new_timer(rtc_clock, rtc_coalesced_timer, s); #endif s->second_timer = qemu_new_timer(rtc_clock, rtc_update_second, s); s->second_timer2 = qemu_new_timer(rtc_clock, rtc_update_second2, s); s->next_second_time = qemu_get_clock(rtc_clock) + (get_ticks_per_sec() * 99) / 100; qemu_mod_timer(s->second_timer2, s->next_second_time); register_ioport_write(base, 2, 1, cmos_ioport_write, s); register_ioport_read(base, 2, 1, cmos_ioport_read, s); register_savevm("mc146818rtc", base, 1, rtc_save, rtc_load, s); #ifdef TARGET_I386 if (rtc_td_hack) register_savevm("mc146818rtc-td", base, 1, rtc_save_td, rtc_load_td, s); #endif qemu_register_reset(rtc_reset, s); return 0; }


static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; return virtio_load(vdev, f, version_id); }


static int read_packet(AVFormatContext *s1, AVPacket *pkt) { VideoDemuxData *s = s1->priv_data; char filename_bytes[1024]; char *filename = filename_bytes; int i; int size[3]={0}, ret[3]={0}; AVIOContext *f[3] = {NULL}; AVCodecContext *codec= s1->streams[0]->codec; if (!s->is_pipe) { /* loop over input */ if (s->loop && s->img_number > s->img_last) { s->img_number = s->img_first; } if (s->img_number > s->img_last) return AVERROR_EOF; if (s->use_glob) { #if HAVE_GLOB filename = s->globstate.gl_pathv[s->img_number]; #endif } else { if (av_get_frame_filename(filename_bytes, sizeof(filename_bytes), s->path, s->img_number)<0 && s->img_number > 1) return AVERROR(EIO); } for(i=0; i<3; i++){ if (avio_open2(&f[i], filename, AVIO_FLAG_READ, &s1->interrupt_callback, NULL) < 0) { if(i>=1) break; av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",filename); return AVERROR(EIO); } size[i]= avio_size(f[i]); if(!s->split_planes) break; filename[ strlen(filename) - 1 ]= 'U' + i; } if(codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->width) infer_size(&codec->width, &codec->height, size[0]); } else { f[0] = s1->pb; if (url_feof(f[0])) return AVERROR(EIO); size[0]= 4096; } av_new_packet(pkt, size[0] + size[1] + size[2]); pkt->stream_index = 0; pkt->flags |= AV_PKT_FLAG_KEY; pkt->size= 0; for(i=0; i<3; i++){ if(f[i]){ ret[i]= avio_read(f[i], pkt->data + pkt->size, size[i]); if (!s->is_pipe) avio_close(f[i]); if(ret[i]>0) pkt->size += ret[i]; } } if (ret[0] <= 0 || ret[1]<0 || ret[2]<0) { av_free_packet(pkt); return AVERROR(EIO); /* signal EOF */ } else { s->img_count++; s->img_number++; return 0; } }


static int smacker_read_header(AVFormatContext *s) { AVIOContext *pb = s->pb; SmackerContext *smk = s->priv_data; AVStream *st, *ast[7]; int i, ret; int tbase; /* read and check header */ smk->magic = avio_rl32(pb); if (smk->magic != MKTAG('S', 'M', 'K', '2') && smk->magic != MKTAG('S', 'M', 'K', '4')) smk->width = avio_rl32(pb); smk->height = avio_rl32(pb); smk->frames = avio_rl32(pb); smk->pts_inc = (int32_t)avio_rl32(pb); smk->flags = avio_rl32(pb); if(smk->flags & SMACKER_FLAG_RING_FRAME) smk->frames++; for(i = 0; i < 7; i++) smk->audio[i] = avio_rl32(pb); smk->treesize = avio_rl32(pb); if(smk->treesize >= UINT_MAX/4){ // smk->treesize + 16 must not overflow (this check is probably redundant) av_log(s, AV_LOG_ERROR, "treesize too large\n"); //FIXME remove extradata "rebuilding" smk->mmap_size = avio_rl32(pb); smk->mclr_size = avio_rl32(pb); smk->full_size = avio_rl32(pb); smk->type_size = avio_rl32(pb); for(i = 0; i < 7; i++) { smk->rates[i] = avio_rl24(pb); smk->aflags[i] = avio_r8(pb); smk->pad = avio_rl32(pb); /* setup data */ if(smk->frames > 0xFFFFFF) { av_log(s, AV_LOG_ERROR, "Too many frames: %"PRIu32"\n", smk->frames); smk->frm_size = av_malloc_array(smk->frames, sizeof(*smk->frm_size)); smk->frm_flags = av_malloc(smk->frames); if (!smk->frm_size || !smk->frm_flags) { av_freep(&smk->frm_size); av_freep(&smk->frm_flags); return AVERROR(ENOMEM); smk->is_ver4 = (smk->magic != MKTAG('S', 'M', 'K', '2')); /* read frame info */ for(i = 0; i < smk->frames; i++) { smk->frm_size[i] = avio_rl32(pb); for(i = 0; i < smk->frames; i++) { smk->frm_flags[i] = avio_r8(pb); /* init video codec */ st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); smk->videoindex = st->index; st->codec->width = smk->width; st->codec->height = smk->height; st->codec->pix_fmt = AV_PIX_FMT_PAL8; st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = AV_CODEC_ID_SMACKVIDEO; st->codec->codec_tag = smk->magic; /* Smacker uses 100000 as internal timebase */ if(smk->pts_inc < 0) smk->pts_inc = -smk->pts_inc; else smk->pts_inc *= 100; tbase = 100000; av_reduce(&tbase, &smk->pts_inc, tbase, smk->pts_inc, (1UL<<31)-1); avpriv_set_pts_info(st, 33, smk->pts_inc, tbase); st->duration = smk->frames; /* handle possible audio streams */ for(i = 0; i < 7; i++) { smk->indexes[i] = -1; if (smk->rates[i]) { ast[i] = avformat_new_stream(s, NULL); if (!ast[i]) return AVERROR(ENOMEM); smk->indexes[i] = ast[i]->index; ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO; if (smk->aflags[i] & SMK_AUD_BINKAUD) { ast[i]->codec->codec_id = AV_CODEC_ID_BINKAUDIO_RDFT; } else if (smk->aflags[i] & SMK_AUD_USEDCT) { ast[i]->codec->codec_id = AV_CODEC_ID_BINKAUDIO_DCT; } else if (smk->aflags[i] & SMK_AUD_PACKED){ ast[i]->codec->codec_id = AV_CODEC_ID_SMACKAUDIO; ast[i]->codec->codec_tag = MKTAG('S', 'M', 'K', 'A'); } else { ast[i]->codec->codec_id = AV_CODEC_ID_PCM_U8; if (smk->aflags[i] & SMK_AUD_STEREO) { ast[i]->codec->channels = 2; ast[i]->codec->channel_layout = AV_CH_LAYOUT_STEREO; } else { ast[i]->codec->channels = 1; ast[i]->codec->channel_layout = AV_CH_LAYOUT_MONO; ast[i]->codec->sample_rate = smk->rates[i]; ast[i]->codec->bits_per_coded_sample = (smk->aflags[i] & SMK_AUD_16BITS) ? 16 : 8; if(ast[i]->codec->bits_per_coded_sample == 16 && ast[i]->codec->codec_id == AV_CODEC_ID_PCM_U8) ast[i]->codec->codec_id = AV_CODEC_ID_PCM_S16LE; avpriv_set_pts_info(ast[i], 64, 1, ast[i]->codec->sample_rate * ast[i]->codec->channels * ast[i]->codec->bits_per_coded_sample / 8); /* load trees to extradata, they will be unpacked by decoder */ if(ff_alloc_extradata(st->codec, smk->treesize + 16)){ av_log(s, AV_LOG_ERROR, "Cannot allocate %"PRIu32" bytes of extradata\n", smk->treesize + 16); av_freep(&smk->frm_size); av_freep(&smk->frm_flags); return AVERROR(ENOMEM); ret = avio_read(pb, st->codec->extradata + 16, st->codec->extradata_size - 16); if(ret != st->codec->extradata_size - 16){ av_freep(&smk->frm_size); av_freep(&smk->frm_flags); return AVERROR(EIO); ((int32_t*)st->codec->extradata)[0] = av_le2ne32(smk->mmap_size); ((int32_t*)st->codec->extradata)[1] = av_le2ne32(smk->mclr_size); ((int32_t*)st->codec->extradata)[2] = av_le2ne32(smk->full_size); ((int32_t*)st->codec->extradata)[3] = av_le2ne32(smk->type_size); smk->curstream = -1; smk->nextpos = avio_tell(pb); return 0;


static int coroutine_fn raw_co_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors) { return bdrv_co_discard(bs->file->bs, sector_num, nb_sectors); }


BlockAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs, int64_t sector_num, int nb_sectors, BdrvRequestFlags flags, BlockCompletionFunc *cb, void *opaque) { trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque); return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors, BDRV_REQ_ZERO_WRITE | flags, cb, opaque, true); }


static void virtio_pci_reset(DeviceState *d) { VirtIOPCIProxy *proxy = container_of(d, VirtIOPCIProxy, pci_dev.qdev); virtio_reset(proxy->vdev); msix_reset(&proxy->pci_dev); proxy->flags = 0; }


static void tcg_out_dat_rIK(TCGContext *s, int cond, int opc, int opinv, TCGReg dst, TCGReg lhs, TCGArg rhs, bool rhs_is_const) { /* Emit either the reg,imm or reg,reg form of a data-processing insn. * rhs must satisfy the "rIK" constraint. */ if (rhs_is_const) { int rot = encode_imm(rhs); if (rot < 0) { rhs = ~rhs; rot = encode_imm(rhs); assert(rot >= 0); opc = opinv; } tcg_out_dat_imm(s, cond, opc, dst, lhs, rotl(rhs, rot) | (rot << 7)); } else { tcg_out_dat_reg(s, cond, opc, dst, lhs, rhs, SHIFT_IMM_LSL(0)); } }


static int twl92230_init(i2c_slave *i2c) { MenelausState *s = FROM_I2C_SLAVE(MenelausState, i2c); s->rtc.hz_tm = qemu_new_timer(rt_clock, menelaus_rtc_hz, s); /* Three output pins plus one interrupt pin. */ qdev_init_gpio_out(&i2c->qdev, s->out, 4); qdev_init_gpio_in(&i2c->qdev, menelaus_gpio_set, 3); s->pwrbtn = qemu_allocate_irqs(menelaus_pwrbtn_set, s, 1)[0]; menelaus_reset(&s->i2c); return 0; }


static int mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVContext *mov = s->priv_data; ByteIOContext *pb = s->pb; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecContext *enc = trk->enc; unsigned int samplesInChunk = 0; int size= pkt->size; if (url_is_streamed(s->pb)) return 0; /* Can't handle that */ if (!size) return 0; /* Discard 0 sized packets */ if (enc->codec_id == CODEC_ID_AMR_NB) { /* We must find out how many AMR blocks there are in one packet */ static uint16_t packed_size[16] = {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0}; int len = 0; while (len < size && samplesInChunk < 100) { len += packed_size[(pkt->data[len] >> 3) & 0x0F]; samplesInChunk++; } if(samplesInChunk > 1){ av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n"); return -1; } } else if (trk->sampleSize) samplesInChunk = size/trk->sampleSize; else samplesInChunk = 1; /* copy extradata if it exists */ if (trk->vosLen == 0 && enc->extradata_size > 0) { trk->vosLen = enc->extradata_size; trk->vosData = av_malloc(trk->vosLen); memcpy(trk->vosData, enc->extradata, trk->vosLen); } if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) { /* from x264 or from bytestream h264 */ /* nal reformating needed */ int ret = ff_avc_parse_nal_units(pkt->data, &pkt->data, &pkt->size); if (ret < 0) return ret; assert(pkt->size); size = pkt->size; } else if (enc->codec_id == CODEC_ID_DNXHD && !trk->vosLen) { /* copy frame to create needed atoms */ trk->vosLen = size; trk->vosData = av_malloc(size); memcpy(trk->vosData, pkt->data, size); } if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) { trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster)); if (!trk->cluster) return -1; } trk->cluster[trk->entry].pos = url_ftell(pb); trk->cluster[trk->entry].samplesInChunk = samplesInChunk; trk->cluster[trk->entry].size = size; trk->cluster[trk->entry].entries = samplesInChunk; trk->cluster[trk->entry].dts = pkt->dts; trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration; if (pkt->pts == AV_NOPTS_VALUE) { av_log(s, AV_LOG_WARNING, "pts has no value\n"); pkt->pts = pkt->dts; } if (pkt->dts != pkt->pts) trk->hasBframes = 1; trk->cluster[trk->entry].cts = pkt->pts - pkt->dts; trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY); if(trk->cluster[trk->entry].key_frame) trk->hasKeyframes++; trk->entry++; trk->sampleCount += samplesInChunk; mov->mdat_size += size; put_buffer(pb, pkt->data, size); put_flush_packet(pb); return 0; }


static void gen_st_cond (DisasContext *ctx, uint32_t opc, int rt, int base, int16_t offset) { const char *opn = "st_cond"; TCGv t0, t1; t0 = tcg_temp_local_new(); gen_base_offset_addr(ctx, t0, base, offset); /* Don't do NOP if destination is zero: we must perform the actual memory access. */ t1 = tcg_temp_local_new(); gen_load_gpr(t1, rt); switch (opc) { #if defined(TARGET_MIPS64) case OPC_SCD: save_cpu_state(ctx, 0); op_st_scd(t1, t0, rt, ctx); opn = "scd"; break; #endif case OPC_SC: save_cpu_state(ctx, 1); op_st_sc(t1, t0, rt, ctx); opn = "sc"; break; } (void)opn; /* avoid a compiler warning */ MIPS_DEBUG("%s %s, %d(%s)", opn, regnames[rt], offset, regnames[base]); tcg_temp_free(t1); tcg_temp_free(t0); }


static int32_t bmdma_prepare_buf(IDEDMA *dma, int is_write) { BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); IDEState *s = bmdma_active_if(bm); PCIDevice *pci_dev = PCI_DEVICE(bm->pci_dev); struct { uint32_t addr; uint32_t size; } prd; int l, len; pci_dma_sglist_init(&s->sg, pci_dev, s->nsector / (BMDMA_PAGE_SIZE / 512) + 1); s->io_buffer_size = 0; for(;;) { if (bm->cur_prd_len == 0) { /* end of table (with a fail safe of one page) */ if (bm->cur_prd_last || (bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE) { return s->io_buffer_size; } pci_dma_read(pci_dev, bm->cur_addr, &prd, 8); bm->cur_addr += 8; prd.addr = le32_to_cpu(prd.addr); prd.size = le32_to_cpu(prd.size); len = prd.size & 0xfffe; if (len == 0) len = 0x10000; bm->cur_prd_len = len; bm->cur_prd_addr = prd.addr; bm->cur_prd_last = (prd.size & 0x80000000); } l = bm->cur_prd_len; if (l > 0) { qemu_sglist_add(&s->sg, bm->cur_prd_addr, l); /* Note: We limit the max transfer to be 2GiB. * This should accommodate the largest ATA transaction * for LBA48 (65,536 sectors) and 32K sector sizes. */ if (s->sg.size > INT32_MAX) { error_report("IDE: sglist describes more than 2GiB."); break; } bm->cur_prd_addr += l; bm->cur_prd_len -= l; s->io_buffer_size += l; } } qemu_sglist_destroy(&s->sg); s->io_buffer_size = 0; return -1; }


static int apply_window_and_mdct(vorbis_enc_context *venc, float *audio, int samples) { int channel; const float * win = venc->win[0]; int window_len = 1 << (venc->log2_blocksize[0] - 1); float n = (float)(1 << venc->log2_blocksize[0]) / 4.0; AVFloatDSPContext *fdsp = venc->fdsp; if (!venc->have_saved && !samples) return 0; if (venc->have_saved) { for (channel = 0; channel < venc->channels; channel++) memcpy(venc->samples + channel * window_len * 2, venc->saved + channel * window_len, sizeof(float) * window_len); } else { for (channel = 0; channel < venc->channels; channel++) memset(venc->samples + channel * window_len * 2, 0, sizeof(float) * window_len); } if (samples) { for (channel = 0; channel < venc->channels; channel++) { float *offset = venc->samples + channel * window_len * 2 + window_len; fdsp->vector_fmul_reverse(offset, audio + channel * window_len, win, samples); fdsp->vector_fmul_scalar(offset, offset, 1/n, samples); } } else { for (channel = 0; channel < venc->channels; channel++) memset(venc->samples + channel * window_len * 2 + window_len, 0, sizeof(float) * window_len); } for (channel = 0; channel < venc->channels; channel++) venc->mdct[0].mdct_calc(&venc->mdct[0], venc->coeffs + channel * window_len, venc->samples + channel * window_len * 2); if (samples) { for (channel = 0; channel < venc->channels; channel++) { float *offset = venc->saved + channel * window_len; fdsp->vector_fmul(offset, audio + channel * window_len, win, samples); fdsp->vector_fmul_scalar(offset, offset, 1/n, samples); } venc->have_saved = 1; } else { venc->have_saved = 0; } return 1; }


static inline int popcountl(unsigned long l) { return BITS_PER_LONG == 32 ? ctpop32(l) : ctpop64(l); }


static int32_t parse_gain(const char *gain) { char *fraction; int scale = 10000; int32_t mb = 0; int sign = 1; int db; if (!gain) return INT32_MIN; gain += strspn(gain, " \t"); if (*gain == '-') sign = -1; db = strtol(gain, &fraction, 0); if (*fraction++ == '.') { while (av_isdigit(*fraction) && scale) { mb += scale * (*fraction - '0'); scale /= 10; fraction++; } } if (abs(db) > (INT32_MAX - mb) / 100000) return INT32_MIN; return db * 100000 + sign * mb; }


static inline void ide_dma_submit_check(IDEState *s, BlockDriverCompletionFunc *dma_cb) { if (s->bus->dma->aiocb) return; dma_cb(s, -1); }


static BlockStats *bdrv_query_bds_stats(const BlockDriverState *bs, bool query_backing) { BlockStats *s = NULL; s = g_malloc0(sizeof(*s)); s->stats = g_malloc0(sizeof(*s->stats)); if (!bs) { return s; } if (bdrv_get_node_name(bs)[0]) { s->has_node_name = true; s->node_name = g_strdup(bdrv_get_node_name(bs)); } s->stats->wr_highest_offset = stat64_get(&bs->wr_highest_offset); if (bs->file) { s->has_parent = true; s->parent = bdrv_query_bds_stats(bs->file->bs, query_backing); } if (query_backing && bs->backing) { s->has_backing = true; s->backing = bdrv_query_bds_stats(bs->backing->bs, query_backing); } return s; }


static int lag_decode_zero_run_line(LagarithContext *l, uint8_t *dst, const uint8_t *src, const uint8_t *src_end, int width, int esc_count) { int i = 0; int count; uint8_t zero_run = 0; const uint8_t *src_start = src; uint8_t mask1 = -(esc_count < 2); uint8_t mask2 = -(esc_count < 3); uint8_t *end = dst + (width - 2); avpriv_request_sample(l->avctx, "zero_run_line"); return AVERROR_PATCHWELCOME; output_zeros: if (l->zeros_rem) { count = FFMIN(l->zeros_rem, width - i); if (end - dst < count) { av_log(l->avctx, AV_LOG_ERROR, "Too many zeros remaining.\n"); return AVERROR_INVALIDDATA; } memset(dst, 0, count); l->zeros_rem -= count; dst += count; } while (dst < end) { i = 0; while (!zero_run && dst + i < end) { i++; if (i+2 >= src_end - src) return AVERROR_INVALIDDATA; zero_run = !(src[i] | (src[i + 1] & mask1) | (src[i + 2] & mask2)); } if (zero_run) { zero_run = 0; i += esc_count; memcpy(dst, src, i); dst += i; l->zeros_rem = lag_calc_zero_run(src[i]); src += i + 1; goto output_zeros; } else { memcpy(dst, src, i); src += i; dst += i; } } return src - src_start; }


static int ram_init_all(RAMState **rsp) { Error *local_err = NULL; if (ram_state_init(rsp)) { return -1; } if (migrate_use_xbzrle()) { XBZRLE_cache_lock(); XBZRLE.zero_target_page = g_malloc0(TARGET_PAGE_SIZE); XBZRLE.cache = cache_init(migrate_xbzrle_cache_size(), TARGET_PAGE_SIZE, &local_err); if (!XBZRLE.cache) { XBZRLE_cache_unlock(); error_report_err(local_err); g_free(*rsp); *rsp = NULL; return -1; } XBZRLE_cache_unlock(); /* We prefer not to abort if there is no memory */ XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE); if (!XBZRLE.encoded_buf) { error_report("Error allocating encoded_buf"); g_free(*rsp); *rsp = NULL; return -1; } XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE); if (!XBZRLE.current_buf) { error_report("Error allocating current_buf"); g_free(XBZRLE.encoded_buf); XBZRLE.encoded_buf = NULL; g_free(*rsp); *rsp = NULL; return -1; } } /* For memory_global_dirty_log_start below. */ qemu_mutex_lock_iothread(); qemu_mutex_lock_ramlist(); rcu_read_lock(); /* Skip setting bitmap if there is no RAM */ if (ram_bytes_total()) { RAMBlock *block; QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { unsigned long pages = block->max_length >> TARGET_PAGE_BITS; block->bmap = bitmap_new(pages); bitmap_set(block->bmap, 0, pages); if (migrate_postcopy_ram()) { block->unsentmap = bitmap_new(pages); bitmap_set(block->unsentmap, 0, pages); } } } memory_global_dirty_log_start(); migration_bitmap_sync(*rsp); qemu_mutex_unlock_ramlist(); qemu_mutex_unlock_iothread(); rcu_read_unlock(); return 0; }


static void av_always_inline filter_mb_edgecv( uint8_t *pix, int stride, int16_t bS[4], unsigned int qp, H264Context *h ) { const unsigned int index_a = qp + h->slice_alpha_c0_offset; const int alpha = alpha_table[index_a]; const int beta = beta_table[qp + h->slice_beta_offset]; if (alpha ==0 || beta == 0) return; if( bS[0] < 4 ) { int8_t tc[4]; tc[0] = tc0_table[index_a][bS[0]]+1; tc[1] = tc0_table[index_a][bS[1]]+1; tc[2] = tc0_table[index_a][bS[2]]+1; tc[3] = tc0_table[index_a][bS[3]]+1; h->h264dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc); } else { h->h264dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta); } }


static int decode_entropy_coded_image(WebPContext *s, enum ImageRole role, int w, int h) { ImageContext *img; HuffReader *hg; int i, j, ret, x, y, width; img = &s->image[role]; img->role = role; if (!img->frame) { img->frame = av_frame_alloc(); if (!img->frame) return AVERROR(ENOMEM); } img->frame->format = AV_PIX_FMT_ARGB; img->frame->width = w; img->frame->height = h; if (role == IMAGE_ROLE_ARGB && !img->is_alpha_primary) { ThreadFrame pt = { .f = img->frame }; ret = ff_thread_get_buffer(s->avctx, &pt, 0); } else ret = av_frame_get_buffer(img->frame, 1); if (ret < 0) return ret; if (get_bits1(&s->gb)) { img->color_cache_bits = get_bits(&s->gb, 4); if (img->color_cache_bits < 1 || img->color_cache_bits > 11) { av_log(s->avctx, AV_LOG_ERROR, "invalid color cache bits: %d\n", img->color_cache_bits); return AVERROR_INVALIDDATA; } img->color_cache = av_mallocz_array(1 << img->color_cache_bits, sizeof(*img->color_cache)); if (!img->color_cache) return AVERROR(ENOMEM); } else { img->color_cache_bits = 0; } img->nb_huffman_groups = 1; if (role == IMAGE_ROLE_ARGB && get_bits1(&s->gb)) { ret = decode_entropy_image(s); if (ret < 0) return ret; img->nb_huffman_groups = s->nb_huffman_groups; } img->huffman_groups = av_mallocz_array(img->nb_huffman_groups * HUFFMAN_CODES_PER_META_CODE, sizeof(*img->huffman_groups)); if (!img->huffman_groups) return AVERROR(ENOMEM); for (i = 0; i < img->nb_huffman_groups; i++) { hg = &img->huffman_groups[i * HUFFMAN_CODES_PER_META_CODE]; for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; j++) { int alphabet_size = alphabet_sizes[j]; if (!j && img->color_cache_bits > 0) alphabet_size += 1 << img->color_cache_bits; if (get_bits1(&s->gb)) { read_huffman_code_simple(s, &hg[j]); } else { ret = read_huffman_code_normal(s, &hg[j], alphabet_size); if (ret < 0) return ret; } } } width = img->frame->width; if (role == IMAGE_ROLE_ARGB && s->reduced_width > 0) width = s->reduced_width; x = 0; y = 0; while (y < img->frame->height) { int v; hg = get_huffman_group(s, img, x, y); v = huff_reader_get_symbol(&hg[HUFF_IDX_GREEN], &s->gb); if (v < NUM_LITERAL_CODES) { /* literal pixel values */ uint8_t *p = GET_PIXEL(img->frame, x, y); p[2] = v; p[1] = huff_reader_get_symbol(&hg[HUFF_IDX_RED], &s->gb); p[3] = huff_reader_get_symbol(&hg[HUFF_IDX_BLUE], &s->gb); p[0] = huff_reader_get_symbol(&hg[HUFF_IDX_ALPHA], &s->gb); if (img->color_cache_bits) color_cache_put(img, AV_RB32(p)); x++; if (x == width) { x = 0; y++; } } else if (v < NUM_LITERAL_CODES + NUM_LENGTH_CODES) { /* LZ77 backwards mapping */ int prefix_code, length, distance, ref_x, ref_y; /* parse length and distance */ prefix_code = v - NUM_LITERAL_CODES; if (prefix_code < 4) { length = prefix_code + 1; } else { int extra_bits = (prefix_code - 2) >> 1; int offset = 2 + (prefix_code & 1) << extra_bits; length = offset + get_bits(&s->gb, extra_bits) + 1; } prefix_code = huff_reader_get_symbol(&hg[HUFF_IDX_DIST], &s->gb); if (prefix_code > 39) { av_log(s->avctx, AV_LOG_ERROR, "distance prefix code too large: %d\n", prefix_code); return AVERROR_INVALIDDATA; } if (prefix_code < 4) { distance = prefix_code + 1; } else { int extra_bits = prefix_code - 2 >> 1; int offset = 2 + (prefix_code & 1) << extra_bits; distance = offset + get_bits(&s->gb, extra_bits) + 1; } /* find reference location */ if (distance <= NUM_SHORT_DISTANCES) { int xi = lz77_distance_offsets[distance - 1][0]; int yi = lz77_distance_offsets[distance - 1][1]; distance = FFMAX(1, xi + yi * width); } else { distance -= NUM_SHORT_DISTANCES; } ref_x = x; ref_y = y; if (distance <= x) { ref_x -= distance; distance = 0; } else { ref_x = 0; distance -= x; } while (distance >= width) { ref_y--; distance -= width; } if (distance > 0) { ref_x = width - distance; ref_y--; } ref_x = FFMAX(0, ref_x); ref_y = FFMAX(0, ref_y); /* copy pixels * source and dest regions can overlap and wrap lines, so just * copy per-pixel */ for (i = 0; i < length; i++) { uint8_t *p_ref = GET_PIXEL(img->frame, ref_x, ref_y); uint8_t *p = GET_PIXEL(img->frame, x, y); AV_COPY32(p, p_ref); if (img->color_cache_bits) color_cache_put(img, AV_RB32(p)); x++; ref_x++; if (x == width) { x = 0; y++; } if (ref_x == width) { ref_x = 0; ref_y++; } if (y == img->frame->height || ref_y == img->frame->height) break; } } else { /* read from color cache */ uint8_t *p = GET_PIXEL(img->frame, x, y); int cache_idx = v - (NUM_LITERAL_CODES + NUM_LENGTH_CODES); if (!img->color_cache_bits) { av_log(s->avctx, AV_LOG_ERROR, "color cache not found\n"); return AVERROR_INVALIDDATA; } if (cache_idx >= 1 << img->color_cache_bits) { av_log(s->avctx, AV_LOG_ERROR, "color cache index out-of-bounds\n"); return AVERROR_INVALIDDATA; } AV_WB32(p, img->color_cache[cache_idx]); x++; if (x == width) { x = 0; y++; } } } return 0; }


void ff_mspel_motion(MpegEncContext *s, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr, uint8_t **ref_picture, op_pixels_func (*pix_op)[4], int motion_x, int motion_y, int h) { Wmv2Context * const w= (Wmv2Context*)s; uint8_t *ptr; int dxy, offset, mx, my, src_x, src_y, v_edge_pos, linesize, uvlinesize; int emu=0; dxy = ((motion_y & 1) << 1) | (motion_x & 1); dxy = 2*dxy + w->hshift; src_x = s->mb_x * 16 + (motion_x >> 1); src_y = s->mb_y * 16 + (motion_y >> 1); /* WARNING: do no forget half pels */ v_edge_pos = s->v_edge_pos; src_x = av_clip(src_x, -16, s->width); src_y = av_clip(src_y, -16, s->height); if(src_x<=-16 || src_x >= s->width) dxy &= ~3; if(src_y<=-16 || src_y >= s->height) dxy &= ~4; linesize = s->linesize; uvlinesize = s->uvlinesize; ptr = ref_picture[0] + (src_y * linesize) + src_x; if(src_x<1 || src_y<1 || src_x + 17 >= s->h_edge_pos || src_y + h+1 >= v_edge_pos){ s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr - 1 - s->linesize, s->linesize, 19, 19, src_x-1, src_y-1, s->h_edge_pos, s->v_edge_pos); ptr= s->edge_emu_buffer + 1 + s->linesize; emu=1; } s->dsp.put_mspel_pixels_tab[dxy](dest_y , ptr , linesize); s->dsp.put_mspel_pixels_tab[dxy](dest_y+8 , ptr+8 , linesize); s->dsp.put_mspel_pixels_tab[dxy](dest_y +8*linesize, ptr +8*linesize, linesize); s->dsp.put_mspel_pixels_tab[dxy](dest_y+8+8*linesize, ptr+8+8*linesize, linesize); if(s->flags&CODEC_FLAG_GRAY) return; if (s->out_format == FMT_H263) { dxy = 0; if ((motion_x & 3) != 0) dxy |= 1; if ((motion_y & 3) != 0) dxy |= 2; mx = motion_x >> 2; my = motion_y >> 2; } else { mx = motion_x / 2; my = motion_y / 2; dxy = ((my & 1) << 1) | (mx & 1); mx >>= 1; my >>= 1; } src_x = s->mb_x * 8 + mx; src_y = s->mb_y * 8 + my; src_x = av_clip(src_x, -8, s->width >> 1); if (src_x == (s->width >> 1)) dxy &= ~1; src_y = av_clip(src_y, -8, s->height >> 1); if (src_y == (s->height >> 1)) dxy &= ~2; offset = (src_y * uvlinesize) + src_x; ptr = ref_picture[1] + offset; if(emu){ s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1); ptr= s->edge_emu_buffer; } pix_op[1][dxy](dest_cb, ptr, uvlinesize, h >> 1); ptr = ref_picture[2] + offset; if(emu){ s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1); ptr= s->edge_emu_buffer; } pix_op[1][dxy](dest_cr, ptr, uvlinesize, h >> 1); }


static int svq1_encode_plane(SVQ1Context *s, int plane, unsigned char *src_plane, unsigned char *ref_plane, unsigned char *decoded_plane, int width, int height, int src_stride, int stride) { const AVFrame *f = s->avctx->coded_frame; int x, y; int i; int block_width, block_height; int level; int threshold[6]; uint8_t *src = s->scratchbuf + stride * 16; const int lambda = (f->quality * f->quality) >> (2 * FF_LAMBDA_SHIFT); /* figure out the acceptable level thresholds in advance */ threshold[5] = QUALITY_THRESHOLD; for (level = 4; level >= 0; level--) threshold[level] = threshold[level + 1] * THRESHOLD_MULTIPLIER; block_width = (width + 15) / 16; block_height = (height + 15) / 16; if (f->pict_type == AV_PICTURE_TYPE_P) { s->m.avctx = s->avctx; s->m.current_picture_ptr = &s->m.current_picture; s->m.last_picture_ptr = &s->m.last_picture; s->m.last_picture.f.data[0] = ref_plane; s->m.linesize = s->m.last_picture.f.linesize[0] = s->m.new_picture.f.linesize[0] = s->m.current_picture.f.linesize[0] = stride; s->m.width = width; s->m.height = height; s->m.mb_width = block_width; s->m.mb_height = block_height; s->m.mb_stride = s->m.mb_width + 1; s->m.b8_stride = 2 * s->m.mb_width + 1; s->m.f_code = 1; s->m.pict_type = f->pict_type; s->m.me_method = s->avctx->me_method; s->m.me.scene_change_score = 0; s->m.flags = s->avctx->flags; // s->m.out_format = FMT_H263; // s->m.unrestricted_mv = 1; s->m.lambda = f->quality; s->m.qscale = s->m.lambda * 139 + FF_LAMBDA_SCALE * 64 >> FF_LAMBDA_SHIFT + 7; s->m.lambda2 = s->m.lambda * s->m.lambda + FF_LAMBDA_SCALE / 2 >> FF_LAMBDA_SHIFT; if (!s->motion_val8[plane]) { s->motion_val8[plane] = av_mallocz((s->m.b8_stride * block_height * 2 + 2) * 2 * sizeof(int16_t)); s->motion_val16[plane] = av_mallocz((s->m.mb_stride * (block_height + 2) + 1) * 2 * sizeof(int16_t)); } s->m.mb_type = s->mb_type; // dummies, to avoid segfaults s->m.current_picture.mb_mean = (uint8_t *)s->dummy; s->m.current_picture.mb_var = (uint16_t *)s->dummy; s->m.current_picture.mc_mb_var = (uint16_t *)s->dummy; s->m.current_picture.mb_type = s->dummy; s->m.current_picture.motion_val[0] = s->motion_val8[plane] + 2; s->m.p_mv_table = s->motion_val16[plane] + s->m.mb_stride + 1; s->m.dsp = s->dsp; // move ff_init_me(&s->m); s->m.me.dia_size = s->avctx->dia_size; s->m.first_slice_line = 1; for (y = 0; y < block_height; y++) { s->m.new_picture.f.data[0] = src - y * 16 * stride; // ugly s->m.mb_y = y; for (i = 0; i < 16 && i + 16 * y < height; i++) { memcpy(&src[i * stride], &src_plane[(i + 16 * y) * src_stride], width); for (x = width; x < 16 * block_width; x++) src[i * stride + x] = src[i * stride + x - 1]; } for (; i < 16 && i + 16 * y < 16 * block_height; i++) memcpy(&src[i * stride], &src[(i - 1) * stride], 16 * block_width); for (x = 0; x < block_width; x++) { s->m.mb_x = x; ff_init_block_index(&s->m); ff_update_block_index(&s->m); ff_estimate_p_frame_motion(&s->m, x, y); } s->m.first_slice_line = 0; } ff_fix_long_p_mvs(&s->m); ff_fix_long_mvs(&s->m, NULL, 0, s->m.p_mv_table, s->m.f_code, CANDIDATE_MB_TYPE_INTER, 0); } s->m.first_slice_line = 1; for (y = 0; y < block_height; y++) { for (i = 0; i < 16 && i + 16 * y < height; i++) { memcpy(&src[i * stride], &src_plane[(i + 16 * y) * src_stride], width); for (x = width; x < 16 * block_width; x++) src[i * stride + x] = src[i * stride + x - 1]; } for (; i < 16 && i + 16 * y < 16 * block_height; i++) memcpy(&src[i * stride], &src[(i - 1) * stride], 16 * block_width); s->m.mb_y = y; for (x = 0; x < block_width; x++) { uint8_t reorder_buffer[3][6][7 * 32]; int count[3][6]; int offset = y * 16 * stride + x * 16; uint8_t *decoded = decoded_plane + offset; uint8_t *ref = ref_plane + offset; int score[4] = { 0, 0, 0, 0 }, best; uint8_t *temp = s->scratchbuf; if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) < 3000) { // FIXME: check size av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n"); return -1; } s->m.mb_x = x; ff_init_block_index(&s->m); ff_update_block_index(&s->m); if (f->pict_type == AV_PICTURE_TYPE_I || (s->m.mb_type[x + y * s->m.mb_stride] & CANDIDATE_MB_TYPE_INTRA)) { for (i = 0; i < 6; i++) init_put_bits(&s->reorder_pb[i], reorder_buffer[0][i], 7 * 32); if (f->pict_type == AV_PICTURE_TYPE_P) { const uint8_t *vlc = ff_svq1_block_type_vlc[SVQ1_BLOCK_INTRA]; put_bits(&s->reorder_pb[5], vlc[1], vlc[0]); score[0] = vlc[1] * lambda; } score[0] += encode_block(s, src + 16 * x, NULL, temp, stride, 5, 64, lambda, 1); for (i = 0; i < 6; i++) { count[0][i] = put_bits_count(&s->reorder_pb[i]); flush_put_bits(&s->reorder_pb[i]); } } else score[0] = INT_MAX; best = 0; if (f->pict_type == AV_PICTURE_TYPE_P) { const uint8_t *vlc = ff_svq1_block_type_vlc[SVQ1_BLOCK_INTER]; int mx, my, pred_x, pred_y, dxy; int16_t *motion_ptr; motion_ptr = ff_h263_pred_motion(&s->m, 0, 0, &pred_x, &pred_y); if (s->m.mb_type[x + y * s->m.mb_stride] & CANDIDATE_MB_TYPE_INTER) { for (i = 0; i < 6; i++) init_put_bits(&s->reorder_pb[i], reorder_buffer[1][i], 7 * 32); put_bits(&s->reorder_pb[5], vlc[1], vlc[0]); s->m.pb = s->reorder_pb[5]; mx = motion_ptr[0]; my = motion_ptr[1]; assert(mx >= -32 && mx <= 31); assert(my >= -32 && my <= 31); assert(pred_x >= -32 && pred_x <= 31); assert(pred_y >= -32 && pred_y <= 31); ff_h263_encode_motion(&s->m, mx - pred_x, 1); ff_h263_encode_motion(&s->m, my - pred_y, 1); s->reorder_pb[5] = s->m.pb; score[1] += lambda * put_bits_count(&s->reorder_pb[5]); dxy = (mx & 1) + 2 * (my & 1); s->hdsp.put_pixels_tab[0][dxy](temp + 16, ref + (mx >> 1) + stride * (my >> 1), stride, 16); score[1] += encode_block(s, src + 16 * x, temp + 16, decoded, stride, 5, 64, lambda, 0); best = score[1] <= score[0]; vlc = ff_svq1_block_type_vlc[SVQ1_BLOCK_SKIP]; score[2] = s->dsp.sse[0](NULL, src + 16 * x, ref, stride, 16); score[2] += vlc[1] * lambda; if (score[2] < score[best] && mx == 0 && my == 0) { best = 2; s->hdsp.put_pixels_tab[0][0](decoded, ref, stride, 16); for (i = 0; i < 6; i++) count[2][i] = 0; put_bits(&s->pb, vlc[1], vlc[0]); } } if (best == 1) { for (i = 0; i < 6; i++) { count[1][i] = put_bits_count(&s->reorder_pb[i]); flush_put_bits(&s->reorder_pb[i]); } } else { motion_ptr[0] = motion_ptr[1] = motion_ptr[2] = motion_ptr[3] = motion_ptr[0 + 2 * s->m.b8_stride] = motion_ptr[1 + 2 * s->m.b8_stride] = motion_ptr[2 + 2 * s->m.b8_stride] = motion_ptr[3 + 2 * s->m.b8_stride] = 0; } } s->rd_total += score[best]; for (i = 5; i >= 0; i--) avpriv_copy_bits(&s->pb, reorder_buffer[best][i], count[best][i]); if (best == 0) s->hdsp.put_pixels_tab[0][0](decoded, temp, stride, 16); } s->m.first_slice_line = 0; } return 0; }


static int ffmmal_add_packet(AVCodecContext *avctx, AVPacket *avpkt, int is_extradata) { MMALDecodeContext *ctx = avctx->priv_data; AVBufferRef *buf = NULL; int size = 0; uint8_t *data = (uint8_t *)""; uint8_t *start; int ret = 0; if (avpkt->size) { if (avpkt->buf) { buf = av_buffer_ref(avpkt->buf); size = avpkt->size; data = avpkt->data; } else { buf = av_buffer_alloc(avpkt->size); if (buf) { memcpy(buf->data, avpkt->data, avpkt->size); size = buf->size; data = buf->data; } } if (!buf) { ret = AVERROR(ENOMEM); goto done; } if (!is_extradata) ctx->packets_sent++; } else { if (!ctx->packets_sent) { // Short-cut the flush logic to avoid upsetting MMAL. ctx->eos_sent = 1; ctx->eos_received = 1; goto done; } } start = data; do { FFBufferEntry *buffer = av_mallocz(sizeof(*buffer)); if (!buffer) { ret = AVERROR(ENOMEM); goto done; } buffer->data = data; buffer->length = FFMIN(size, ctx->decoder->input[0]->buffer_size); if (is_extradata) buffer->flags |= MMAL_BUFFER_HEADER_FLAG_CONFIG; if (data == start) buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_START; data += buffer->length; size -= buffer->length; buffer->pts = avpkt->pts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->pts; buffer->dts = avpkt->dts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->dts; if (!size) buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_END; if (!buffer->length) { buffer->flags |= MMAL_BUFFER_HEADER_FLAG_EOS; ctx->eos_sent = 1; } if (buf) { buffer->ref = av_buffer_ref(buf); if (!buffer->ref) { av_free(buffer); ret = AVERROR(ENOMEM); goto done; } } // Insert at end of the list if (!ctx->waiting_buffers) ctx->waiting_buffers = buffer; if (ctx->waiting_buffers_tail) ctx->waiting_buffers_tail->next = buffer; ctx->waiting_buffers_tail = buffer; } while (size); done: av_buffer_unref(&buf); return ret; }


static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost) { AVBitStreamFilterContext *bsfc = ost->bitstream_filters; AVCodecContext *avctx = ost->st->codec; int ret; if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) || (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0)) pkt->pts = pkt->dts = AV_NOPTS_VALUE; if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) { int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT); if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE && max > pkt->dts) { av_log(s, max - pkt->dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt->dts, max); pkt->pts = pkt->dts = max; /* * Audio encoders may split the packets -- #frames in != #packets out. * But there is no reordering, so we can limit the number of output packets * by simply dropping them here. * Counting encoded video frames needs to be done separately because of * reordering, see do_video_out() */ if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) { if (ost->frame_number >= ost->max_frames) { av_free_packet(pkt); return; ost->frame_number++; while (bsfc) { AVPacket new_pkt = *pkt; int a = av_bitstream_filter_filter(bsfc, avctx, NULL, &new_pkt.data, &new_pkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY); if (a > 0) { av_free_packet(pkt); new_pkt.destruct = av_destruct_packet; } else if (a < 0) { av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s", bsfc->filter->name, pkt->stream_index, avctx->codec ? avctx->codec->name : "copy"); print_error("", a); if (exit_on_error) exit_program(1); *pkt = new_pkt; bsfc = bsfc->next; pkt->stream_index = ost->index; ret = av_interleaved_write_frame(s, pkt); if (ret < 0) { print_error("av_interleaved_write_frame()", ret); exit_program(1);


void qed_commit_l2_cache_entry(L2TableCache *l2_cache, CachedL2Table *l2_table) { CachedL2Table *entry; entry = qed_find_l2_cache_entry(l2_cache, l2_table->offset); if (entry) { qed_unref_l2_cache_entry(entry); qed_unref_l2_cache_entry(l2_table); return; } if (l2_cache->n_entries >= MAX_L2_CACHE_SIZE) { entry = QTAILQ_FIRST(&l2_cache->entries); QTAILQ_REMOVE(&l2_cache->entries, entry, node); l2_cache->n_entries--; qed_unref_l2_cache_entry(entry); } l2_cache->n_entries++; QTAILQ_INSERT_TAIL(&l2_cache->entries, l2_table, node); }


av_cold void ff_pixblockdsp_init_x86(PixblockDSPContext *c, AVCodecContext *avctx, unsigned high_bit_depth) { int cpu_flags = av_get_cpu_flags(); if (EXTERNAL_MMX(cpu_flags)) { if (!high_bit_depth) c->get_pixels = ff_get_pixels_mmx; c->diff_pixels = ff_diff_pixels_mmx; } if (EXTERNAL_SSE2(cpu_flags)) { if (!high_bit_depth) c->get_pixels = ff_get_pixels_sse2; c->diff_pixels = ff_diff_pixels_sse2; } }


static USBDevice *usb_net_init(const char *cmdline) { USBDevice *dev; QemuOpts *opts; int idx; opts = qemu_opts_parse(&qemu_net_opts, cmdline, NULL); if (!opts) { qemu_opt_set(opts, "type", "nic"); qemu_opt_set(opts, "model", "usb"); idx = net_client_init(NULL, opts, 0); if (idx == -1) { dev = usb_create(NULL /* FIXME */, "usb-net"); qdev_set_nic_properties(&dev->qdev, &nd_table[idx]); qdev_init_nofail(&dev->qdev); return dev;


static void pkt_dump_internal(void *avcl, FILE *f, int level, const AVPacket *pkt, int dump_payload, AVRational time_base) { HEXDUMP_PRINT("stream #%d:\n", pkt->stream_index); HEXDUMP_PRINT(" keyframe=%d\n", (pkt->flags & AV_PKT_FLAG_KEY) != 0); HEXDUMP_PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base)); /* DTS is _always_ valid after av_read_frame() */ HEXDUMP_PRINT(" dts="); if (pkt->dts == AV_NOPTS_VALUE) HEXDUMP_PRINT("N/A"); else HEXDUMP_PRINT("%0.3f", pkt->dts * av_q2d(time_base)); /* PTS may not be known if B-frames are present. */ HEXDUMP_PRINT(" pts="); if (pkt->pts == AV_NOPTS_VALUE) HEXDUMP_PRINT("N/A"); else HEXDUMP_PRINT("%0.3f", pkt->pts * av_q2d(time_base)); HEXDUMP_PRINT("\n"); HEXDUMP_PRINT(" size=%d\n", pkt->size); if (dump_payload) av_hex_dump(f, pkt->data, pkt->size); }


static void handle_mousewheel(SDL_Event *ev) { struct sdl2_console *scon = get_scon_from_window(ev->key.windowID); SDL_MouseWheelEvent *wev = &ev->wheel; InputButton btn; if (wev->y > 0) { btn = INPUT_BUTTON_WHEEL_UP; } else if (wev->y < 0) { btn = INPUT_BUTTON_WHEEL_DOWN; } else { return; } qemu_input_queue_btn(scon->dcl.con, btn, true); qemu_input_event_sync(); qemu_input_queue_btn(scon->dcl.con, btn, false); qemu_input_event_sync(); }


static void init_virtio_dev(TestServer *s) { QPCIBus *bus; QVirtioPCIDevice *dev; uint32_t features; bus = qpci_init_pc(NULL); g_assert_nonnull(bus); dev = qvirtio_pci_device_find(bus, VIRTIO_ID_NET); g_assert_nonnull(dev); qvirtio_pci_device_enable(dev); qvirtio_reset(&dev->vdev); qvirtio_set_acknowledge(&dev->vdev); qvirtio_set_driver(&dev->vdev); features = qvirtio_get_features(&dev->vdev); features = features & VIRTIO_NET_F_MAC; qvirtio_set_features(&dev->vdev, features); qvirtio_set_driver_ok(&dev->vdev); }


int av_packet_split_side_data(AVPacket *pkt){ if (!pkt->side_data_elems && pkt->size >12 && AV_RB64(pkt->data + pkt->size - 8) == FF_MERGE_MARKER){ int i; unsigned int size; uint8_t *p; p = pkt->data + pkt->size - 8 - 5; for (i=1; ; i++){ size = AV_RB32(p); if (size>INT_MAX || p - pkt->data < size) return 0; if (p[4]&128) break; p-= size+5; } pkt->side_data = av_malloc_array(i, sizeof(*pkt->side_data)); if (!pkt->side_data) return AVERROR(ENOMEM); p= pkt->data + pkt->size - 8 - 5; for (i=0; ; i++){ size= AV_RB32(p); av_assert0(size<=INT_MAX && p - pkt->data >= size); pkt->side_data[i].data = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE); pkt->side_data[i].size = size; pkt->side_data[i].type = p[4]&127; if (!pkt->side_data[i].data) return AVERROR(ENOMEM); memcpy(pkt->side_data[i].data, p-size, size); pkt->size -= size + 5; if(p[4]&128) break; p-= size+5; } pkt->size -= 8; pkt->side_data_elems = i+1; return 1; } return 0; }


static void usb_msd_cancel_io(USBDevice *dev, USBPacket *p) { MSDState *s = DO_UPCAST(MSDState, dev, dev); scsi_req_cancel(s->req); }


ram_addr_t ppc405_set_bootinfo (CPUState *env, ppc4xx_bd_info_t *bd, uint32_t flags) { ram_addr_t bdloc; int i, n; /* We put the bd structure at the top of memory */ if (bd->bi_memsize >= 0x01000000UL) bdloc = 0x01000000UL - sizeof(struct ppc4xx_bd_info_t); else bdloc = bd->bi_memsize - sizeof(struct ppc4xx_bd_info_t); stl_phys(bdloc + 0x00, bd->bi_memstart); stl_phys(bdloc + 0x04, bd->bi_memsize); stl_phys(bdloc + 0x08, bd->bi_flashstart); stl_phys(bdloc + 0x0C, bd->bi_flashsize); stl_phys(bdloc + 0x10, bd->bi_flashoffset); stl_phys(bdloc + 0x14, bd->bi_sramstart); stl_phys(bdloc + 0x18, bd->bi_sramsize); stl_phys(bdloc + 0x1C, bd->bi_bootflags); stl_phys(bdloc + 0x20, bd->bi_ipaddr); for (i = 0; i < 6; i++) stb_phys(bdloc + 0x24 + i, bd->bi_enetaddr[i]); stw_phys(bdloc + 0x2A, bd->bi_ethspeed); stl_phys(bdloc + 0x2C, bd->bi_intfreq); stl_phys(bdloc + 0x30, bd->bi_busfreq); stl_phys(bdloc + 0x34, bd->bi_baudrate); for (i = 0; i < 4; i++) stb_phys(bdloc + 0x38 + i, bd->bi_s_version[i]); for (i = 0; i < 32; i++) stb_phys(bdloc + 0x3C + i, bd->bi_s_version[i]); stl_phys(bdloc + 0x5C, bd->bi_plb_busfreq); stl_phys(bdloc + 0x60, bd->bi_pci_busfreq); for (i = 0; i < 6; i++) stb_phys(bdloc + 0x64 + i, bd->bi_pci_enetaddr[i]); n = 0x6A; if (flags & 0x00000001) { for (i = 0; i < 6; i++) stb_phys(bdloc + n++, bd->bi_pci_enetaddr2[i]); } stl_phys(bdloc + n, bd->bi_opbfreq); n += 4; for (i = 0; i < 2; i++) { stl_phys(bdloc + n, bd->bi_iic_fast[i]); n += 4; } return bdloc; }


bool virtio_ipl_disk_is_valid(void) { return blk_cfg.blk_size && (virtio_disk_is_scsi() || virtio_disk_is_eckd()); }


static void bdrv_password_cb(Monitor *mon, const char *password, void *opaque) { BlockDriverState *bs = opaque; int ret = 0; if (bdrv_set_key(bs, password) != 0) { monitor_printf(mon, "invalid password\n"); ret = -EPERM; } if (mon->password_completion_cb) mon->password_completion_cb(mon->password_opaque, ret); monitor_read_command(mon, 1); }


dshow_cycle_devices(AVFormatContext *avctx, ICreateDevEnum *devenum, enum dshowDeviceType devtype, IBaseFilter **pfilter) { struct dshow_ctx *ctx = avctx->priv_data; IBaseFilter *device_filter = NULL; IEnumMoniker *classenum = NULL; IMoniker *m = NULL; const char *device_name = ctx->device_name[devtype]; int skip = (devtype == VideoDevice) ? ctx->video_device_number : ctx->audio_device_number; int r; const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory, &CLSID_AudioInputDeviceCategory }; const char *devtypename = (devtype == VideoDevice) ? "video" : "audio"; r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[devtype], (IEnumMoniker **) &classenum, 0); if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices.\n", devtypename); return AVERROR(EIO); } while (!device_filter && IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK) { IPropertyBag *bag = NULL; char *buf = NULL; VARIANT var; r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag); if (r != S_OK) goto fail1; var.vt = VT_BSTR; r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL); if (r != S_OK) goto fail1; buf = dup_wchar_to_utf8(var.bstrVal); if (pfilter) { if (strcmp(device_name, buf)) goto fail1; if (!skip--) IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter); } else { av_log(avctx, AV_LOG_INFO, " \"%s\"\n", buf); } fail1: if (buf) av_free(buf); if (bag) IPropertyBag_Release(bag); IMoniker_Release(m); } IEnumMoniker_Release(classenum); if (pfilter) { if (!device_filter) { av_log(avctx, AV_LOG_ERROR, "Could not find %s device.\n", devtypename); return AVERROR(EIO); } *pfilter = device_filter; } return 0; }


static int do_decode(AVCodecContext *avctx, AVPacket *pkt) { int got_frame; int ret; av_assert0(!avctx->internal->buffer_frame->buf[0]); if (!pkt) pkt = avctx->internal->buffer_pkt; // This is the lesser evil. The field is for compatibility with legacy users // of the legacy API, and users using the new API should not be forced to // even know about this field. avctx->refcounted_frames = 1; // Some codecs (at least wma lossless) will crash when feeding drain packets // after EOF was signaled. if (avctx->internal->draining_done) return AVERROR_EOF; if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) { ret = avcodec_decode_video2(avctx, avctx->internal->buffer_frame, &got_frame, pkt); if (ret >= 0 && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED)) ret = pkt->size; } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) { ret = avcodec_decode_audio4(avctx, avctx->internal->buffer_frame, &got_frame, pkt); } else { ret = AVERROR(EINVAL); } if (ret == AVERROR(EAGAIN)) ret = pkt->size; if (ret < 0) return ret; if (avctx->internal->draining && !got_frame) avctx->internal->draining_done = 1; if (ret >= pkt->size) { av_packet_unref(avctx->internal->buffer_pkt); } else { int consumed = ret; if (pkt != avctx->internal->buffer_pkt) { av_packet_unref(avctx->internal->buffer_pkt); if ((ret = av_packet_ref(avctx->internal->buffer_pkt, pkt)) < 0) return ret; } avctx->internal->buffer_pkt->data += consumed; avctx->internal->buffer_pkt->size -= consumed; avctx->internal->buffer_pkt->pts = AV_NOPTS_VALUE; avctx->internal->buffer_pkt->dts = AV_NOPTS_VALUE; } if (got_frame) av_assert0(avctx->internal->buffer_frame->buf[0]); return 0; }


void net_host_device_remove(Monitor *mon, int vlan_id, const char *device) { VLANState *vlan; VLANClientState *vc; vlan = qemu_find_vlan(vlan_id); for(vc = vlan->first_client; vc != NULL; vc = vc->next) if (!strcmp(vc->name, device)) break; if (!vc) { monitor_printf(mon, "can't find device %s\n", device); return; } qemu_del_vlan_client(vc); }


static void vfio_bar_write(void *opaque, hwaddr addr, uint64_t data, unsigned size) { VFIOBAR *bar = opaque; union { uint8_t byte; uint16_t word; uint32_t dword; uint64_t qword; } buf; switch (size) { case 1: buf.byte = data; break; case 2: buf.word = cpu_to_le16(data); break; case 4: buf.dword = cpu_to_le32(data); break; default: hw_error("vfio: unsupported write size, %d bytes\n", size); break; } if (pwrite(bar->fd, &buf, size, bar->fd_offset + addr) != size) { error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m", __func__, addr, data, size); } DPRINTF("%s(BAR%d+0x%"HWADDR_PRIx", 0x%"PRIx64", %d)\n", __func__, bar->nr, addr, data, size); /* * A read or write to a BAR always signals an INTx EOI. This will * do nothing if not pending (including not in INTx mode). We assume * that a BAR access is in response to an interrupt and that BAR * accesses will service the interrupt. Unfortunately, we don't know * which access will service the interrupt, so we're potentially * getting quite a few host interrupts per guest interrupt. */ vfio_eoi(container_of(bar, VFIODevice, bars[bar->nr])); }


static void mcf5208evb_init(QEMUMachineInitArgs *args) { ram_addr_t ram_size = args->ram_size; const char *cpu_model = args->cpu_model; const char *kernel_filename = args->kernel_filename; CPUM68KState *env; int kernel_size; uint64_t elf_entry; target_phys_addr_t entry; qemu_irq *pic; MemoryRegion *address_space_mem = get_system_memory(); MemoryRegion *ram = g_new(MemoryRegion, 1); MemoryRegion *sram = g_new(MemoryRegion, 1); if (!cpu_model) cpu_model = "m5208"; env = cpu_init(cpu_model); if (!env) { fprintf(stderr, "Unable to find m68k CPU definition\n"); exit(1); } /* Initialize CPU registers. */ env->vbr = 0; /* TODO: Configure BARs. */ /* DRAM at 0x40000000 */ memory_region_init_ram(ram, "mcf5208.ram", ram_size); vmstate_register_ram_global(ram); memory_region_add_subregion(address_space_mem, 0x40000000, ram); /* Internal SRAM. */ memory_region_init_ram(sram, "mcf5208.sram", 16384); vmstate_register_ram_global(sram); memory_region_add_subregion(address_space_mem, 0x80000000, sram); /* Internal peripherals. */ pic = mcf_intc_init(address_space_mem, 0xfc048000, env); mcf_uart_mm_init(address_space_mem, 0xfc060000, pic[26], serial_hds[0]); mcf_uart_mm_init(address_space_mem, 0xfc064000, pic[27], serial_hds[1]); mcf_uart_mm_init(address_space_mem, 0xfc068000, pic[28], serial_hds[2]); mcf5208_sys_init(address_space_mem, pic); if (nb_nics > 1) { fprintf(stderr, "Too many NICs\n"); exit(1); } if (nd_table[0].used) mcf_fec_init(address_space_mem, &nd_table[0], 0xfc030000, pic + 36); /* 0xfc000000 SCM. */ /* 0xfc004000 XBS. */ /* 0xfc008000 FlexBus CS. */ /* 0xfc030000 FEC. */ /* 0xfc040000 SCM + Power management. */ /* 0xfc044000 eDMA. */ /* 0xfc048000 INTC. */ /* 0xfc058000 I2C. */ /* 0xfc05c000 QSPI. */ /* 0xfc060000 UART0. */ /* 0xfc064000 UART0. */ /* 0xfc068000 UART0. */ /* 0xfc070000 DMA timers. */ /* 0xfc080000 PIT0. */ /* 0xfc084000 PIT1. */ /* 0xfc088000 EPORT. */ /* 0xfc08c000 Watchdog. */ /* 0xfc090000 clock module. */ /* 0xfc0a0000 CCM + reset. */ /* 0xfc0a4000 GPIO. */ /* 0xfc0a8000 SDRAM controller. */ /* Load kernel. */ if (!kernel_filename) { fprintf(stderr, "Kernel image must be specified\n"); exit(1); } kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry, NULL, NULL, 1, ELF_MACHINE, 0); entry = elf_entry; if (kernel_size < 0) { kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL); } if (kernel_size < 0) { kernel_size = load_image_targphys(kernel_filename, 0x40000000, ram_size); entry = 0x40000000; } if (kernel_size < 0) { fprintf(stderr, "qemu: could not load kernel '%s'\n", kernel_filename); exit(1); } env->pc = entry; }


static QObject *parse_escape(JSONParserContext *ctxt, va_list *ap) { QObject *token; const char *val; if (ap == NULL) { return NULL; } token = parser_context_pop_token(ctxt); assert(token && token_get_type(token) == JSON_ESCAPE); val = token_get_value(token); if (!strcmp(val, "%p")) { return va_arg(*ap, QObject *); } else if (!strcmp(val, "%i")) { return QOBJECT(qbool_from_bool(va_arg(*ap, int))); } else if (!strcmp(val, "%d")) { return QOBJECT(qint_from_int(va_arg(*ap, int))); } else if (!strcmp(val, "%ld")) { return QOBJECT(qint_from_int(va_arg(*ap, long))); } else if (!strcmp(val, "%lld") || !strcmp(val, "%I64d")) { return QOBJECT(qint_from_int(va_arg(*ap, long long))); } else if (!strcmp(val, "%s")) { return QOBJECT(qstring_from_str(va_arg(*ap, const char *))); } else if (!strcmp(val, "%f")) { return QOBJECT(qfloat_from_double(va_arg(*ap, double))); } return NULL; }


static inline uint64_t ldq_phys_internal(hwaddr addr, enum device_endian endian) { uint8_t *ptr; uint64_t val; MemoryRegionSection *section; section = phys_page_find(address_space_memory.dispatch, addr >> TARGET_PAGE_BITS); if (!(memory_region_is_ram(section->mr) || memory_region_is_romd(section->mr))) { /* I/O case */ addr = memory_region_section_addr(section, addr); /* XXX This is broken when device endian != cpu endian. Fix and add "endian" variable check */ #ifdef TARGET_WORDS_BIGENDIAN val = io_mem_read(section->mr, addr, 4) << 32; val |= io_mem_read(section->mr, addr + 4, 4); #else val = io_mem_read(section->mr, addr, 4); val |= io_mem_read(section->mr, addr + 4, 4) << 32; #endif } else { /* RAM case */ ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(section->mr) & TARGET_PAGE_MASK) + memory_region_section_addr(section, addr)); switch (endian) { case DEVICE_LITTLE_ENDIAN: val = ldq_le_p(ptr); break; case DEVICE_BIG_ENDIAN: val = ldq_be_p(ptr); break; default: val = ldq_p(ptr); break; } } return val; }


void main_loop_wait(int nonblocking) { fd_set rfds, wfds, xfds; int ret, nfds; struct timeval tv; int timeout; if (nonblocking) timeout = 0; else { timeout = qemu_calculate_timeout(); qemu_bh_update_timeout(&timeout); } os_host_main_loop_wait(&timeout); tv.tv_sec = timeout / 1000; tv.tv_usec = (timeout % 1000) * 1000; /* poll any events */ /* XXX: separate device handlers from system ones */ nfds = -1; FD_ZERO(&rfds); FD_ZERO(&wfds); FD_ZERO(&xfds); qemu_iohandler_fill(&nfds, &rfds, &wfds, &xfds); slirp_select_fill(&nfds, &rfds, &wfds, &xfds); qemu_mutex_unlock_iothread(); ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv); qemu_mutex_lock_iothread(); qemu_iohandler_poll(&rfds, &wfds, &xfds, ret); slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0)); qemu_run_all_timers(); /* Check bottom-halves last in case any of the earlier events triggered them. */ qemu_bh_poll(); }


void bdrv_invalidate_cache_all(Error **errp) { BlockDriverState *bs; Error *local_err = NULL; BdrvNextIterator *it = NULL; while ((it = bdrv_next(it, &bs)) != NULL) { AioContext *aio_context = bdrv_get_aio_context(bs); aio_context_acquire(aio_context); bdrv_invalidate_cache(bs, &local_err); aio_context_release(aio_context); if (local_err) { error_propagate(errp, local_err); return; } } }


static int parse_adaptation_sets(AVFormatContext *s) { WebMDashMuxContext *w = s->priv_data; char *p = w->adaptation_sets; char *q; enum { new_set, parsed_id, parsing_streams } state; if (!w->adaptation_sets) { av_log(s, AV_LOG_ERROR, "The 'adaptation_sets' option must be set.\n"); return AVERROR(EINVAL); } // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on state = new_set; while (p < w->adaptation_sets + strlen(w->adaptation_sets)) { if (*p == ' ') continue; else if (state == new_set && !strncmp(p, "id=", 3)) { void *mem = av_realloc(w->as, sizeof(*w->as) * (w->nb_as + 1)); if (mem == NULL) return AVERROR(ENOMEM); w->as = mem; ++w->nb_as; w->as[w->nb_as - 1].nb_streams = 0; w->as[w->nb_as - 1].streams = NULL; p += 3; // consume "id=" q = w->as[w->nb_as - 1].id; while (*p != ',') *q++ = *p++; *q = 0; p++; state = parsed_id; } else if (state == parsed_id && !strncmp(p, "streams=", 8)) { p += 8; // consume "streams=" state = parsing_streams; } else if (state == parsing_streams) { struct AdaptationSet *as = &w->as[w->nb_as - 1]; q = p; while (*q != '\0' && *q != ',' && *q != ' ') q++; as->streams = av_realloc(as->streams, sizeof(*as->streams) * ++as->nb_streams); if (as->streams == NULL) return AVERROR(ENOMEM); as->streams[as->nb_streams - 1] = to_integer(p, q - p + 1); if (as->streams[as->nb_streams - 1] < 0) return -1; if (*q == '\0') break; if (*q == ' ') state = new_set; p = ++q; } else { return -1; } } return 0; }


static QObject *parse_keyword(JSONParserContext *ctxt) { QObject *token, *ret; JSONParserContext saved_ctxt = parser_context_save(ctxt); token = parser_context_pop_token(ctxt); if (token == NULL) { goto out; } if (token_get_type(token) != JSON_KEYWORD) { goto out; } if (token_is_keyword(token, "true")) { ret = QOBJECT(qbool_from_int(true)); } else if (token_is_keyword(token, "false")) { ret = QOBJECT(qbool_from_int(false)); } else { parse_error(ctxt, token, "invalid keyword `%s'", token_get_value(token)); goto out; } return ret; out: parser_context_restore(ctxt, saved_ctxt); return NULL; }


static int aac_encode_frame(AVCodecContext *avctx, uint8_t *frame, int buf_size, void *data) { AACEncContext *s = avctx->priv_data; int16_t *samples = s->samples, *samples2, *la; ChannelElement *cpe; int i, j, chans, tag, start_ch; const uint8_t *chan_map = aac_chan_configs[avctx->channels-1]; int chan_el_counter[4]; FFPsyWindowInfo windows[AAC_MAX_CHANNELS]; if (s->last_frame) return 0; if (data) { if (!s->psypp) { memcpy(s->samples + 1024 * avctx->channels, data, 1024 * avctx->channels * sizeof(s->samples[0])); } else { start_ch = 0; samples2 = s->samples + 1024 * avctx->channels; for (i = 0; i < chan_map[0]; i++) { tag = chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; ff_psy_preprocess(s->psypp, (uint16_t*)data + start_ch, samples2 + start_ch, start_ch, chans); start_ch += chans; } } } if (!avctx->frame_number) { memcpy(s->samples, s->samples + 1024 * avctx->channels, 1024 * avctx->channels * sizeof(s->samples[0])); return 0; } start_ch = 0; for (i = 0; i < chan_map[0]; i++) { FFPsyWindowInfo* wi = windows + start_ch; tag = chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; cpe = &s->cpe[i]; for (j = 0; j < chans; j++) { IndividualChannelStream *ics = &cpe->ch[j].ics; int k; int cur_channel = start_ch + j; samples2 = samples + cur_channel; la = samples2 + (448+64) * avctx->channels; if (!data) la = NULL; if (tag == TYPE_LFE) { wi[j].window_type[0] = ONLY_LONG_SEQUENCE; wi[j].window_shape = 0; wi[j].num_windows = 1; wi[j].grouping[0] = 1; } else { wi[j] = ff_psy_suggest_window(&s->psy, samples2, la, cur_channel, ics->window_sequence[0]); } ics->window_sequence[1] = ics->window_sequence[0]; ics->window_sequence[0] = wi[j].window_type[0]; ics->use_kb_window[1] = ics->use_kb_window[0]; ics->use_kb_window[0] = wi[j].window_shape; ics->num_windows = wi[j].num_windows; ics->swb_sizes = s->psy.bands [ics->num_windows == 8]; ics->num_swb = tag == TYPE_LFE ? 12 : s->psy.num_bands[ics->num_windows == 8]; for (k = 0; k < ics->num_windows; k++) ics->group_len[k] = wi[j].grouping[k]; apply_window_and_mdct(avctx, s, &cpe->ch[j], samples2); } start_ch += chans; } do { int frame_bits; init_put_bits(&s->pb, frame, buf_size*8); if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT)) put_bitstream_info(avctx, s, LIBAVCODEC_IDENT); start_ch = 0; memset(chan_el_counter, 0, sizeof(chan_el_counter)); for (i = 0; i < chan_map[0]; i++) { FFPsyWindowInfo* wi = windows + start_ch; tag = chan_map[i+1]; chans = tag == TYPE_CPE ? 2 : 1; cpe = &s->cpe[i]; put_bits(&s->pb, 3, tag); put_bits(&s->pb, 4, chan_el_counter[tag]++); for (j = 0; j < chans; j++) { s->cur_channel = start_ch + j; ff_psy_set_band_info(&s->psy, s->cur_channel, cpe->ch[j].coeffs, &wi[j]); s->coder->search_for_quantizers(avctx, s, &cpe->ch[j], s->lambda); } cpe->common_window = 0; if (chans > 1 && wi[0].window_type[0] == wi[1].window_type[0] && wi[0].window_shape == wi[1].window_shape) { cpe->common_window = 1; for (j = 0; j < wi[0].num_windows; j++) { if (wi[0].grouping[j] != wi[1].grouping[j]) { cpe->common_window = 0; break; } } } s->cur_channel = start_ch; if (cpe->common_window && s->coder->search_for_ms) s->coder->search_for_ms(s, cpe, s->lambda); adjust_frame_information(s, cpe, chans); if (chans == 2) { put_bits(&s->pb, 1, cpe->common_window); if (cpe->common_window) { put_ics_info(s, &cpe->ch[0].ics); encode_ms_info(&s->pb, cpe); } } for (j = 0; j < chans; j++) { s->cur_channel = start_ch + j; encode_individual_channel(avctx, s, &cpe->ch[j], cpe->common_window); } start_ch += chans; } frame_bits = put_bits_count(&s->pb); if (frame_bits <= 6144 * avctx->channels - 3) { s->psy.bitres.bits = frame_bits / avctx->channels; break; } s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits; } while (1); put_bits(&s->pb, 3, TYPE_END); flush_put_bits(&s->pb); avctx->frame_bits = put_bits_count(&s->pb); // rate control stuff if (!(avctx->flags & CODEC_FLAG_QSCALE)) { float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits; s->lambda *= ratio; s->lambda = FFMIN(s->lambda, 65536.f); } if (!data) s->last_frame = 1; memcpy(s->samples, s->samples + 1024 * avctx->channels, 1024 * avctx->channels * sizeof(s->samples[0])); return put_bits_count(&s->pb)>>3; }