Frame * Decoder::decodeAudio2(Packet & packet) {
  LOGTRACEMETHOD("Decode Audio");
  LOGDEBUG(packet.toString());
  //        Frame frame;
  Frame * frame = new Frame();
  int size = packet.packet->size;
  int samples_size = 192000;//AVCODEC_MAX_AUDIO_FRAME_SIZE;
  int bps = av_get_bytes_per_sample(ctx->sample_fmt);
  //uint8_t* t=(uint8_t*)av_malloc(100);
  //uint8_t *outbuf = static_cast<uint8_t*> (av_malloc(samples_size));
  //int len = avcodec_decode_audio3(ctx, (short *) outbuf, &samples_size, packet.packet);
  int len = avcodec_decode_audio4(ctx, frame->getAVFrame(), &samples_size, packet.packet);

  //@TODO: this is a hack, because the decoder changes the TimeBase after the first packet was decoded
  if (_next_pts == AV_NOPTS_VALUE) {
#ifdef USE_TIME_BASE_Q
    _next_pts = av_rescale_q(packet.getPts(), packet.getTimeBase(), AV_TIME_BASE_Q);
#else
    _next_pts = av_rescale_q(packet.getPts(), packet.getTimeBase(), ctx->time_base);
#endif

    LOGDEBUG("setting last pts to " << _next_pts << " ctxtb=" << ctx->time_base.num << "/" << ctx->time_base.den
    << " ptb=" << packet.getTimeBase().num << "/" << packet.getTimeBase().den);
  }
  LOGDEBUG("DecodingLength:" << len << " PacketSize:" << packet.getSize() << "SampleSize:" << samples_size << "FrameSize:" << ctx->frame_size * ctx->channels);
  if (len < 0 /*||ctx->channels<=0||samples_size<=0*/) {
    LOGERROR("Error while decoding audio Frame");
    //av_free(outbuf);
    return new Frame();
  }
  //Frame * frame = new Frame(outbuf,samples_size);
  if (samples_size > 0) {
    frame->setFinished(true);
  } else {
    frame->setFinished(false);
  }
  size -= len;

  frame->_allocated = true;
  //frame->getAVFrame()->nb_samples=samples_size;
  //  frame._buffer = outbuf;
  frame->stream_index = packet.packet->stream_index;


  frame->setPts(_next_pts);
  //frame->setDts(_next_pts);
  AVRational ar;
  ar.num = 1;
  ar.den = ctx->sample_rate;
#ifdef USE_TIME_BASE_Q
  int64_t dur = av_rescale_q(samples_size, ar, AV_TIME_BASE_Q);
  frame->duration = dur;
  frame->setTimeBase(AV_TIME_BASE_Q);
#else
  //  int64_t dur = av_rescale_q(samples_size, packet.getTimeBase(), ar);
  //samples_size=max(1,samples_size);
  int64_t dur = ((int64_t) AV_TIME_BASE / bps * samples_size) / (ctx->sample_rate * ctx->channels);
  AVRational arbase;
  arbase.num = 1;
  arbase.den = AV_TIME_BASE;

  frame->duration = av_rescale_q(dur, arbase, ar);
  frame->setTimeBase(ar);

  //  _last_pts += frame->duration;
#endif
  _last_pts = _next_pts;
  _next_pts += frame->duration;
  frame->pos = packet.packet->pos;
  //  frame->duration = packet.packet->duration;
  /*
  frame->_size = samples_size;
  frame->_buffer=outbuf;
  */
  frame->_type = AVMEDIA_TYPE_AUDIO;
  frame->channels = ctx->channels;
  frame->sample_rate = ctx->sample_rate;
  //frame->dumpHex();
  LOGDEBUG(frame->toString());
  //  frame->dumpHex();
  pushFrame(new Frame(*frame));

  return frame;
}
Esempio n. 2
0
bool EditorClientEfl::handleEditingKeyboardEvent(KeyboardEvent* event)
{
    Node* node = event->target()->toNode();
    ASSERT(node);
    Frame* frame = node->document().frame();
    ASSERT(frame);

    const PlatformKeyboardEvent* keyEvent = event->keyEvent();
    if (!keyEvent)
        return false;

    bool caretBrowsing = frame->settings().caretBrowsingEnabled();
    if (caretBrowsing) {
        switch (keyEvent->windowsVirtualKeyCode()) {
        case VK_LEFT:
            frame->selection().modify(keyEvent->shiftKey() ? FrameSelection::AlterationExtend : FrameSelection::AlterationMove,
                                       DirectionLeft,
                                       keyEvent->ctrlKey() ? WordGranularity : CharacterGranularity,
                                       UserTriggered);
            return true;
        case VK_RIGHT:
            frame->selection().modify(keyEvent->shiftKey() ? FrameSelection::AlterationExtend : FrameSelection::AlterationMove,
                                       DirectionRight,
                                       keyEvent->ctrlKey() ? WordGranularity : CharacterGranularity,
                                       UserTriggered);
            return true;
        case VK_UP:
            frame->selection().modify(keyEvent->shiftKey() ? FrameSelection::AlterationExtend : FrameSelection::AlterationMove,
                                       DirectionBackward,
                                       keyEvent->ctrlKey() ? ParagraphGranularity : LineGranularity,
                                       UserTriggered);
            return true;
        case VK_DOWN:
            frame->selection().modify(keyEvent->shiftKey() ? FrameSelection::AlterationExtend : FrameSelection::AlterationMove,
                                       DirectionForward,
                                       keyEvent->ctrlKey() ? ParagraphGranularity : LineGranularity,
                                       UserTriggered);
            return true;
        }
    }

    Editor::Command command = frame->editor().command(interpretKeyEvent(event));

    if (keyEvent->type() == PlatformEvent::RawKeyDown) {
        // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
        // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
        // (e.g. Tab that inserts a Tab character, or Enter).
        return !command.isTextInsertion() && command.execute(event);
    }

    if (command.execute(event))
        return true;

    // Don't allow text insertion for nodes that cannot edit.
    if (!frame->editor().canEdit())
        return false;

    // Don't insert null or control characters as they can result in unexpected behaviour
    if (event->charCode() < ' ')
        return false;

    // Don't insert anything if a modifier is pressed
    if (keyEvent->ctrlKey() || keyEvent->altKey())
        return false;

    return frame->editor().insertText(event->keyEvent()->text(), event);
}
int Animation::nodeCount() const
{
    Frame *frame = m_frames.at(m_currentFrame);
    return frame->nodeCount();
}
Esempio n. 4
0
static Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, NavigationPolicy policy, ShouldSendReferrer shouldSendReferrer, bool& created)
{
    ASSERT(!features.dialog || request.frameName().isEmpty());

    if (!request.frameName().isEmpty() && request.frameName() != "_blank" && policy == NavigationPolicyIgnore) {
        if (Frame* frame = lookupFrame->loader().findFrameForNavigation(request.frameName(), openerFrame->document())) {
            if (request.frameName() != "_self")
                frame->page()->focusController().setFocusedFrame(frame);
            created = false;
            return frame;
        }
    }

    // Sandboxed frames cannot open new auxiliary browsing contexts.
    if (openerFrame->document()->isSandboxed(SandboxPopups)) {
        // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
        openerFrame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked opening '" + request.resourceRequest().url().elidedString() + "' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.");
        return 0;
    }

    if (openerFrame->settings() && !openerFrame->settings()->supportsMultipleWindows()) {
        created = false;
        return openerFrame->tree().top();
    }

    Page* oldPage = openerFrame->page();
    if (!oldPage)
        return 0;

    Page* page = oldPage->chrome().client().createWindow(openerFrame, request, features, policy, shouldSendReferrer);
    if (!page)
        return 0;

    Frame* frame = page->mainFrame();

    frame->loader().forceSandboxFlags(openerFrame->document()->sandboxFlags());

    if (request.frameName() != "_blank")
        frame->tree().setName(request.frameName());

    page->chrome().setWindowFeatures(features);

    // 'x' and 'y' specify the location of the window, while 'width' and 'height'
    // specify the size of the viewport. We can only resize the window, so adjust
    // for the difference between the window size and the viewport size.

    FloatRect windowRect = page->chrome().windowRect();
    FloatSize viewportSize = page->chrome().pageRect().size();

    if (features.xSet)
        windowRect.setX(features.x);
    if (features.ySet)
        windowRect.setY(features.y);
    if (features.widthSet)
        windowRect.setWidth(features.width + (windowRect.width() - viewportSize.width()));
    if (features.heightSet)
        windowRect.setHeight(features.height + (windowRect.height() - viewportSize.height()));

    // Ensure non-NaN values, minimum size as well as being within valid screen area.
    FloatRect newWindowRect = DOMWindow::adjustWindowRect(page, windowRect);

    page->chrome().setWindowRect(newWindowRect);
    page->chrome().show(policy);

    created = true;
    return frame;
}
Esempio n. 5
0
// Traj_NcEnsemble::writeArray()
int Traj_NcEnsemble::writeArray(int set, FramePtrArray const& Farray) {
# ifdef HAS_PNETCDF
  MPI_Offset pstart_[4];
  MPI_Offset pcount_[4];
# define start_ pstart_
# define count_ pcount_
# endif
  start_[0] = ncframe_; // Frame
  start_[2] = 0;        // Atoms
  start_[3] = 0;        // XYZ
  count_[0] = 1; // Frame
  count_[1] = 1; // Ensemble
  count_[3] = 3; // XYZ
  for (int member = ensembleStart_; member != ensembleEnd_; member++) {
    //rprintf("DEBUG: Writing set %i, member %i\n", set+1, member); 
#   ifdef MPI
    Frame* frm = Farray[0];
#   else
    Frame* frm = Farray[member];
#   endif
    start_[1] = member;   // Ensemble
    count_[2] = Ncatom(); // Atoms
    // Write Coords
    //WriteIndices(); // DEBUG
    DoubleToFloat(Coord_, frm->xAddress());
#   ifdef HAS_PNETCDF
    if (ncmpi_put_vara_float_all(ncid_, coordVID_, start_, count_, Coord_))
#   else
    if (checkNCerr(nc_put_vara_float(ncid_, coordVID_, start_, count_, Coord_)))
#   endif
    {
      mprinterr("Error: Netcdf Writing coords frame %i\n", set+1);
      return 1;
    }
    // Write velocity.
    if (CoordInfo().HasVel() && frm->HasVelocity()) { // TODO: Determine V beforehand
      DoubleToFloat(Coord_, frm->vAddress());
#     ifdef HAS_PNETCDF
      if (ncmpi_put_vara_float_all(ncid_, velocityVID_, start_, count_, Coord_))
#     else
      if (checkNCerr(nc_put_vara_float(ncid_, velocityVID_, start_, count_, Coord_)) )
#     endif
      {
        mprinterr("Error: Netcdf writing velocity frame %i\n", set+1);
        return 1;
      }
    }
    // Write box
    if (cellLengthVID_ != -1) {
      count_[2] = 3;
#     ifdef HAS_PNETCDF
      if (ncmpi_put_vara_double_all(ncid_,cellLengthVID_,start_,count_,frm->bAddress()))
#     else
      if (checkNCerr(nc_put_vara_double(ncid_,cellLengthVID_,start_,count_,frm->bAddress())) )
#     endif
      {
        mprinterr("Error: Writing cell lengths frame %i.\n", set+1);
        return 1;
      }
#     ifdef HAS_PNETCDF
      if (ncmpi_put_vara_double_all(ncid_,cellAngleVID_,start_,count_,frm->bAddress()+3))
#     else
      if (checkNCerr(nc_put_vara_double(ncid_,cellAngleVID_,start_,count_,frm->bAddress()+3)))
#     endif
      {
        mprinterr("Error: Writing cell angles frame %i.\n", set+1);
        return 1;
      }
    }
    // Write temperature
    if (TempVID_!=-1) {
#     ifdef HAS_PNETCDF
      if (ncmpi_put_vara_double_all(ncid_,TempVID_,start_,count_,frm->tAddress()))
#     else
      if (checkNCerr(nc_put_vara_double(ncid_,TempVID_,start_,count_,frm->tAddress())))
#     endif
      {
        mprinterr("Error: Writing temperature frame %i.\n", set+1);
        return 1;
      }
    }
    // Write indices
    if (indicesVID_ != -1) {
      count_[2] = remd_dimension_;
#     ifdef HAS_PNETCDF
      if (ncmpi_put_vara_int_all(ncid_,indicesVID_,start_,count_,frm->iAddress()))
#     else
      if (checkNCerr(nc_put_vara_int(ncid_,indicesVID_,start_,count_,frm->iAddress())))
#     endif
      {
        mprinterr("Error: Writing indices frame %i.\n", set+1);
        return 1;
      }
    }
  }
# ifdef HAS_PNETCDF
  //ncmpi_sync(ncid_);
# else
  nc_sync(ncid_); // Necessary after every write??
# endif
  ++ncframe_;
# ifdef HAS_PNETCDF
  // DEBUG
# undef start_
# undef count_
# endif
  return 0;
}
void HTMLAppletElement::updateWidgetInternal()
{
    ASSERT(!m_isDelayingLoadEvent);
    setNeedsWidgetUpdate(false);
    // FIXME: This should ASSERT isFinishedParsingChildren() instead.
    if (!isFinishedParsingChildren())
        return;

    RenderEmbeddedObject* renderer = renderEmbeddedObject();

    Frame* frame = document().frame();
    ASSERT(frame);

    LayoutUnit contentWidth = renderer->style()->width().isFixed() ? LayoutUnit(renderer->style()->width().value()) :
        renderer->width() - renderer->borderAndPaddingWidth();
    LayoutUnit contentHeight = renderer->style()->height().isFixed() ? LayoutUnit(renderer->style()->height().value()) :
        renderer->height() - renderer->borderAndPaddingHeight();

    Vector<String> paramNames;
    Vector<String> paramValues;

    const AtomicString& codeBase = getAttribute(codebaseAttr);
    if (!codeBase.isNull()) {
        KURL codeBaseURL = document().completeURL(codeBase);
        paramNames.append("codeBase");
        paramValues.append(codeBase.string());
    }

    const AtomicString& archive = getAttribute(archiveAttr);
    if (!archive.isNull()) {
        paramNames.append("archive");
        paramValues.append(archive.string());
    }

    const AtomicString& code = getAttribute(codeAttr);
    paramNames.append("code");
    paramValues.append(code.string());

    // If the 'codebase' attribute is set, it serves as a relative root for the file that the Java
    // plugin will load. If the 'code' attribute is set, and the 'archive' is not set, then we need
    // to check the url generated by resolving 'code' against 'codebase'. If the 'archive'
    // attribute is set, then 'code' points to a class inside the archive, so we need to check the
    // url generated by resolving 'archive' against 'codebase'.
    KURL urlToCheck;
    KURL rootURL = codeBase.isNull() ? document().url() : document().completeURL(codeBase);
    if (!archive.isNull())
        urlToCheck = KURL(rootURL, archive);
    else if (!code.isNull())
        urlToCheck = KURL(rootURL, code);
    if (!canEmbedURL(urlToCheck))
        return;

    const AtomicString& name = document().isHTMLDocument() ? getNameAttribute() : getIdAttribute();
    if (!name.isNull()) {
        paramNames.append("name");
        paramValues.append(name.string());
    }

    paramNames.append("baseURL");
    KURL baseURL = document().baseURL();
    paramValues.append(baseURL.string());

    const AtomicString& mayScript = getAttribute(mayscriptAttr);
    if (!mayScript.isNull()) {
        paramNames.append("mayScript");
        paramValues.append(mayScript.string());
    }

    for (Node* child = firstChild(); child; child = child->nextSibling()) {
        if (!child->hasTagName(paramTag))
            continue;

        HTMLParamElement* param = toHTMLParamElement(child);
        if (param->name().isEmpty())
            continue;

        paramNames.append(param->name());
        paramValues.append(param->value());
    }

    RefPtr<Widget> widget;
    if (frame->loader().allowPlugins(AboutToInstantiatePlugin))
        widget = frame->loader().client()->createJavaAppletWidget(roundedIntSize(LayoutSize(contentWidth, contentHeight)), this, baseURL, paramNames, paramValues);

    if (!widget) {
        if (!renderer->showsUnavailablePluginIndicator())
            renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginMissing);
        return;
    }
    document().setContainsPlugins();
    renderer->setWidget(widget);
}
Esempio n. 7
0
bool EditorClientImpl::handleEditingKeyboardEvent(KeyboardEvent* evt)
{
    const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
    // do not treat this as text input if it's a system key event
    if (!keyEvent || keyEvent->isSystemKey())
        return false;

    Frame* frame = evt->target()->toNode()->document()->frame();
    if (!frame)
        return false;

    String commandName = interpretKeyEvent(evt);
    Editor::Command command = frame->editor()->command(commandName);

    if (keyEvent->type() == PlatformKeyboardEvent::RawKeyDown) {
        // WebKit doesn't have enough information about mode to decide how
        // commands that just insert text if executed via Editor should be treated,
        // so we leave it upon WebCore to either handle them immediately
        // (e.g. Tab that changes focus) or let a keypress event be generated
        // (e.g. Tab that inserts a Tab character, or Enter).
        if (command.isTextInsertion() || commandName.isEmpty())
            return false;
        if (command.execute(evt)) {
            if (m_webView->client())
                m_webView->client()->didExecuteCommand(WebString(commandName));
            return true;
        }
        return false;
    }

    if (command.execute(evt)) {
        if (m_webView->client())
            m_webView->client()->didExecuteCommand(WebString(commandName));
        return true;
    }

    // Here we need to filter key events.
    // On Gtk/Linux, it emits key events with ASCII text and ctrl on for ctrl-<x>.
    // In Webkit, EditorClient::handleKeyboardEvent in
    // WebKit/gtk/WebCoreSupport/EditorClientGtk.cpp drop such events.
    // On Mac, it emits key events with ASCII text and meta on for Command-<x>.
    // These key events should not emit text insert event.
    // Alt key would be used to insert alternative character, so we should let
    // through. Also note that Ctrl-Alt combination equals to AltGr key which is
    // also used to insert alternative character.
    // http://code.google.com/p/chromium/issues/detail?id=10846
    // Windows sets both alt and meta are on when "Alt" key pressed.
    // http://code.google.com/p/chromium/issues/detail?id=2215
    // Also, we should not rely on an assumption that keyboards don't
    // send ASCII characters when pressing a control key on Windows,
    // which may be configured to do it so by user.
    // See also http://en.wikipedia.org/wiki/Keyboard_Layout
    // FIXME(ukai): investigate more detail for various keyboard layout.
    if (evt->keyEvent()->text().length() == 1) {
        UChar ch = evt->keyEvent()->text()[0U];

        // Don't insert null or control characters as they can result in
        // unexpected behaviour
        if (ch < ' ')
            return false;
#if !OS(WINDOWS)
        // Don't insert ASCII character if ctrl w/o alt or meta is on.
        // On Mac, we should ignore events when meta is on (Command-<x>).
        if (ch < 0x80) {
            if (evt->keyEvent()->ctrlKey() && !evt->keyEvent()->altKey())
                return false;
#if OS(DARWIN)
            if (evt->keyEvent()->metaKey())
            return false;
#endif
        }
#endif
    }

    if (!frame->editor()->canEdit())
        return false;

    return frame->editor()->insertText(evt->keyEvent()->text(), evt);
}
Esempio n. 8
0
void
FormManager::SwitchToForm(RequestId requestId, Osp::Base::Collection::IList* pArgs)
{
	Frame* pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();
	BaseForm* pExeForm = null;

	switch (requestId)
	{
	case REQUEST_MAINFORM:
	{
		if (__pMainForm == null)
		{
			__pMainForm = new MainForm();
			__pMainForm->Initialize();
			pFrame->AddControl(*__pMainForm);
		}
		pFrame->SetCurrentForm(*__pMainForm);
		__pMainForm->Draw();
		__pMainForm->Show();
		if (__pPreviousForm != null)
		{
			if (__pPreviousForm != __pMainForm)
				pFrame->RemoveControl(*__pPreviousForm);
		}
		__pPreviousForm = __pMainForm;

		return;
	}
	break;

	case REQUEST_FACEBOOKLOGINFORM:

		pExeForm = new LoginForm();
		break;

	case REQUEST_USERPROFILEFORM:

		pExeForm = new UserProfileForm();
		break;


	case REQUEST_FRIENDSFORM:
		pExeForm = new FriendsForm();
		break;

	default:
		return;
		break;
	}

	pExeForm->Initialize();
	pFrame->AddControl(*pExeForm);
	pFrame->SetCurrentForm(*pExeForm);
	pExeForm->Draw();
	pExeForm->Show();

	if (__pPreviousForm != null)
	{
		if (__pPreviousForm != __pMainForm)
			pFrame->RemoveControl(*__pPreviousForm);
	}
	__pPreviousForm = pExeForm;

	return;
}
int main (int argc, char **argv)
{

	Config::init("cluster.cfg");
	loginit();
	Encoder *temp=CodecFactory::getStreamEncoder(1);
  av_register_all ();

  avcodec_init ();
  avcodec_register_all ();

  char *filename = argv[1];



  File file (filename);
  FormatInputStream fois (&file);
  AVFormatContext *ic = fois.getFormatContext ();

  fois.dumpFormat ();
  PacketInputStream pis (fois);
  int got_picture;

  int insize = 0, outsize = 0;




/*
  Encoder enc2 (CODEC_ID_H264);
  enc2.setWidth (format.width);
  enc2.setHeight (format.height);
  enc2.setTimeBase ((AVRational) {1, 25});
  enc2.setBitRate (4000000);
  enc2.setGopSize (250);
  enc2.setPixelFormat (PIX_FMT_YUV420P);
  enc2.open ();
*/





  Decoder * dec=new Decoder (ic->streams[0]->codec->codec_id);
  dec->setWidth (ic->streams[0]->codec->width);
  dec->setHeight (ic->streams[0]->codec->height);
  dec->setTimeBase ((AVRational) {1, 25});
  dec->setPixelFormat (ic->streams[0]->codec->pix_fmt);

//      dec.setGopSize(0);
  dec->open ();

  FrameFormat informat;
  informat.pixel_format = (PixelFormat)dec->getPixelFormat();//_pix_fmt;
  informat.height = ic->streams[0]->codec->height;
  informat.width = ic->streams[0]->codec->width;

  FrameFormat format;
  format.pixel_format = PIX_FMT_YUV420P;
  format.height = ic->streams[0]->codec->height;
  format.width = ic->streams[0]->codec->width;

  FrameConverter converter (informat,format);

//      cerr << "Decoder"<<endl;
//      Encoder enc(CODEC_ID_MPEG2VIDEO);
//      enc.max_b_frames=3;



  Encoder * enc=new Encoder(CODEC_ID_MSMPEG4V3);

//  Encoder * enc=new Encoder(CODEC_ID_H264);
//  Encoder enc (CODEC_ID_H264);
  enc->setWidth (format.width);
  enc->setHeight (format.height);
  enc->setTimeBase ((AVRational) {1, 25});
  enc->setBitRate (4000000);
  enc->setGopSize (25);
  enc->setPixelFormat (PIX_FMT_YUV420P);
//      enc.setFlag(CODEC_FLAG_PASS1);
  enc->open ();

  File fout (argv[2]);
  FormatOutputStream ffos (&fout);
  PacketOutputStream pos (&ffos);
  pos.setEncoder (*enc, 0);
  pos.init ();
//  		fois.seek(0,44289);//38978


//  FILE *logfile;
//  logfile = fopen ("stats.out", "w");
	int a=0;
	bool firstSeek=false;
  for (int i = 0;i < 1000; i++) {
    Packet p;
//    av_init_packet (p.packet);
    if(pis.readPacket (p)<0)break;
    if (p.packet->stream_index != 0)
      continue;

    if (false&&p.isKeyFrame()) {
    	cout << "!!!!!!!!!!!!INIT ENCODER - DECODER"<<endl;
      enc->close ();
	  delete enc;


//	dec->close();
//	delete dec;
//  dec=new Decoder (ic->streams[0]->codec->codec_id);
//  dec->setWidth (ic->streams[0]->codec->width);
//  dec->setHeight (ic->streams[0]->codec->height);
//  dec->setTimeBase ((AVRational) {1, 25});
//  dec->setPixelFormat (ic->streams[0]->codec->pix_fmt);
//      dec.setGopSize(0);
//	dec->open();

      enc=new Encoder(CODEC_ID_H264);
//      enc=new Encoder(CODEC_ID_MSMPEG4V3);
//  Encoder enc (CODEC_ID_H264);
	  enc->setWidth (format.width);
  	  enc->setHeight (format.height);
  	  enc->setTimeBase ((AVRational) {1, 25});
  	  enc->setBitRate (4000000);
  	  enc->setGopSize (25);
  	  enc->setPixelFormat (PIX_FMT_YUV420P);
//      enc.setFlag(CODEC_FLAG_PASS1);
  	  enc->open ();
//      enc->open ();
    }






//          enc.thread_count=1;
//          enc.max_qdiff=0;
//          enc.sample_aspect_ratio=(AVRational){1,1};
//          enc.rc_override_count=0;
//          enc.me_threshold=0;
//          enc.intra_dc_precision=0;
//          enc.strict_std_compliance=0;
//          enc.debug|=FF_DEBUG_MV;

//      enc.open();



//    cout << i << "read Packet:"<<p.packet->pts;
//    cout.flush ();
//          AVFrame * picture= avcodec_alloc_frame();
    insize += p.packet->size;
    cout << "InputPacketPts:"<<p.packet->pts;
    cout << "\tInputPacketDts:"<<p.packet->dts;
    cout << endl;
//              boost::shared_ptr<Packet> ptr(new Packet(p));
//      cout << "InputPacketSize:"<<ptr->packet->size<<endl;
//              Frame frame(enc.getPixelFormat(), enc.getWidth(), enc.getHeight());
//          unit._input_packets.push_back(ptr);
//          dec.debug|=FF_DEBUG_MV;
//          fill_yuv_image(picture, i, enc.getWidth(), enc.getHeight());

    int out_size = 0;
//          out_size = avcodec_decode_video(decc, &frame, &got_picture, p.packet->data, p.packet->size);
//          picture->pict_type=1;
//          picture->quality=dec.coded_frame->quality;

//    cout << "decode Packet";
//    cout.flush ();

    Frame tmp=dec->decode(p);
    if(tmp._buffer==0)continue;
    Frame f = converter.convert (tmp);
    cout << "FrameSize:" << f.getSize () << endl;
//    frame.pts = p.packet->pts;
    f.setPts( p.packet->dts);
//    f.setDts( p.packet->dts);

    cout << "encode Packet";
    cout.flush ();
    Packet pe = enc->encode (f);
		if(!firstSeek){
  			fois.seek(0,44289);
  			firstSeek=true;
  		}

//    if (enc.ctx->stats_out)
//      fprintf (logfile, "%s", enc.ctx->stats_out);

//          pe.packet->pts=p.packet->pts;
//          pe.packet->dts=p.packet->dts;
//          pe.packet->stream_index=0;

    cout << "write Packet";
    cout.flush ();
    pe.packet->pts=++a;
    pe.packet->dts=AV_NOPTS_VALUE;;
    
    pos.writePacket (pe);
    out_size = pe.packet->size;

//          fill_yuv_image(&f, i, enc.getWidth(), enc.getHeight());



//          picture->pts = AV_NOPTS_VALUE;//p.packet->pts;
//          frame.pts = p.packet->pts;//AV_NOPTS_VALUE;//p.packet->pts;

//          out_size = avcodec_encode_video(enc.ctx, video_outbuf, video_outbuf_size, &frame);
    outsize += out_size;
//		cout << "InputPts:"<<p.packet->pts<<"\tOutputPts:"<<pe.packet->pts<<endl;	
//    cout << "InputPacketSize:" << p.packet->size << "\tOutputPacketSize:" << out_size << "\tKeyFrame:" << enc.ctx->coded_frame->key_frame << endl;

//          cout <<"FrameHere:"<<out_size<<endl;
//          outsize+=out_size;
//          Packet pe=enc.encode(f);
//          cout << "EncPacketSize:"<<pe.packet->size<<endl;

//              av_free(picture);
  }
  cout << "InputPacketSizeAll:" << insize << "\tOutputPacketSizeAll:" <<
    outsize << endl;
//  pos.close();
  
  
//  Config::close();
/*
    av_free(video_outbuf);
	avcodec_close(cc);
	avcodec_close(decc);
	av_free(cc);
	av_free(decc);
//	av_free(decodec);
//	av_free(codec);
	av_free(picture);
	av_free(picture_buf);
*/
/*	
	FileOutputStream fos("test.unit");
	ObjectOutputStream oos(&fos);
	oos.writeObject(unit);
	fos.flush();
	cout << "Data Serailized"<<endl;
*/
  /*
     ProcessUnit unit2;   
     FileInputStream fis("test.unit");
     ObjectInputStream ois(&fis);
     ois.readObject(unit2);

     unit2.process();
   */
//      delete unit2._decoder;
//      delete unit2._encoder;


/*
	ProcessUnit unit;
//	unit._decoder=&dec;
//	unit._encoder=&enc;
	PacketInputStream pais(&fois);
//	Packet p;
//	list<boost::shared_ptr<Packet> > input_packets;

*/


/*
	for(int a=0;a<100;a++){
		pais.readPacket(p);
	
	
	}
*/
//           int len = avcodec_decode_video(c, picture, &got_picture, p.data, p.size);


//              Frame f=dec.decode(p);
//              Packet p2=enc.encode(f);
//              boost::shared_ptr<Packet> ptr(new Packet(p));
//              unit._input_packets.push_back(ptr);

//      unit.process();
/*
	FileOutputStream fos("test.unit");
	ObjectOutputStream oos(&fos);
	oos.writeObject(unit);
	fos.flush();
*/

/*	
	ProcessUnit unit2;	
	FileInputStream fis("test.unit");
	ObjectInputStream ois(&fis);
	ois.readObject(unit2);

	unit2.process();

	delete unit2._decoder;
	delete unit2._encoder;
*/
//      delete unit2._decoder;


//      Config::close();
}
static bool logCanCacheFrameDecision(Frame* frame, int indentLevel)
{
    // Only bother logging for frames that have actually loaded and have content.
    if (frame->loader()->stateMachine()->creatingInitialEmptyDocument())
        return false;
    KURL currentURL = frame->loader()->documentLoader() ? frame->loader()->documentLoader()->url() : KURL();
    if (currentURL.isEmpty())
        return false;
    
    PCLOG("+---");
    KURL newURL = frame->loader()->provisionalDocumentLoader() ? frame->loader()->provisionalDocumentLoader()->url() : KURL();
    if (!newURL.isEmpty())
        PCLOG(" Determining if frame can be cached navigating from (", currentURL.string(), ") to (", newURL.string(), "):");
    else
        PCLOG(" Determining if subframe with URL (", currentURL.string(), ") can be cached:");
    
    bool cannotCache = false;
    
    do {
        if (!frame->loader()->documentLoader()) {
            PCLOG("   -There is no DocumentLoader object");
            cannotCache = true;
            break;
        }
        if (!frame->loader()->documentLoader()->mainDocumentError().isNull()) {
            PCLOG("   -Main document has an error");
            if (frame->loader()->documentLoader()->mainDocumentError().isCancellation() && frame->loader()->documentLoader()->subresourceLoadersArePageCacheAcceptable())
                PCLOG("    -But, it was a cancellation and all loaders during the cancel were loading images.");
            else
                cannotCache = true;
        }
        if (frame->loader()->subframeLoader()->containsPlugins()) {
            PCLOG("   -Frame contains plugins");
            // iOS allows pages with plug-ins to enter the page cache.
            PCLOG("    -But, iOS can handle plugins.");
        }
        if (frame->document()->url().protocolIs("https")) {
            PCLOG("   -Frame is HTTPS");
            cannotCache = true;
        }
        if (frame->domWindow() && frame->domWindow()->hasEventListeners(eventNames().unloadEvent)) {
            PCLOG("   -Frame has an unload event listener");
            // iOS allows pages with unload event listeners to enter the page cache.
            PCLOG("    -BUT iOS allows these pages to be cached.");
        }
#if ENABLE(DATABASE)
        if (frame->document()->hasOpenDatabases()) {
            PCLOG("   -Frame has open database handles");
            cannotCache = true;
        }
#endif
#if ENABLE(SHARED_WORKERS)
        if (SharedWorkerRepository::hasSharedWorkers(frame->document())) {
            PCLOG("   -Frame has associated SharedWorkers");
            cannotCache = true;
        }
#endif
        if (frame->document()->usingGeolocation()) {
            PCLOG("   -Frame uses Geolocation");
            // iOS allows pages geolocation to enter the page cache.
            PCLOG("    -BUT iOS allows these pages to be cached.");
        }
        if (!frame->loader()->history()->currentItem()) {
            PCLOG("   -No current history item");
            cannotCache = true;
        }
        if (frame->loader()->quickRedirectComing()) {
            PCLOG("   -Quick redirect is coming");
            cannotCache = true;
        }
        if (frame->loader()->documentLoader()->isLoadingInAPISense()) {
            PCLOG("   -DocumentLoader is still loading in API sense");
            cannotCache = true;
        }
        if (frame->loader()->documentLoader()->isStopping()) {
            PCLOG("   -DocumentLoader is in the middle of stopping");
            cannotCache = true;
        }
        if (!frame->document()->canSuspendActiveDOMObjects()) {
            PCLOG("   -The document cannot suspect its active DOM Objects");
            cannotCache = true;
        }
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
        if (!frame->loader()->documentLoader()->applicationCacheHost()->canCacheInPageCache()) {
            PCLOG("   -The DocumentLoader uses an application cache");
            cannotCache = true;
        }
#endif
        if (!frame->loader()->client()->canCachePage()) {
            PCLOG("   -The client says this frame cannot be cached");
            cannotCache = true; 
        }
    } while (false);
    
    for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
        if (!logCanCacheFrameDecision(child, indentLevel + 1))
            cannotCache = true;
    
    PCLOG(cannotCache ? " Frame CANNOT be cached" : " Frame CAN be cached");
    PCLOG("+---");
    
    return !cannotCache;
}
Esempio n. 11
0
void CachedFrameBase::restore()
{
    ASSERT(m_document->view() == m_view);

    Frame* frame = m_view->frame();
    m_cachedFrameScriptData->restore(frame);

#if ENABLE(SVG)
    if (m_document->svgExtensions())
        m_document->accessSVGExtensions()->unpauseAnimations();
#endif

    frame->animation()->resumeAnimationsForDocument(m_document.get());
    frame->eventHandler()->setMousePressNode(m_mousePressNode.get());
    m_document->resumeActiveDOMObjects();
    m_document->resumeScriptedAnimationControllerCallbacks();

    // It is necessary to update any platform script objects after restoring the
    // cached page.
    frame->script()->updatePlatformScriptObjects();

    frame->loader()->client()->didRestoreFromPageCache();

    // Reconstruct the FrameTree
    for (unsigned i = 0; i < m_childFrames.size(); ++i)
        frame->tree()->appendChild(m_childFrames[i]->view()->frame());

    // Open the child CachedFrames in their respective FrameLoaders.
    for (unsigned i = 0; i < m_childFrames.size(); ++i)
        m_childFrames[i]->open();

    m_document->enqueuePageshowEvent(PageshowEventPersisted);
    
    HistoryItem* historyItem = frame->loader()->history()->currentItem();
    m_document->enqueuePopstateEvent(historyItem && historyItem->stateObject() ? historyItem->stateObject() : SerializedScriptValue::nullValue());
    
#if ENABLE(TOUCH_EVENTS)
    if (m_document->hasListenerType(Document::TOUCH_LISTENER))
        m_document->page()->chrome()->client()->needTouchEvents(true);
#endif
    // CAPPFIX_WEB_NAMEDITEM_HISTORY_NAV : recover NamedItem for history navigation in case of HTMLDocument.
    Document* document = m_document.get();
    if (document && document->isHTMLDocument() == true) {
        HTMLDocument* htmldocument = static_cast<HTMLDocument*>(document);
        RefPtr<HTMLCollection> items = document->all();;
        Node* item;
        for (unsigned i = 0; i < items->length(); i++) {
            item = items->item(i);
            if (!item->isElementNode())
                continue;
            Element* e = static_cast<Element*>(item);
            if (e->hasLocalName(HTMLNames::imgTag) || e->hasLocalName(HTMLNames::formTag) || e->hasLocalName(HTMLNames::objectTag)
                || e->hasLocalName(HTMLNames::embedTag) || e->hasLocalName(HTMLNames::appletTag)) {
                const AtomicString &name = e->getAttribute(HTMLNames::nameAttr);
                if (name != nullAtom)
                    htmldocument->addNamedItem(name);
            }
        }
    }
    // CAPPFIX_WEB_NAMEDITEM_HISTORY_NAV_END
    m_document->documentDidBecomeActive();
}
Esempio n. 12
0
JSValue JSDOMWindow::showModalDialog(ExecState* exec, const ArgList& args)
{
    Frame* frame = impl()->frame();
    if (!frame)
        return jsUndefined();
    Frame* lexicalFrame = toLexicalFrame(exec);
    if (!lexicalFrame)
        return jsUndefined();
    Frame* dynamicFrame = toDynamicFrame(exec);
    if (!dynamicFrame)
        return jsUndefined();

    if (!DOMWindow::canShowModalDialogNow(frame) || !DOMWindow::allowPopUp(dynamicFrame))
        return jsUndefined();

    String url = valueToStringWithUndefinedOrNullCheck(exec, args.at(0));
    JSValue dialogArgs = args.at(1);
    String featureArgs = valueToStringWithUndefinedOrNullCheck(exec, args.at(2));

    HashMap<String, String> features;
    DOMWindow::parseModalDialogFeatures(featureArgs, features);

    const bool trusted = false;

    // The following features from Microsoft's documentation are not implemented:
    // - default font settings
    // - width, height, left, and top specified in units other than "px"
    // - edge (sunken or raised, default is raised)
    // - dialogHide: trusted && boolFeature(features, "dialoghide"), makes dialog hide when you print
    // - help: boolFeature(features, "help", true), makes help icon appear in dialog (what does it do on Windows?)
    // - unadorned: trusted && boolFeature(features, "unadorned");

    FloatRect screenRect = screenAvailableRect(frame->view());

    WindowFeatures wargs;
    wargs.width = WindowFeatures::floatFeature(features, "dialogwidth", 100, screenRect.width(), 620); // default here came from frame size of dialog in MacIE
    wargs.widthSet = true;
    wargs.height = WindowFeatures::floatFeature(features, "dialogheight", 100, screenRect.height(), 450); // default here came from frame size of dialog in MacIE
    wargs.heightSet = true;

    wargs.x = WindowFeatures::floatFeature(features, "dialogleft", screenRect.x(), screenRect.right() - wargs.width, -1);
    wargs.xSet = wargs.x > 0;
    wargs.y = WindowFeatures::floatFeature(features, "dialogtop", screenRect.y(), screenRect.bottom() - wargs.height, -1);
    wargs.ySet = wargs.y > 0;

    if (WindowFeatures::boolFeature(features, "center", true)) {
        if (!wargs.xSet) {
            wargs.x = screenRect.x() + (screenRect.width() - wargs.width) / 2;
            wargs.xSet = true;
        }
        if (!wargs.ySet) {
            wargs.y = screenRect.y() + (screenRect.height() - wargs.height) / 2;
            wargs.ySet = true;
        }
    }

    wargs.dialog = true;
    wargs.resizable = WindowFeatures::boolFeature(features, "resizable");
    wargs.scrollbarsVisible = WindowFeatures::boolFeature(features, "scroll", true);
    wargs.statusBarVisible = WindowFeatures::boolFeature(features, "status", !trusted);
    wargs.menuBarVisible = false;
    wargs.toolBarVisible = false;
    wargs.locationBarVisible = false;
    wargs.fullscreen = false;

    Frame* dialogFrame = createWindow(exec, lexicalFrame, dynamicFrame, frame, url, "", wargs, dialogArgs);
    if (!dialogFrame)
        return jsUndefined();

    JSDOMWindow* dialogWindow = toJSDOMWindow(dialogFrame);
    dialogFrame->page()->chrome()->runModal();

    return dialogWindow->getDirect(Identifier(exec, "returnValue"));
}
Esempio n. 13
0
JSValue JSDOMWindow::open(ExecState* exec, const ArgList& args)
{
    Frame* frame = impl()->frame();
    if (!frame)
        return jsUndefined();
    Frame* lexicalFrame = toLexicalFrame(exec);
    if (!lexicalFrame)
        return jsUndefined();
    Frame* dynamicFrame = toDynamicFrame(exec);
    if (!dynamicFrame)
        return jsUndefined();

    Page* page = frame->page();

    String urlString = valueToStringWithUndefinedOrNullCheck(exec, args.at(0));
    AtomicString frameName = args.at(1).isUndefinedOrNull() ? "_blank" : AtomicString(args.at(1).toString(exec));

    // Because FrameTree::find() returns true for empty strings, we must check for empty framenames.
    // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
    if (!DOMWindow::allowPopUp(dynamicFrame) && (frameName.isEmpty() || !frame->tree()->find(frameName)))
        return jsUndefined();

    // Get the target frame for the special cases of _top and _parent.  In those
    // cases, we can schedule a location change right now and return early.
    bool topOrParent = false;
    if (frameName == "_top") {
        frame = frame->tree()->top();
        topOrParent = true;
    } else if (frameName == "_parent") {
        if (Frame* parent = frame->tree()->parent())
            frame = parent;
        topOrParent = true;
    }
    if (topOrParent) {
        if (!shouldAllowNavigation(exec, frame))
            return jsUndefined();

        String completedURL;
        if (!urlString.isEmpty())
            completedURL = completeURL(exec, urlString).string();

        const JSDOMWindow* targetedWindow = toJSDOMWindow(frame);
        if (!completedURL.isEmpty() && (!protocolIsJavaScript(completedURL) || (targetedWindow && targetedWindow->allowsAccessFrom(exec)))) {
            bool userGesture = processingUserGesture(exec);

            // For whatever reason, Firefox uses the dynamicGlobalObject to
            // determine the outgoingReferrer.  We replicate that behavior
            // here.
            String referrer = dynamicFrame->loader()->outgoingReferrer();

            frame->loader()->scheduleLocationChange(completedURL, referrer, !lexicalFrame->script()->anyPageIsProcessingUserGesture(), false, userGesture);
        }
        return toJS(exec, frame->domWindow());
    }

    // In the case of a named frame or a new window, we'll use the createWindow() helper
    WindowFeatures windowFeatures(valueToStringWithUndefinedOrNullCheck(exec, args.at(2)));
    FloatRect windowRect(windowFeatures.xSet ? windowFeatures.x : 0, windowFeatures.ySet ? windowFeatures.y : 0,
                         windowFeatures.widthSet ? windowFeatures.width : 0, windowFeatures.heightSet ? windowFeatures.height : 0);
    DOMWindow::adjustWindowRect(screenAvailableRect(page ? page->mainFrame()->view() : 0), windowRect, windowRect);

    windowFeatures.x = windowRect.x();
    windowFeatures.y = windowRect.y();
    windowFeatures.height = windowRect.height();
    windowFeatures.width = windowRect.width();

    frame = createWindow(exec, lexicalFrame, dynamicFrame, frame, urlString, frameName, windowFeatures, JSValue());

    if (!frame)
        return jsUndefined();

    return toJS(exec, frame->domWindow());
}
Esempio n. 14
0
void MainResourceLoader::willSendRequest(ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
{
    // Note that there are no asserts here as there are for the other callbacks. This is due to the
    // fact that this "callback" is sent when starting every load, and the state of callback
    // deferrals plays less of a part in this function in preventing the bad behavior deferring 
    // callbacks is meant to prevent.
    ASSERT(!newRequest.isNull());

    // The additional processing can do anything including possibly removing the last
    // reference to this object; one example of this is 3266216.
    RefPtr<MainResourceLoader> protect(this);

    if (!frameLoader()->checkIfFormActionAllowedByCSP(newRequest.url())) {
        cancel();
        return;
    }

    ASSERT(documentLoader()->timing()->fetchStart());
    if (!redirectResponse.isNull()) {
        // If the redirecting url is not allowed to display content from the target origin,
        // then block the redirect.
        RefPtr<SecurityOrigin> redirectingOrigin = SecurityOrigin::create(redirectResponse.url());
        if (!redirectingOrigin->canDisplay(newRequest.url())) {
            FrameLoader::reportLocalLoadFailed(m_documentLoader->frame(), newRequest.url().string());
            cancel();
            return;
        }
        documentLoader()->timing()->addRedirect(redirectResponse.url(), newRequest.url());
    }

    // Update cookie policy base URL as URL changes, except for subframes, which use the
    // URL of the main frame which doesn't change when we redirect.
    if (frameLoader()->isLoadingMainFrame())
        newRequest.setFirstPartyForCookies(newRequest.url());

    // If we're fielding a redirect in response to a POST, force a load from origin, since
    // this is a common site technique to return to a page viewing some data that the POST
    // just modified.
    // Also, POST requests always load from origin, but this does not affect subresources.
    if (newRequest.cachePolicy() == UseProtocolCachePolicy && isPostOrRedirectAfterPost(newRequest, redirectResponse))
        newRequest.setCachePolicy(ReloadIgnoringCacheData);

    Frame* top = m_documentLoader->frame()->tree()->top();
    if (top != m_documentLoader->frame()) {
        if (!frameLoader()->mixedContentChecker()->canDisplayInsecureContent(top->document()->securityOrigin(), newRequest.url())) {
            cancel();
            return;
        }
    }

    // Don't set this on the first request. It is set when the main load was started.
    m_documentLoader->setRequest(newRequest);

    if (!redirectResponse.isNull()) {
        // We checked application cache for initial URL, now we need to check it for redirected one.
        ASSERT(!m_substituteData.isValid());
        documentLoader()->applicationCacheHost()->maybeLoadMainResourceForRedirect(newRequest, m_substituteData);
        if (m_substituteData.isValid())
            m_identifierForLoadWithoutResourceLoader = identifier();
    }

    // FIXME: Ideally we'd stop the I/O until we hear back from the navigation policy delegate
    // listener. But there's no way to do that in practice. So instead we cancel later if the
    // listener tells us to. In practice that means the navigation policy needs to be decided
    // synchronously for these redirect cases.
    if (!redirectResponse.isNull()) {
        ref(); // balanced by deref in continueAfterNavigationPolicy
        frameLoader()->policyChecker()->checkNavigationPolicy(newRequest, callContinueAfterNavigationPolicy, this);
    }
}
Esempio n. 15
0
JSValue* JSSVGViewElement::getValueProperty(ExecState* exec, int token) const
{
    switch (token) {
    case ViewTargetAttrNum: {
        SVGViewElement* imp = static_cast<SVGViewElement*>(impl());

        return toJS(exec, WTF::getPtr(imp->viewTarget()));
    }
    case ExternalResourcesRequiredAttrNum: {
        SVGViewElement* imp = static_cast<SVGViewElement*>(impl());

        ASSERT(exec && exec->dynamicInterpreter());

        RefPtr<SVGAnimatedBoolean> obj = imp->externalResourcesRequiredAnimated();
        Frame* activeFrame = static_cast<ScriptInterpreter*>(exec->dynamicInterpreter())->frame();
        if (activeFrame) {
            SVGDocumentExtensions* extensions = (activeFrame->document() ? activeFrame->document()->accessSVGExtensions() : 0);
            if (extensions) {
                if (extensions->hasGenericContext<SVGAnimatedBoolean>(obj.get()))
                    ASSERT(extensions->genericContext<SVGAnimatedBoolean>(obj.get()) == imp);
                else
                    extensions->setGenericContext<SVGAnimatedBoolean>(obj.get(), imp);
            }
        }

        return toJS(exec, obj.get());
    }
    case ViewBoxAttrNum: {
        SVGViewElement* imp = static_cast<SVGViewElement*>(impl());

        ASSERT(exec && exec->dynamicInterpreter());

        RefPtr<SVGAnimatedRect> obj = imp->viewBoxAnimated();
        Frame* activeFrame = static_cast<ScriptInterpreter*>(exec->dynamicInterpreter())->frame();
        if (activeFrame) {
            SVGDocumentExtensions* extensions = (activeFrame->document() ? activeFrame->document()->accessSVGExtensions() : 0);
            if (extensions) {
                if (extensions->hasGenericContext<SVGAnimatedRect>(obj.get()))
                    ASSERT(extensions->genericContext<SVGAnimatedRect>(obj.get()) == imp);
                else
                    extensions->setGenericContext<SVGAnimatedRect>(obj.get(), imp);
            }
        }

        return toJS(exec, obj.get());
    }
    case PreserveAspectRatioAttrNum: {
        SVGViewElement* imp = static_cast<SVGViewElement*>(impl());

        ASSERT(exec && exec->dynamicInterpreter());

        RefPtr<SVGAnimatedPreserveAspectRatio> obj = imp->preserveAspectRatioAnimated();
        Frame* activeFrame = static_cast<ScriptInterpreter*>(exec->dynamicInterpreter())->frame();
        if (activeFrame) {
            SVGDocumentExtensions* extensions = (activeFrame->document() ? activeFrame->document()->accessSVGExtensions() : 0);
            if (extensions) {
                if (extensions->hasGenericContext<SVGAnimatedPreserveAspectRatio>(obj.get()))
                    ASSERT(extensions->genericContext<SVGAnimatedPreserveAspectRatio>(obj.get()) == imp);
                else
                    extensions->setGenericContext<SVGAnimatedPreserveAspectRatio>(obj.get(), imp);
            }
        }

        return toJS(exec, obj.get());
    }
    case ZoomAndPanAttrNum: {
        SVGViewElement* imp = static_cast<SVGViewElement*>(impl());

        return jsNumber(imp->zoomAndPan());
    }
    }
    return 0;
}
Esempio n. 16
0
v8::Handle<v8::Value> V8AudioContext::constructorCallback(const v8::Arguments& args)
{
    INC_STATS("DOM.AudioContext.Contructor");

    if (!args.IsConstructCall())
        return throwTypeError("AudioContext constructor cannot be called as a function.", args.GetIsolate());

    if (ConstructorMode::current() == ConstructorMode::WrapExistingObject)
        return args.Holder();

    Frame* frame = currentFrame(BindingState::instance());
    if (!frame)
        return throwError(ReferenceError, "AudioContext constructor associated frame is unavailable", args.GetIsolate());

    Document* document = frame->document();
    if (!document)
        return throwError(ReferenceError, "AudioContext constructor associated document is unavailable", args.GetIsolate());

    RefPtr<AudioContext> audioContext;
    
    if (!args.Length()) {
        // Constructor for default AudioContext which talks to audio hardware.
        ExceptionCode ec = 0;
        audioContext = AudioContext::create(document, ec);
        if (ec)
            return setDOMException(ec, args.GetIsolate());
        if (!audioContext.get())
            return throwError(SyntaxError, "audio resources unavailable for AudioContext construction", args.GetIsolate());
    } else {
        // Constructor for offline (render-target) AudioContext which renders into an AudioBuffer.
        // new AudioContext(in unsigned long numberOfChannels, in unsigned long numberOfFrames, in float sampleRate);
        if (args.Length() < 3)
            return throwNotEnoughArgumentsError(args.GetIsolate());

        bool ok = false;

        int32_t numberOfChannels = toInt32(args[0], ok);
        if (!ok || numberOfChannels <= 0 || numberOfChannels > 10)
            return throwError(SyntaxError, "Invalid number of channels", args.GetIsolate());

        int32_t numberOfFrames = toInt32(args[1], ok);
        if (!ok || numberOfFrames <= 0)
            return throwError(SyntaxError, "Invalid number of frames", args.GetIsolate());

        float sampleRate = toFloat(args[2]);
        if (sampleRate <= 0)
            return throwError(SyntaxError, "Invalid sample rate", args.GetIsolate());

        ExceptionCode ec = 0;
        audioContext = AudioContext::createOfflineContext(document, numberOfChannels, numberOfFrames, sampleRate, ec);
        if (ec)
            return setDOMException(ec, args.GetIsolate());
    }

    if (!audioContext.get())
        return throwError(SyntaxError, "Error creating AudioContext", args.GetIsolate());
    
    // Transform the holder into a wrapper object for the audio context.
    V8DOMWrapper::setDOMWrapper(args.Holder(), &info, audioContext.get());
    audioContext->ref();
    
    return args.Holder();
}
Esempio n. 17
0
bool Dyninst::Stackwalker::frame_addr_cmp(const Frame &a, const Frame &b)
{
   return a.getRA() < b.getRA();
}
Esempio n. 18
0
void EditorClientQt::handleKeyboardEvent(KeyboardEvent* event)
{
    Frame* frame = m_page->page->focusController()->focusedOrMainFrame();
    if (!frame)
        return;

    const PlatformKeyboardEvent* kevent = event->keyEvent();
    if (!kevent || kevent->type() == PlatformEvent::KeyUp)
        return;

    Node* start = frame->selection()->start().containerNode();
    if (!start)
        return;

    // FIXME: refactor all of this to use Actions or something like them
    if (start->isContentEditable()) {
        bool doSpatialNavigation = false;
        if (isSpatialNavigationEnabled(frame)) {
            if (!kevent->modifiers()) {
                switch (kevent->windowsVirtualKeyCode()) {
                case VK_LEFT:
                case VK_RIGHT:
                case VK_UP:
                case VK_DOWN:
                    doSpatialNavigation = true;
                }
            }
        }

#ifndef QT_NO_SHORTCUT
        const char* cmd = m_page->editorCommandForKeyEvent(kevent->qtEvent());
        if (cmd && !doSpatialNavigation) {
            // WebKit doesn't have enough information about mode to decide how commands that just insert text if executed via Editor should be treated,
            // so we leave it upon WebCore to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
            // (e.g. Tab that inserts a Tab character, or Enter).
            if (frame->editor().command(cmd).isTextInsertion()
                && kevent->type() == PlatformEvent::RawKeyDown)
                return;

            m_page->triggerActionForKeyEvent(kevent->qtEvent());
            event->setDefaultHandled();
            return;
        }
#endif // QT_NO_SHORTCUT
        {
            String commandName = editorCommandForKeyDownEvent(event);
            if (!commandName.isEmpty()) {
                if (frame->editor().command(commandName).execute()) // Event handled.
                    event->setDefaultHandled();
                return;
            }

            if (kevent->windowsVirtualKeyCode() == VK_TAB) {
                // Do not handle TAB text insertion here.
                return;
            }

            // Text insertion.
            bool shouldInsertText = false;
            if (kevent->type() != PlatformEvent::KeyDown && !kevent->text().isEmpty()) {

                if (kevent->ctrlKey()) {
                    if (kevent->altKey())
                        shouldInsertText = true;
                } else {
#ifndef Q_WS_MAC
                // We need to exclude checking for Alt because it is just a different Shift
                if (!kevent->altKey())
#endif
                    shouldInsertText = true;

                }
            }

            if (shouldInsertText) {
                frame->editor().insertText(kevent->text(), event);
                event->setDefaultHandled();
                return;
            }
        }

        // Event not handled.
        return;
    }

    // Non editable content.
    if (m_page->page->settings()->caretBrowsingEnabled()) {
        switch (kevent->windowsVirtualKeyCode()) {
        case VK_LEFT:
        case VK_RIGHT:
        case VK_UP:
        case VK_DOWN:
        case VK_HOME:
        case VK_END:
            {
#ifndef QT_NO_SHORTCUT
                m_page->triggerActionForKeyEvent(kevent->qtEvent());
                event->setDefaultHandled();
#endif
                return;
            }
        case VK_PRIOR: // PageUp
        case VK_NEXT: // PageDown
            {
                String commandName = editorCommandForKeyDownEvent(event);
                ASSERT(!commandName.isEmpty());
                frame->editor().command(commandName).execute();
                event->setDefaultHandled();
                return;
            }
        }
    }

#ifndef QT_NO_SHORTCUT
    if (kevent->qtEvent() == QKeySequence::Copy) {
        m_page->triggerCopyAction();
        event->setDefaultHandled();
        return;
    }
#endif // QT_NO_SHORTCUT
}
Esempio n. 19
0
static Frame* createWindow(Frame* openerFrame,
                           const String& url,
                           const String& frameName,
                           const WindowFeatures& windowFeatures,
                           v8::Local<v8::Value> dialogArgs)
{
    Frame* activeFrame = V8Proxy::retrieveFrameForEnteredContext();

    ResourceRequest request;
    if (activeFrame)
        request.setHTTPReferrer(activeFrame->loader()->outgoingReferrer());
    FrameLoadRequest frameRequest(request, frameName);

    // FIXME: It's much better for client API if a new window starts with a URL,
    // here where we know what URL we are going to open. Unfortunately, this
    // code passes the empty string for the URL, but there's a reason for that.
    // Before loading we have to set up the opener, openedByDOM,
    // and dialogArguments values. Also, to decide whether to use the URL
    // we currently do an allowsAccessFrom call using the window we create,
    // which can't be done before creating it. We'd have to resolve all those
    // issues to pass the URL instead of "".

    bool created;
    // We pass in the opener frame here so it can be used for looking up the
    // frame name, in case the active frame is different from the opener frame,
    // and the name references a frame relative to the opener frame, for example
    // "_self" or "_parent".
    Frame* newFrame = activeFrame->loader()->createWindow(openerFrame->loader(), frameRequest, windowFeatures, created);
    if (!newFrame)
        return 0;

    newFrame->loader()->setOpener(openerFrame);
    newFrame->loader()->setOpenedByDOM();

    // Set dialog arguments on the global object of the new frame.
    if (!dialogArgs.IsEmpty()) {
        v8::Local<v8::Context> context = V8Proxy::GetContext(newFrame);
        if (!context.IsEmpty()) {
            v8::Context::Scope scope(context);
            context->Global()->Set(v8::String::New("dialogArguments"), dialogArgs);
        }
    }

    if (!parseURL(url).startsWith("javascript:", false)
        || ScriptController::isSafeScript(newFrame)) {
        KURL completedUrl =
            url.isEmpty() ? KURL("") : activeFrame->document()->completeURL(url);
        bool userGesture = activeFrame->script()->processingUserGesture();

        if (created)
            newFrame->loader()->changeLocation(completedUrl, activeFrame->loader()->outgoingReferrer(), false, false, userGesture);
        else if (!url.isEmpty())
            newFrame->loader()->scheduleLocationChange(completedUrl.string(), activeFrame->loader()->outgoingReferrer(), false, userGesture);
    }

    return newFrame;
}
Esempio n. 20
0
FrameTree::~FrameTree()
{
    for (Frame* child = firstChild(); child; child = child->tree()->nextSibling())
        child->setView(0);
}
Esempio n. 21
0
void AnimationControllerPrivate::updateRenderingDispatcherFired(Timer<AnimationControllerPrivate>*)
{
    if (m_frame && m_frame->document()) {
        m_frame->document()->updateRendering();
    }
}
Esempio n. 22
0
void JSEventListener::handleEvent(ScriptExecutionContext* scriptExecutionContext, Event* event)
{
    ASSERT(scriptExecutionContext);
    if (!scriptExecutionContext || scriptExecutionContext->isJSExecutionForbidden())
        return;

    JSLock lock(SilenceAssertionsOnly);

    JSObject* jsFunction = this->jsFunction(scriptExecutionContext);
    if (!jsFunction)
        return;

    JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(scriptExecutionContext, m_isolatedWorld.get());
    if (!globalObject)
        return;

    if (scriptExecutionContext->isDocument()) {
        JSDOMWindow* window = static_cast<JSDOMWindow*>(globalObject);
        Frame* frame = window->impl()->frame();
        if (!frame)
            return;
        // The window must still be active in its frame. See <https://bugs.webkit.org/show_bug.cgi?id=21921>.
        // FIXME: A better fix for this may be to change DOMWindow::frame() to not return a frame the detached window used to be in.
        if (frame->domWindow() != window->impl())
            return;
        // FIXME: Is this check needed for other contexts?
        ScriptController* script = frame->script();
        if (!script->canExecuteScripts(AboutToExecuteScript) || script->isPaused())
            return;
    }

    ExecState* exec = globalObject->globalExec();
    JSValue handleEventFunction = jsFunction->get(exec, Identifier(exec, "handleEvent"));

    CallData callData;
    CallType callType = getCallData(handleEventFunction, callData);
    if (callType == CallTypeNone) {
        handleEventFunction = JSValue();
        callType = jsFunction->getCallData(callData);
    }

    if (callType != CallTypeNone) {
        RefPtr<JSEventListener> protect(this);

        MarkedArgumentBuffer args;
        args.append(toJS(exec, globalObject, event));

        Event* savedEvent = globalObject->currentEvent();
        globalObject->setCurrentEvent(event);

        JSGlobalData& globalData = globalObject->globalData();
        DynamicGlobalObjectScope globalObjectScope(globalData, globalData.dynamicGlobalObject ? globalData.dynamicGlobalObject : globalObject);

        globalData.timeoutChecker.start();
        JSValue retval;
        if (handleEventFunction) {
            retval = scriptExecutionContext->isDocument()
                ? JSMainThreadExecState::call(exec, handleEventFunction, callType, callData, jsFunction, args)
                : JSC::call(exec, handleEventFunction, callType, callData, jsFunction, args);
        } else {
            JSValue currentTarget = toJS(exec, globalObject, event->currentTarget());
            retval = scriptExecutionContext->isDocument()
                ? JSMainThreadExecState::call(exec, jsFunction, callType, callData, currentTarget, args)
                : JSC::call(exec, jsFunction, callType, callData, currentTarget, args);
        }
        globalData.timeoutChecker.stop();

        globalObject->setCurrentEvent(savedEvent);

#if ENABLE(WORKERS)
        if (scriptExecutionContext->isWorkerContext()) {
            bool terminatorCausedException = (exec->hadException() && isTerminatedExecutionException(exec->exception()));
            if (terminatorCausedException || globalData.terminator.shouldTerminate())
                static_cast<WorkerContext*>(scriptExecutionContext)->script()->forbidExecution();
        }
#endif

        if (exec->hadException()) {
            event->target()->uncaughtExceptionInEventHandler();
            reportCurrentException(exec);
        } else {
            if (!retval.isUndefinedOrNull() && event->storesResultAsString())
                event->storeResult(ustringToString(retval.toString(exec)));
            if (m_isAttribute) {
                bool retvalbool;
                if (retval.getBoolean(retvalbool) && !retvalbool)
                    event->preventDefault();
            }
        }
    }
}
Esempio n. 23
0
void HTMLFormElement::submit(Event* event, bool activateSubmitButton)
{
    FrameView* view = document()->view();
    Frame* frame = document()->frame();
    if (!view || !frame)
        return;

    if (m_insubmit) {
        m_doingsubmit = true;
        return;
    }

    m_insubmit = true;

    HTMLFormControlElement* firstSuccessfulSubmitButton = 0;
    bool needButtonActivation = activateSubmitButton; // do we need to activate a submit button?
    
    frame->loader()->clearRecordedFormValues();
    frame->loader()->setFormAboutToBeSubmitted(this);
    for (unsigned i = 0; i < formElements.size(); ++i) {
        HTMLFormControlElement* control = formElements[i];
        if (control->hasLocalName(inputTag)) {
            HTMLInputElement* input = static_cast<HTMLInputElement*>(control);
            if (input->isTextField()) {
                frame->loader()->recordFormValue(input->name(), input->value());
                if (input->isSearchField())
                    input->addSearchResult();
            }
        }
        if (needButtonActivation) {
            if (control->isActivatedSubmit())
                needButtonActivation = false;
            else if (firstSuccessfulSubmitButton == 0 && control->isSuccessfulSubmitButton())
                firstSuccessfulSubmitButton = control;
        }
    }

    if (needButtonActivation && firstSuccessfulSubmitButton)
        firstSuccessfulSubmitButton->setActivatedSubmit(true);
    
    if (m_url.isEmpty())
        m_url = document()->url().string();

    if (m_formDataBuilder.isPostMethod()) {
        if (m_formDataBuilder.isMultiPartForm() && isMailtoForm()) {
            setEnctype("application/x-www-form-urlencoded");
            ASSERT(!m_formDataBuilder.isMultiPartForm());
        }

        if (!m_formDataBuilder.isMultiPartForm()) {
            RefPtr<FormData> data = createFormData(CString());
            if (isMailtoForm()) {
                String body = data->flattenToString();
                if (equalIgnoringCase(m_formDataBuilder.encodingType(), "text/plain")) {
                    // Convention seems to be to decode, and s/&/\r\n/. Also, spaces are encoded as %20.
                    body = decodeURLEscapeSequences(body.replace('&', "\r\n").replace('+', ' ') + "\r\n");
                }
                Vector<char> bodyData;
                bodyData.append("body=", 5);
                FormDataBuilder::encodeStringAsFormData(bodyData, body.utf8());
                data = FormData::create(String(bodyData.data(), bodyData.size()).replace('+', "%20").latin1());
            }
            frame->loader()->submitForm("POST", m_url, data, m_target, m_formDataBuilder.encodingType(), String(), event);
        } else {
            Vector<char> boundary = m_formDataBuilder.generateUniqueBoundaryString();
            frame->loader()->submitForm("POST", m_url, createFormData(boundary.data()), m_target, m_formDataBuilder.encodingType(), boundary.data(), event);
        }
    } else {
        m_formDataBuilder.setIsMultiPartForm(false);
        frame->loader()->submitForm("GET", m_url, createFormData(CString()), m_target, String(), String(), event);
    }

    if (needButtonActivation && firstSuccessfulSubmitButton)
        firstSuccessfulSubmitButton->setActivatedSubmit(false);
    
    m_doingsubmit = m_insubmit = false;
}
void ContextMenuController::contextMenuItemSelected(ContextMenuItem* item)
{
    ASSERT(item->type() == ActionType || item->type() == CheckableActionType);

    if (item->action() >= ContextMenuItemBaseApplicationTag) {
        m_client->contextMenuItemSelected(item, m_contextMenu.get());
        return;
    }

    HitTestResult result = m_contextMenu->hitTestResult();
    Frame* frame = result.innerNonSharedNode()->document()->frame();
    if (!frame)
        return;
    
    switch (item->action()) {
        case ContextMenuItemTagOpenLinkInNewWindow: 
            openNewWindow(result.absoluteLinkURL(), frame);
            break;
        case ContextMenuItemTagDownloadLinkToDisk:
            // FIXME: Some day we should be able to do this from within WebCore.
            m_client->downloadURL(result.absoluteLinkURL());
            break;
        case ContextMenuItemTagCopyLinkToClipboard:
            frame->editor()->copyURL(result.absoluteLinkURL(), result.textContent());
            break;
        case ContextMenuItemTagOpenImageInNewWindow:
            openNewWindow(result.absoluteImageURL(), frame);
            break;
        case ContextMenuItemTagDownloadImageToDisk:
            // FIXME: Some day we should be able to do this from within WebCore.
            m_client->downloadURL(result.absoluteImageURL());
            break;
        case ContextMenuItemTagCopyImageToClipboard:
            // FIXME: The Pasteboard class is not written yet
            // For now, call into the client. This is temporary!
            frame->editor()->copyImage(result);
            break;
        case ContextMenuItemTagOpenFrameInNewWindow: {
            DocumentLoader* loader = frame->loader()->documentLoader();
            if (!loader->unreachableURL().isEmpty())
                openNewWindow(loader->unreachableURL(), frame);
            else
                openNewWindow(loader->url(), frame);
            break;
        }
        case ContextMenuItemTagCopy:
            frame->editor()->copy();
            break;
        case ContextMenuItemTagGoBack:
            frame->loader()->goBackOrForward(-1);
            break;
        case ContextMenuItemTagGoForward:
            frame->loader()->goBackOrForward(1);
            break;
        case ContextMenuItemTagStop:
            frame->loader()->stop();
            break;
        case ContextMenuItemTagReload:
            frame->loader()->reload();
            break;
        case ContextMenuItemTagCut:
            frame->editor()->cut();
            break;
        case ContextMenuItemTagPaste:
            frame->editor()->paste();
            break;
#if PLATFORM(GTK)
        case ContextMenuItemTagDelete:
            frame->editor()->performDelete();
            break;
        case ContextMenuItemTagSelectAll:
            frame->editor()->command("SelectAll").execute();
            break;
#endif
        case ContextMenuItemTagSpellingGuess:
            ASSERT(frame->selectedText().length());
            if (frame->editor()->shouldInsertText(item->title(), frame->selection()->toRange().get(),
                EditorInsertActionPasted)) {
                Document* document = frame->document();
                RefPtr<ReplaceSelectionCommand> command =
                    ReplaceSelectionCommand::create(document, createFragmentFromMarkup(document, item->title(), ""),
                                                                                   true, false, true);
                applyCommand(command);
                frame->revealSelection(RenderLayer::gAlignToEdgeIfNeeded);
            }
            break;
        case ContextMenuItemTagIgnoreSpelling:
            frame->editor()->ignoreSpelling();
            break;
        case ContextMenuItemTagLearnSpelling:
            frame->editor()->learnSpelling();
            break;
        case ContextMenuItemTagSearchWeb:
            m_client->searchWithGoogle(frame);
            break;
        case ContextMenuItemTagLookUpInDictionary:
            // FIXME: Some day we may be able to do this from within WebCore.
            m_client->lookUpInDictionary(frame);
            break;
        case ContextMenuItemTagOpenLink:
            if (Frame* targetFrame = result.targetFrame())
                targetFrame->loader()->loadFrameRequestWithFormAndValues(FrameLoadRequest(ResourceRequest(result.absoluteLinkURL(), 
                    frame->loader()->outgoingReferrer())), false, false, 0, 0, HashMap<String, String>());
            else
                openNewWindow(result.absoluteLinkURL(), frame);
            break;
        case ContextMenuItemTagBold:
            frame->editor()->command("ToggleBold").execute();
            break;
        case ContextMenuItemTagItalic:
            frame->editor()->command("ToggleItalic").execute();
            break;
        case ContextMenuItemTagUnderline:
            frame->editor()->toggleUnderline();
            break;
        case ContextMenuItemTagOutline:
            // We actually never enable this because CSS does not have a way to specify an outline font,
            // which may make this difficult to implement. Maybe a special case of text-shadow?
            break;
        case ContextMenuItemTagStartSpeaking: {
            ExceptionCode ec;
            RefPtr<Range> selectedRange = frame->selection()->toRange();
            if (!selectedRange || selectedRange->collapsed(ec)) {
                Document* document = result.innerNonSharedNode()->document();
                selectedRange = document->createRange();
                selectedRange->selectNode(document->documentElement(), ec);
            }
            m_client->speak(plainText(selectedRange.get()));
            break;
        }
        case ContextMenuItemTagStopSpeaking:
            m_client->stopSpeaking();
            break;
        case ContextMenuItemTagDefaultDirection:
            frame->editor()->setBaseWritingDirection(NaturalWritingDirection);
            break;
        case ContextMenuItemTagLeftToRight:
            frame->editor()->setBaseWritingDirection(LeftToRightWritingDirection);
            break;
        case ContextMenuItemTagRightToLeft:
            frame->editor()->setBaseWritingDirection(RightToLeftWritingDirection);
            break;
        case ContextMenuItemTagTextDirectionDefault:
            frame->editor()->command("MakeTextWritingDirectionNatural").execute();
            break;
        case ContextMenuItemTagTextDirectionLeftToRight:
            frame->editor()->command("MakeTextWritingDirectionLeftToRight").execute();
            break;
        case ContextMenuItemTagTextDirectionRightToLeft:
            frame->editor()->command("MakeTextWritingDirectionRightToLeft").execute();
            break;
#if PLATFORM(MAC)
        case ContextMenuItemTagSearchInSpotlight:
            m_client->searchWithSpotlight();
            break;
#endif
        case ContextMenuItemTagShowSpellingPanel:
            frame->editor()->showSpellingGuessPanel();
            break;
        case ContextMenuItemTagCheckSpelling:
            frame->editor()->advanceToNextMisspelling();
            break;
        case ContextMenuItemTagCheckSpellingWhileTyping:
            frame->editor()->toggleContinuousSpellChecking();
            break;
#ifndef BUILDING_ON_TIGER
        case ContextMenuItemTagCheckGrammarWithSpelling:
            frame->editor()->toggleGrammarChecking();
            break;
#endif
#if PLATFORM(MAC)
        case ContextMenuItemTagShowFonts:
            frame->editor()->showFontPanel();
            break;
        case ContextMenuItemTagStyles:
            frame->editor()->showStylesPanel();
            break;
        case ContextMenuItemTagShowColors:
            frame->editor()->showColorPanel();
            break;
#endif
        case ContextMenuItemTagInspectElement:
            if (Page* page = frame->page())
                page->inspectorController()->inspect(result.innerNonSharedNode());
            break;
        default:
            break;
    }
}
Esempio n. 25
0
PopupMenuChromium::PopupMenuChromium(Frame& frame, PopupMenuClient* client)
    : m_popupClient(client)
    , m_frameView(frame.view())
{
}
Esempio n. 26
0
void DocumentWriter::addData(const char* str, int len, bool flush)
{
    if (len == 0 && !flush)
        return;

    if (len == -1)
        len = strlen(str);

    Tokenizer* tokenizer = m_frame->document()->tokenizer();
    if (tokenizer && tokenizer->wantsRawData()) {
        if (len > 0)
            tokenizer->writeRawData(str, len);
        return;
    }
    
    if (!m_decoder) {
        if (Settings* settings = m_frame->settings()) {
            m_decoder = TextResourceDecoder::create(m_mimeType,
                settings->defaultTextEncodingName(),
                settings->usesEncodingDetector());
            Frame* parentFrame = m_frame->tree()->parent();
            // Set the hint encoding to the parent frame encoding only if
            // the parent and the current frames share the security origin.
            // We impose this condition because somebody can make a child frame 
            // containing a carefully crafted html/javascript in one encoding
            // that can be mistaken for hintEncoding (or related encoding) by
            // an auto detector. When interpreted in the latter, it could be
            // an attack vector.
            // FIXME: This might be too cautious for non-7bit-encodings and
            // we may consider relaxing this later after testing.
            if (canReferToParentFrameEncoding(m_frame, parentFrame))
                m_decoder->setHintEncoding(parentFrame->document()->decoder());
        } else
            m_decoder = TextResourceDecoder::create(m_mimeType, String());
        Frame* parentFrame = m_frame->tree()->parent();
        if (m_encoding.isEmpty()) {
            if (canReferToParentFrameEncoding(m_frame, parentFrame))
                m_decoder->setEncoding(parentFrame->document()->inputEncoding(), TextResourceDecoder::EncodingFromParentFrame);
        } else {
            m_decoder->setEncoding(m_encoding,
                m_encodingWasChosenByUser ? TextResourceDecoder::UserChosenEncoding : TextResourceDecoder::EncodingFromHTTPHeader);
        }
        m_frame->document()->setDecoder(m_decoder.get());
    }

    String decoded = m_decoder->decode(str, len);
    if (flush)
        decoded += m_decoder->flush();
    if (decoded.isEmpty())
        return;

    if (!m_receivedData) {
        m_receivedData = true;
        if (m_decoder->encoding().usesVisualOrdering())
            m_frame->document()->setVisuallyOrdered();
        m_frame->document()->recalcStyle(Node::Force);
    }

    if (tokenizer) {
        ASSERT(!tokenizer->wantsRawData());
        tokenizer->write(decoded, true);
    }
}
void Animation::setNodeCount(int nodeCount)
{
    Frame *frame = m_frames.at(m_currentFrame);
    frame->setNodeCount(nodeCount);
}
Esempio n. 28
0
bool WebViewInputMethodFilter::canEdit()
{
    Frame* frame = focusedOrMainFrame();
    return frame && frame->editor().canEdit();
}
void Animation::setNodePos(int idx, const QPointF &pos)
{
    Frame *frame = m_frames.at(m_currentFrame);
    frame->setNodePos(idx, pos);
}
Frame * Decoder::decodeVideo2(Packet & packet) {
  LOGTRACEMETHOD("Decode Video");
  if (false && !_pix_fmt_converter) {
    Format in;
    in.width = ctx->width;
    in.height = ctx->height;
    in.pixel_format = ctx->pix_fmt;
    _output_format = in;
    _output_format.pixel_format = STD_PIX_FMT;
    _pix_fmt_converter = new PixelFormatConverter(in, _output_format);
    _pix_fmt_converter->open();
  }
  //Ptr<Frame> tmp_frame = new Frame(ctx->pix_fmt, ctx->width, ctx->height, false);
  //Frame * frame = new Frame(ctx->pix_fmt, ctx->width, ctx->height);
  Frame * frame = new Frame();
  int _frameFinished = 0;
  int len = packet.packet->size;
  LOGDEBUG(packet.toString());

  //  while (len > 0) {
  //    logdebug("Decode Packet");
  int bytesDecoded = 0;
  //if (ctx->codec_id > -1) {
  bytesDecoded = avcodec_decode_video2(ctx, frame->getAVFrame(), &_frameFinished, packet.packet);
  //}
  if (_frameFinished) {

    //_pix_fmt_converter->process(*tmp_frame, *frame);
    if (ctx->coded_frame) {
      LOGDEBUG("DeCodedFrameQuality:" << ctx->coded_frame->quality);
      LOGDEBUG("Interlaced:" << ctx->coded_frame->interlaced_frame);
      LOGDEBUG("topfieldfirst:" << ctx->coded_frame->top_field_first);
      //LOGDEBUG("PictureType:" << av_get_pict_type_char(ctx->coded_frame->pict_type));
    }
  }
  //@TODO: this is a hack, because the decoder changes the TimeBase after the first packet was decoded
  if (false && _last_pts == AV_NOPTS_VALUE) {
#ifdef USE_TIME_BASE_Q
    _last_pts = av_rescale_q(packet.getPts(), packet.getTimeBase(), AV_TIME_BASE_Q);
#else
    _last_pts = av_rescale_q(packet.getPts(), packet.getTimeBase(), _frame_rate);
#endif
    LOGDEBUG("setting last pts to " << _last_pts << " ctxtb=" << _frame_rate.num << "/" << _frame_rate.den
    << " ptb=" << packet.getTimeBase().num << "/" << packet.getTimeBase().den);
  }

  LOGDEBUG("BytesDecoded:" << bytesDecoded);
  frame->setPixelAspectRatio(ctx->sample_aspect_ratio);
  LOGDEBUG("PAR " << ctx->sample_aspect_ratio.num << "/" << ctx->sample_aspect_ratio.den);
  LOGDEBUG("RES " << ctx->coded_width << "/" << ctx->coded_height);
  AVRational display_aspect_ratio;
  av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
  ctx->width * ctx->sample_aspect_ratio.num,
  ctx->height * ctx->sample_aspect_ratio.den,
  1024 * 1024);
  LOGDEBUG("DAR " << display_aspect_ratio.num << "/" << display_aspect_ratio.den);

  if (bytesDecoded < 0) {
    LOGERROR("Error while decoding frame");
  }
  /**
   * if frame is not finished, returns the blank frame
   * the calling process of decode must ensure to check if the returning frame isFinished by calling the Method isFinished()
   */
  if (!_frameFinished) {
    LOGDEBUG("frame not finished");
    return frame;
  }
  frame->setStorageAspectRatio(ctx->coded_width, ctx->coded_height);
  frame->setPixelAspectRatio(ctx->sample_aspect_ratio);
  frame->setDisplayAspectRatio(display_aspect_ratio);
  len -= bytesDecoded;


  //  }
  /* calculating the Presentation TimeStamp here*/
  frame->setPts(_last_pts);
  //frame->setDts(_last_pts);

#ifdef USE_TIME_BASE_Q
  frame->setTimeBase(AV_TIME_BASE_Q);
  // calculating the duration of the decoded packet
  int64_t dur = av_rescale_q(packet.packet->duration, packet.getTimeBase(), AV_TIME_BASE_Q);
#else
  //  frame->setTimeBase(ctx->time_base);
  // calculating the duration of the decoded packet
  //    int64_t dur = av_rescale_q(packet.packet->duration, packet.getTimeBase(), ctx->time_base);
  //  int64_t tmp_dur=((int64_t)AV_TIME_BASE * ctx->time_base.num * ctx->ticks_per_frame) / ctx->time_base.den;
  AVRational ar;
  ar.num = _frame_rate.den;
  ar.den = _frame_rate.num; //* ctx->ticks_per_frame;
  LOGDEBUG("ticks:" << ctx->ticks_per_frame);
  //  int64_t dur = av_rescale_q(ar.num , ar, ctx->time_base);
  frame->setTimeBase(ar);
  int64_t dur = 1;
#endif

  frame->setFinished(_frameFinished!=0);
  //  frame->_pixFormat = ctx->pix_fmt;
  frame->stream_index = _stream_index;//packet.packet->stream_index;


  frame->duration = dur;
  _last_pts += dur;
  //  if (!_frameFinished) {
  //    return frame;
  //  }

  frame->pos = 0;
  frame->_type = AVMEDIA_TYPE_VIDEO;
  LOGDEBUG(frame->toString());
  pushFrame(new Frame(*frame));
  return frame;
}