inline void thread_usleep(unsigned int usec) { snooze(usec); }
RTDECL(int) RTThreadSleep(RTMSINTERVAL cMillies) { RT_ASSERT_PREEMPTIBLE(); snooze((bigtime_t)cMillies * 1000); return VINF_SUCCESS; }
Hub::Hub(Object *parent, int8 hubAddress, uint8 hubPort, usb_device_descriptor &desc, int8 deviceAddress, usb_speed speed, bool isRootHub) : Device(parent, hubAddress, hubPort, desc, deviceAddress, speed, isRootHub), fInterruptPipe(NULL) { TRACE("creating hub\n"); memset(&fHubDescriptor, 0, sizeof(fHubDescriptor)); for (int32 i = 0; i < USB_MAX_PORT_COUNT; i++) fChildren[i] = NULL; if (!fInitOK) { TRACE_ERROR("device failed to initialize\n"); return; } // Set to false again for the hub init. fInitOK = false; if (fDeviceDescriptor.device_class != 9) { TRACE_ERROR("wrong class! bailing out\n"); return; } TRACE("getting hub descriptor...\n"); size_t actualLength; status_t status = GetDescriptor(USB_DESCRIPTOR_HUB, 0, 0, (void *)&fHubDescriptor, sizeof(usb_hub_descriptor), &actualLength); // we need at least 8 bytes if (status < B_OK || actualLength < 8) { TRACE_ERROR("error getting hub descriptor\n"); return; } TRACE("hub descriptor (%ld bytes):\n", actualLength); TRACE("\tlength:..............%d\n", fHubDescriptor.length); TRACE("\tdescriptor_type:.....0x%02x\n", fHubDescriptor.descriptor_type); TRACE("\tnum_ports:...........%d\n", fHubDescriptor.num_ports); TRACE("\tcharacteristics:.....0x%04x\n", fHubDescriptor.characteristics); TRACE("\tpower_on_to_power_g:.%d\n", fHubDescriptor.power_on_to_power_good); TRACE("\tdevice_removeable:...0x%02x\n", fHubDescriptor.device_removeable); TRACE("\tpower_control_mask:..0x%02x\n", fHubDescriptor.power_control_mask); if (fHubDescriptor.num_ports > USB_MAX_PORT_COUNT) { TRACE_ALWAYS("hub supports more ports than we do (%d vs. %d)\n", fHubDescriptor.num_ports, USB_MAX_PORT_COUNT); fHubDescriptor.num_ports = USB_MAX_PORT_COUNT; } usb_interface_list *list = Configuration()->interface; Object *object = GetStack()->GetObject(list->active->endpoint[0].handle); if (object && (object->Type() & USB_OBJECT_INTERRUPT_PIPE) != 0) { fInterruptPipe = (InterruptPipe *)object; fInterruptPipe->QueueInterrupt(fInterruptStatus, sizeof(fInterruptStatus), InterruptCallback, this); } else { TRACE_ALWAYS("no interrupt pipe found\n"); } // Wait some time before powering up the ports if (!isRootHub) snooze(USB_DELAY_HUB_POWER_UP); // Enable port power on all ports for (int32 i = 0; i < fHubDescriptor.num_ports; i++) { status = DefaultPipe()->SendRequest(USB_REQTYPE_CLASS | USB_REQTYPE_OTHER_OUT, USB_REQUEST_SET_FEATURE, PORT_POWER, i + 1, 0, NULL, 0, NULL); if (status < B_OK) TRACE_ERROR("power up failed on port %" B_PRId32 "\n", i); } // Wait for power to stabilize snooze(fHubDescriptor.power_on_to_power_good * 2000); fInitOK = true; TRACE("initialised ok\n"); }
static void *sendKeepalives(void *parm) { KeepaliveThreadParms *parms = (KeepaliveThreadParms *) parm; int keepaliveTimer = 0; int bytesSent; int backoffTimer = BACKOFF_TIMER_START; int backoffTimerCount = 0; unsigned char *buffer; buffer = MTAKE(TCPCLA_BUFSZ); //To send keepalive bundle if (buffer == NULL) { putErrmsg("No memory for TCP buffer in tcpclo.", NULL); return NULL; } iblock(SIGTERM); while (*(parms->cloRunning)) { snooze(1); keepaliveTimer++; if (keepaliveTimer < *(parms->keepalivePeriod)) { continue; } // If the negotiated keep alive interval is 0, then // keep alives will not be sent. if(*(parms->keepalivePeriod) == 0) { continue; } /* Time to send a keepalive. Note that the * interval between keepalive attempts will be * KEEPALIVE_PERIOD plus (if the remote induct * is not reachable) the length of time taken * by TCP to determine that the connection * attempt will not succeed (e.g., 3 seconds). */ keepaliveTimer = 0; pthread_mutex_lock(parms->mutex); bytesSent = sendBundleByTCPCL(parms->socketName, parms->ductSocket, 0, 0, buffer, parms->keepalivePeriod); pthread_mutex_unlock(parms->mutex); /* if the node is unable to establish a TCP connection, * the connection should be tried only after some delay. * */ if(bytesSent == 0) { while((backoffTimerCount < backoffTimer) && (*(parms->ductSocket) < 0)) { snooze(1); backoffTimerCount++; if(!(*(parms->cloRunning))) { break; } } backoffTimerCount = 0; /* keepaliveTimer keeps track of when the keepalive needs * to be sent. This value is set to keepalive period. * That way at the end of backoff period a * keepalive is sent * */ keepaliveTimer = *(parms->keepalivePeriod); if(backoffTimer < BACKOFF_TIMER_LIMIT) { backoffTimer *= 2; } continue; } backoffTimer = BACKOFF_TIMER_START; if (bytesSent < 0) { shutDownClo(); break; } } MRELEASE(buffer); return NULL; }
void DownloadProgressView::MessageReceived(BMessage* message) { switch (message->what) { case B_DOWNLOAD_STARTED: { BString path; if (message->FindString("path", &path) != B_OK) break; fPath.SetTo(path); BEntry entry(fPath.Path()); fIconView->SetTo(entry); fStatusBar->Reset(fPath.Leaf()); _StartNodeMonitor(entry); // Immediately switch to speed display whenever a new download // starts. sShowSpeed = true; sLastEstimatedFinishSpeedToggleTime = fProcessStartTime = fLastSpeedReferenceTime = fEstimatedFinishReferenceTime = system_time(); break; } case B_DOWNLOAD_PROGRESS: { int64 currentSize; int64 expectedSize; if (message->FindInt64("current size", ¤tSize) == B_OK && message->FindInt64("expected size", &expectedSize) == B_OK) { _UpdateStatus(currentSize, expectedSize); } break; } case B_DOWNLOAD_REMOVED: // TODO: This is a bit asymetric. The removed notification // arrives here, but it would be nicer if it arrived // at the window... Window()->PostMessage(message); break; case OPEN_DOWNLOAD: { // TODO: In case of executable files, ask the user first! entry_ref ref; status_t status = get_ref_for_path(fPath.Path(), &ref); if (status == B_OK) status = be_roster->Launch(&ref); if (status != B_OK && status != B_ALREADY_RUNNING) { BAlert* alert = new BAlert("Open download error", "The download could not be opened.", "OK"); alert->Go(NULL); } break; } case RESTART_DOWNLOAD: BWebPage::RequestDownload(fURL); break; case CANCEL_DOWNLOAD: fDownload->Cancel(); DownloadCanceled(); break; case REMOVE_DOWNLOAD: { Window()->PostMessage(SAVE_SETTINGS); RemoveSelf(); delete this; // TOAST! return; } case B_NODE_MONITOR: { int32 opCode; if (message->FindInt32("opcode", &opCode) != B_OK) break; switch (opCode) { case B_ENTRY_REMOVED: fIconView->SetIconDimmed(true); DownloadCanceled(); break; case B_ENTRY_MOVED: { // Follow the entry to the new location dev_t device; ino_t directory; const char* name; if (message->FindInt32("device", reinterpret_cast<int32*>(&device)) != B_OK || message->FindInt64("to directory", reinterpret_cast<int64*>(&directory)) != B_OK || message->FindString("name", &name) != B_OK || strlen(name) == 0) { break; } // Construct the BEntry and update fPath entry_ref ref(device, directory, name); BEntry entry(&ref); if (entry.GetPath(&fPath) != B_OK) break; // Find out if the directory is the Trash for this // volume char trashPath[B_PATH_NAME_LENGTH]; if (find_directory(B_TRASH_DIRECTORY, device, false, trashPath, B_PATH_NAME_LENGTH) == B_OK) { BPath trashDirectory(trashPath); BPath parentDirectory; fPath.GetParent(&parentDirectory); if (parentDirectory == trashDirectory) { // The entry was moved into the Trash. // If the download is still in progress, // cancel it. if (fDownload) fDownload->Cancel(); fIconView->SetIconDimmed(true); DownloadCanceled(); break; } else if (fIconView->IsIconDimmed()) { // Maybe it was moved out of the trash. fIconView->SetIconDimmed(false); } } // Inform download of the new path if (fDownload) fDownload->HasMovedTo(fPath); float value = fStatusBar->CurrentValue(); fStatusBar->Reset(name); fStatusBar->SetTo(value); Window()->PostMessage(SAVE_SETTINGS); break; } case B_ATTR_CHANGED: { BEntry entry(fPath.Path()); fIconView->SetIconDimmed(false); fIconView->SetTo(entry); break; } } break; } // Context menu messages case COPY_URL_TO_CLIPBOARD: if (be_clipboard->Lock()) { BMessage* data = be_clipboard->Data(); if (data != NULL) { be_clipboard->Clear(); data->AddData("text/plain", B_MIME_TYPE, fURL.String(), fURL.Length()); } be_clipboard->Commit(); be_clipboard->Unlock(); } break; case OPEN_CONTAINING_FOLDER: if (fPath.InitCheck() == B_OK) { BPath containingFolder; if (fPath.GetParent(&containingFolder) != B_OK) break; BEntry entry(containingFolder.Path()); if (!entry.Exists()) break; entry_ref ref; if (entry.GetRef(&ref) != B_OK) break; be_roster->Launch(&ref); // Use Tracker scripting and select the download pose // in the window. // TODO: We should somehow get the window that just openend. // Using the name like this is broken when there are multiple // windows open with this name. Also Tracker does not scroll // to this entry. BString windowName = ref.name; BString fullWindowName = containingFolder.Path(); BMessenger trackerMessenger("application/x-vnd.Be-TRAK"); if (trackerMessenger.IsValid() && get_ref_for_path(fPath.Path(), &ref) == B_OK) { // We need to wait a bit until the folder is open. // TODO: This is also too fragile... we should be able // to wait for the roster message. snooze(250000); int32 tries = 2; while (tries > 0) { BMessage selectionCommand(B_SET_PROPERTY); selectionCommand.AddSpecifier("Selection"); selectionCommand.AddSpecifier("Poses"); selectionCommand.AddSpecifier("Window", windowName.String()); selectionCommand.AddRef("data", &ref); BMessage reply; trackerMessenger.SendMessage(&selectionCommand, &reply); int32 error; if (reply.FindInt32("error", &error) != B_OK || error == B_OK) { break; } windowName = fullWindowName; tries--; } } } break; default: BGroupView::MessageReceived(message); } }
static void Virge_GEReset(const DisplayModeEx& mode) { SharedInfo& si = *gInfo.sharedInfo; if (si.chipType == S3_TRIO_3D) Virge_NopAllCmdSets(); gInfo.WaitIdleEmpty(); if (si.chipType == S3_TRIO_3D) { bool ge_was_on = false; snooze(10000); for (int r = 1; r < 10; r++) { uint8 resetidx = 0x66; VerticalRetraceWait(); uint8 tmp = ReadCrtcReg(resetidx); VerticalRetraceWait(); IN_SUBSYS_STAT(); // turn off the GE if (tmp & 0x01) { WriteCrtcReg(resetidx, tmp); ge_was_on = true; snooze(10000); } IN_SUBSYS_STAT(); WriteCrtcReg(resetidx, tmp | 0x02); snooze(10000); VerticalRetraceWait(); WriteCrtcReg(resetidx, tmp & ~0x02); snooze(10000); if (ge_was_on) { tmp |= 0x01; WriteCrtcReg(resetidx, tmp); snooze(10000); } VerticalRetraceWait(); Virge_NopAllCmdSets(); gInfo.WaitIdleEmpty(); WriteReg32(DEST_SRC_STR, mode.bytesPerRow << 16 | mode.bytesPerRow); snooze(10000); if ((IN_SUBSYS_STAT() & 0x3f802000 & 0x20002000) != 0x20002000) { TRACE("Restarting S3 graphics engine reset %2d ...%lx\n", r, IN_SUBSYS_STAT() ); } else break; } } else { uint8 regIndex = (si.chipType == S3_VIRGE_VX ? 0x63 : 0x66); uint8 tmp = ReadCrtcReg(regIndex); snooze(10000); // try multiple times to avoid lockup of VIRGE/MX for (int r = 1; r < 10; r++) { WriteCrtcReg(regIndex, tmp | 0x02); snooze(10000); WriteCrtcReg(regIndex, tmp & ~0x02); snooze(10000); gInfo.WaitIdleEmpty(); WriteReg32(DEST_SRC_STR, mode.bytesPerRow << 16 | mode.bytesPerRow); snooze(10000); if (((IN_SUBSYS_STAT() & 0x3f00) != 0x3000)) { TRACE("Restarting S3 graphics engine reset %2d ...\n", r); } else break; } } gInfo.WaitQueue(2); WriteReg32(SRC_BASE, 0); WriteReg32(DEST_BASE, 0); gInfo.WaitQueue(4); WriteReg32(CLIP_L_R, ((0) << 16) | mode.timing.h_display); WriteReg32(CLIP_T_B, ((0) << 16) | mode.timing.v_display); WriteReg32(MONO_PAT_0, ~0); WriteReg32(MONO_PAT_1, ~0); if (si.chipType == S3_TRIO_3D) Virge_NopAllCmdSets(); }
static int floatsleep(double secs) { /* XXX Should test for MS_WINDOWS first! */ #if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__) struct timeval t; double frac; #if defined (AMITCP) || defined(INET225) /* check for availability of an Amiga TCP stack for select() */ if(!checksocketlib()) { /* no bsdsocket.library-- use dos/Delay() */ PyErr_Clear(); Delay((long)(secs*50)); /* XXX Can't interrupt this sleep */ return 0; } #endif frac = fmod(secs, 1.0); secs = floor(secs); t.tv_sec = (long)secs; t.tv_usec = (long)(frac*1000000.0); Py_BEGIN_ALLOW_THREADS if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) { #ifdef EINTR if (errno != EINTR) { #else if (1) { #endif Py_BLOCK_THREADS PyErr_SetFromErrno(PyExc_IOError); return -1; } } Py_END_ALLOW_THREADS #elif defined(macintosh) #define MacTicks (* (long *)0x16A) long deadline; deadline = MacTicks + (long)(secs * 60.0); while (MacTicks < deadline) { /* XXX Should call some yielding function here */ if (PyErr_CheckSignals()) return -1; } #elif defined(__WATCOMC__) && !defined(__QNX__) /* XXX Can't interrupt this sleep */ Py_BEGIN_ALLOW_THREADS delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */ Py_END_ALLOW_THREADS #elif defined(MS_WINDOWS) { double millisecs = secs * 1000.0; unsigned long ul_millis; if (millisecs > (double)ULONG_MAX) { PyErr_SetString(PyExc_OverflowError, "sleep length is too large"); return -1; } Py_BEGIN_ALLOW_THREADS /* Allow sleep(0) to maintain win32 semantics, and as decreed * by Guido, only the main thread can be interrupted. */ ul_millis = (unsigned long)millisecs; if (ul_millis == 0 || main_thread != PyThread_get_thread_ident()) Sleep(ul_millis); else { DWORD rc; ResetEvent(hInterruptEvent); rc = WaitForSingleObject(hInterruptEvent, ul_millis); if (rc == WAIT_OBJECT_0) { /* Yield to make sure real Python signal * handler called. */ Sleep(1); Py_BLOCK_THREADS errno = EINTR; PyErr_SetFromErrno(PyExc_IOError); return -1; } } Py_END_ALLOW_THREADS } #elif defined(PYOS_OS2) /* This Sleep *IS* Interruptable by Exceptions */ Py_BEGIN_ALLOW_THREADS if (DosSleep(secs * 1000) != NO_ERROR) { Py_BLOCK_THREADS PyErr_SetFromErrno(PyExc_IOError); return -1; } Py_END_ALLOW_THREADS #elif defined(__BEOS__) /* This sleep *CAN BE* interrupted. */ { if( secs <= 0.0 ) { return; } Py_BEGIN_ALLOW_THREADS /* BeOS snooze() is in microseconds... */ if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) { Py_BLOCK_THREADS PyErr_SetFromErrno( PyExc_IOError ); return -1; } Py_END_ALLOW_THREADS } #elif defined(RISCOS) if (secs <= 0.0) return 0; Py_BEGIN_ALLOW_THREADS /* This sleep *CAN BE* interrupted. */ if ( riscos_sleep(secs) ) return -1; Py_END_ALLOW_THREADS #elif defined(PLAN9) { double millisecs = secs * 1000.0; if (millisecs > (double)LONG_MAX) { PyErr_SetString(PyExc_OverflowError, "sleep length is too large"); return -1; } /* This sleep *CAN BE* interrupted. */ Py_BEGIN_ALLOW_THREADS if(sleep((long)millisecs) < 0){ Py_BLOCK_THREADS PyErr_SetFromErrno(PyExc_IOError); return -1; } Py_END_ALLOW_THREADS } #elif _AMIGA /* XXX Can't interrupt this sleep */ Py_BEGIN_ALLOW_THREADS Delay((long)(secs*50)); Py_END_ALLOW_THREADS #else /* !_AMIGA */ /* XXX Can't interrupt this sleep */ Py_BEGIN_ALLOW_THREADS sleep((int)secs); Py_END_ALLOW_THREADS #endif /* !_AMIGA */ /* XXX Can't interrupt this sleep */ return 0; }
status_t TToolTipView::ToolTipThread(tool_tip *tip) { uint32 buttons; BPoint where; BScreen s(B_MAIN_SCREEN_ID); BRect screen = s.Frame(); screen.InsetBy(2, 2); while (!tip->quit) { if (tip->tool_tip_window->LockWithTimeout(0) == B_NO_ERROR) { if (tip->tool_tip_view->Window()) tip->tool_tip_view->GetMouse(&where, &buttons,false); /* if (tip->tool_tip_view->Window()) if (tip->tool_tip_view->Window()->CurrentMessage()) { tip->tool_tip_view->Window()->CurrentMessage()->FindPoint("where", &where); tip->tool_tip_view->Window()->CurrentMessage()->FindInt32("buttons", (int32*)&buttons); } */ tip->tool_tip_view->ConvertToScreen(&where); tip->stopped = tip->stop; if (tip->reset) { if (tip->showing) tip->tool_tip_window->Hide(); tip->stop = false; tip->stopped = false; tip->reset = false; tip->shown = false; tip->showing = false; tip->start_time = system_time() + tip->settings.delay; } else if (tip->showing) { if ((tip->stop) || (!tip->settings.enabled) || (!tip->app_active) || (!tip->bounds.Contains(where)) || (tip->expire_time < system_time()) || (abs((int)tip->start.x - (int)where.x) > kSLOP) || (abs((int)tip->start.y - (int)where.y) > kSLOP) || (buttons)) { tip->tool_tip_window->Hide(); tip->shown = tip->settings.one_time_only; tip->showing = false; tip->tip_timed_out = (tip->expire_time < system_time()); tip->start_time = system_time() + tip->settings.delay; } } else if ((tip->settings.enabled) && (!tip->stopped) && (tip->app_active) && (!tip->shown) && (!tip->tip_timed_out) && (!buttons) && (tip->bounds.Contains(where)) && (tip->start_time < system_time())) { tip->start = where; tip->tool_tip_view->AdjustWindow(); tip->tool_tip_window->Show(); tip->tool_tip_window->Activate(false); tip->showing = true; tip->expire_time = system_time() + tip->settings.hold; tip->start = where; } else if ((abs((int)tip->start.x - (int)where.x) > kSLOP) || (abs((int)tip->start.y - (int)where.y) > kSLOP)) { tip->start = where; tip->start_time = system_time() + tip->settings.delay; tip->tip_timed_out = false; } if (buttons) tip->start_time = system_time() + tip->settings.delay; tip->tool_tip_window->Unlock(); } snooze(50000); } return B_NO_ERROR; }
int main (int argc, char* argv[]) { // int oldtime, newtime; // bk001204 - unused int len, i; char *cmdline; //jens void Sys_SetDefaultCDPath(const char *path); thread_id cThread; cThread = spawn_thread(appthread, "q3appthread", B_LOW_PRIORITY, 0); resume_thread(cThread); snooze(100000); //Todo app_info cInfo; be_app->GetAppInfo(&cInfo); BEntry cFile(&cInfo.ref); BEntry cDir; cFile.GetParent(&cDir); BPath cPath; cDir.GetPath(&cPath); chdir(cPath.Path()); be_app->HideCursor(); // go back to real user for config loads //jens saved_euid = geteuid(); //jens seteuid(getuid()); Sys_ParseArgs(argc, argv); // bk010104 - added this for support Sys_SetDefaultCDPath(argv[0]); // merge the command line, this is kinda silly for (len = 1, i = 1; i < argc; i++) len += strlen(argv[i]) + 1; cmdline = (char*)malloc(len); *cmdline = 0; for (i = 1; i < argc; i++) { if (i > 1) strcat(cmdline, " "); strcat(cmdline, argv[i]); } // bk000306 - clear queues memset(&eventQue[0], 0, MAX_QUED_EVENTS*sizeof(sysEvent_t) ); memset(&sys_packetReceived[0], 0, MAX_MSGLEN*sizeof(byte) ); Com_Init(cmdline); NET_Init(); Sys_ConsoleInputInit(); // int fd = 0; // fd = fileno(stdin); // int on = 1; // setsockopt(fd, SOL_SOCKET, SO_NONBLOCK, &on, sizeof(int)); // setsockopt(STDIN_FILENO, SOL_SOCKET, SO_NONBLOCK, &on, sizeof(int)); //jensfcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | FNDELAY); #ifdef DEDICATED // init here for dedicated, as we don't have GLimp_Init //jens InitSig(); #endif while (1) { #ifdef __linux__ Sys_ConfigureFPU(); #endif Com_Frame (); } }
int32 yahoo_io_thread( void * _data ) { YahooConnection * conn = (YahooConnection*)_data; register_callbacks(); conn->fID = yahoo_init_with_attributes(conn->fYahooID, conn->fPassword, "local_host", "95.252.70.62", "pager_port", 5050, NULL); LOG("yahoo_io_thread: id: %s, pass: %s\n", conn->fYahooID, conn->fPassword ); gYahooConnections[conn->fID] = conn; yahoo_login(conn->fID, YAHOO_STATUS_AVAILABLE); int lfd = 0; fd_set inp, outp; struct timeval tv; while (conn->IsAlive()) { snooze(10000); FD_ZERO(&inp); FD_ZERO(&outp); tv.tv_sec=3; tv.tv_usec=1E4; lfd=0; int i; for(i = 0; i < conn->CountConnections(); i++) { struct conn_handler *c = conn->ConnectionAt(i); if(c->remove) { conn->RemoveConnection(c); c->remove = 0; free(c); } else { if(c->cond & YAHOO_INPUT_READ) FD_SET(c->con->fd, &inp); if(c->cond & YAHOO_INPUT_WRITE) FD_SET(c->con->fd, &outp); if(lfd < c->con->fd) lfd = c->con->fd; } } select(lfd + 1, &inp, &outp, NULL, &tv); time(&curTime); for(i = 0; i < conn->CountConnections(); i++) { struct conn_handler *c = conn->ConnectionAt(i); if(c->con->remove) { free(c->con); c->con = NULL; break; } if(c->remove) continue; if(FD_ISSET(c->con->fd, &inp)) yahoo_callback(c, YAHOO_INPUT_READ); if(FD_ISSET(c->con->fd, &outp)) yahoo_callback(c, YAHOO_INPUT_WRITE); } if(expired(pingTimer)) yahoo_ping_timeout_callback(conn->fID); // if(expired(webcamTimer)) yahoo_webcam_timeout_callback(webcam_id); } LOG("Exited loop"); for(int i = 0; i < conn->CountConnections(); i++) { struct conn_handler *c = conn->ConnectionAt(i); free(c); conn->RemoveConnection(c); } return 0; }
int ltpclock(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10) { #else int main(int argc, char *argv[]) { #endif Sdr sdr; LtpDB *ltpConstants; int state = 1; time_t currentTime; if (ltpInit(0, 0) < 0) { putErrmsg("ltpclock can't initialize LTP.", NULL); return 1; } sdr = getIonsdr(); ltpConstants = getLtpConstants(); isignal(SIGTERM, shutDown); /* Main loop: wait for event occurrence time, then * execute applicable events. */ oK(_running(&state)); writeMemo("[i] ltpclock is running."); while (_running(NULL)) { /* Sleep for 1 second, then dispatch all events * whose executions times have now been reached. */ snooze(1); currentTime = getUTCTime(); /* Infer link state changes from rate changes * noted in the shared ION database. */ if (manageLinks(sdr, currentTime) < 0) { putErrmsg("Can't manage links.", NULL); state = 0; /* Terminate loop. */ oK(_running(&state)); continue; } /* Then dispatch retransmission events, as * constrained by the new link state. */ if (dispatchEvents(sdr, ltpConstants->timeline, currentTime) < 0) { putErrmsg("Can't dispatch events.", NULL); state = 0; /* Terminate loop. */ oK(_running(&state)); continue; } } writeErrmsgMemos(); writeMemo("[i] ltpclock has ended."); ionDetach(); return 0; }
static status_t usb_disk_device_added(usb_device newDevice, void **cookie) { TRACE("device_added(0x%08lx)\n", newDevice); disk_device *device = (disk_device *)malloc(sizeof(disk_device)); device->device = newDevice; device->removed = false; device->open_count = 0; device->interface = 0xff; device->current_tag = 0; device->sync_support = SYNC_SUPPORT_RELOAD; device->is_atapi = false; device->luns = NULL; // scan through the interfaces to find our data interface const usb_configuration_info *configuration = gUSBModule->get_configuration(newDevice); if (configuration == NULL) { free(device); return B_ERROR; } for (size_t i = 0; i < configuration->interface_count; i++) { usb_interface_info *interface = configuration->interface[i].active; if (interface == NULL) continue; if (interface->descr->interface_class == 0x08 /* mass storage */ && interface->descr->interface_subclass == 0x04 /* UFI (floppy) */ && interface->descr->interface_protocol == 0x00) { bool hasIn = false; bool hasOut = false; bool hasInt = false; for (size_t j = 0; j < interface->endpoint_count; j++) { usb_endpoint_info *endpoint = &interface->endpoint[j]; if (endpoint == NULL) continue; if (!hasIn && (endpoint->descr->endpoint_address & USB_ENDPOINT_ADDR_DIR_IN) && endpoint->descr->attributes == USB_ENDPOINT_ATTR_BULK) { device->bulk_in = endpoint->handle; hasIn = true; } else if (!hasOut && (endpoint->descr->endpoint_address & USB_ENDPOINT_ADDR_DIR_IN) == 0 && endpoint->descr->attributes == USB_ENDPOINT_ATTR_BULK) { device->bulk_out = endpoint->handle; hasOut = true; } else if (!hasInt && (endpoint->descr->endpoint_address & USB_ENDPOINT_ADDR_DIR_IN) && endpoint->descr->attributes == USB_ENDPOINT_ATTR_INTERRUPT) { // TODO:ensure there is only one interrupt endpoint and // stop enumerating device->interrupt = endpoint->handle; hasInt = true; } if (hasIn && hasOut && hasInt) break; } if (!(hasIn && hasOut && hasInt)) { TRACE("in: %d, out: %d, int: %d\n", hasIn, hasOut, hasInt); continue; } device->interface = interface->descr->interface_number; device->is_atapi = interface->descr->interface_subclass != 0x06; break; } } if (device->interface == 0xff) { TRACE_ALWAYS("no valid CBI interface found\n"); free(device); return B_ERROR; } mutex_init(&device->lock, "usb_disk device lock"); status_t result = device->notify = create_sem(0, "usb_disk callback notify"); if (result < B_OK) { mutex_destroy(&device->lock); free(device); return result; } result = device->interruptLock = create_sem(0, "usb_disk interrupt lock"); if (result < B_OK) { mutex_destroy(&device->lock); free(device); return result; } // TODO: handle more than 1 unit device->lun_count = 1; device->luns = (device_lun **)malloc(device->lun_count * sizeof(device_lun *)); for (uint8 i = 0; i < device->lun_count; i++) device->luns[i] = NULL; result = B_OK; TRACE_ALWAYS("device reports a lun count of %d\n", device->lun_count); for (uint8 i = 0; i < device->lun_count; i++) { // create the individual luns present on this device device_lun *lun = (device_lun *)malloc(sizeof(device_lun)); if (lun == NULL) { result = B_NO_MEMORY; break; } device->luns[i] = lun; lun->device = device; lun->logical_unit_number = i; lun->should_sync = false; lun->media_present = true; lun->media_changed = true; usb_disk_reset_capacity(lun); // initialize this lun result = usb_disk_inquiry(lun); // Reset the device // If we don't do it all the other commands except inquiry and send // diagnostics will be stalled. result = usb_disk_send_diagnostic(lun); for (uint32 tries = 0; tries < 3; tries++) { status_t ready = usb_disk_test_unit_ready(lun); if (ready == B_OK || ready == B_DEV_NO_MEDIA) { if (ready == B_OK) { if (lun->device_type == B_CD) lun->write_protected = true; // TODO: check for write protection; disabled since // some devices lock up when getting the mode sense else if (/*usb_disk_mode_sense(lun) != B_OK*/true) lun->write_protected = false; } break; } snooze(10000); } if (result != B_OK) break; } if (result != B_OK) { TRACE_ALWAYS("failed to initialize logical units\n"); usb_disk_free_device_and_luns(device); return result; } mutex_lock(&gDeviceListLock); device->device_number = 0; disk_device *other = gDeviceList; while (other != NULL) { if (other->device_number >= device->device_number) device->device_number = other->device_number + 1; other = (disk_device *)other->link; } device->link = (void *)gDeviceList; gDeviceList = device; gLunCount += device->lun_count; for (uint8 i = 0; i < device->lun_count; i++) sprintf(device->luns[i]->name, DEVICE_NAME, device->device_number, i); mutex_unlock(&gDeviceListLock); TRACE("new device: 0x%08lx\n", (uint32)device); *cookie = (void *)device; return B_OK; }
int main(int argc, char *argv[]) { ALuint freq; ALenum format; ALvoid *data; ALsizei i, size; thread_id thread1, thread2; status_t status; /* listener parameters */ ALfloat listenerOrientation[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f }; ALfloat listenerPosition[] = { 0.0f, 0.0f, 0.0f }; ALfloat listenerVelocity[] = { 0.0f, 0.0f, 0.0f }; /* source parameters */ ALfloat sourcePosition[] = { 0.0f, 0.0f, 1.0f }; ALfloat sourceVelocity[] = { 0.0f, 0.0f, 0.0f }; ALfloat sourcePitch = 1.0f; ALfloat sourceGain = 1.0f; /* initialize */ print("Main: initialize"); alInit((ALint *) &argc, (ALubyte **) argv); /* create context */ print("Main: create context"); context = alcCreateContext(22050, AL_FORMAT_STEREO16, 2048); /* lock the context */ print("Main: make current"); alcMakeCurrent(context); /* create buffers and sources */ if (alGenBuffers(kNumBuffers, buffer) != kNumBuffers) quit("Can't create buffers"); if (alGenSources(kNumSources, source) != kNumSources) quit("Can't create sources"); /* load buffers with data */ alutLoadWAV(kWaveFileName, &format, &data, &size, &freq); for (i = 0; i < kNumBuffers; i++) { alBufferData(buffer[i], format, data, size, freq); } free(data); /* initialize listener */ alListenerfv(AL_POSITION, listenerPosition); alListenerfv(AL_VELOCITY, listenerVelocity); alListenerfv(AL_ORIENTATION, listenerOrientation); /* initialize sources */ for (i = 0; i < kNumSources; i++) { alSourcefv(source[i], AL_POSITION, sourcePosition); alSourcefv(source[i], AL_VELOCITY, sourceVelocity); alSourcef(source[i], AL_PITCH, sourcePitch); alSourcef(source[i], AL_GAIN, sourceGain); alSourcei(source[i], AL_BUFFER, buffer[i % kNumBuffers]); alSourcei(source[i], AL_LOOPING, AL_TRUE); } /* start the sources */ print("Main: play"); for (i = 0; i < kNumSources; i++) alSourcePlay(source[i]); /* release the context */ print("Main: release current"); alcMakeCurrent(NULL); /* spawn two threads */ print("Main: spawn thread 1"); thread1 = spawn_thread(threadFunc1, "thread 1", B_NORMAL_PRIORITY, NULL); print("Main: spawn thread 2"); thread2 = spawn_thread(threadFunc2, "thread 2", B_NORMAL_PRIORITY, NULL); /* resume the threads */ print("Main: resume thread 1"); resume_thread(thread1); print("Main: resume thread 2"); resume_thread(thread2); /* acquire context, snooze and release context */ print("Main: make current"); alcMakeCurrent(context); print("Main: snooze..."); snooze(500000); print("Main: release current"); alcMakeCurrent(NULL); /* wait until the threads end */ print("Main: wait thread 1"); wait_for_thread(thread1, &status); if (status != 0) print("Main: thread 1 failed?"); print("Main: wait thread 2"); wait_for_thread(thread2, &status); if (status != 0) print("Main: thread 2 failed?"); /* acquire the context */ print("Main: make current"); alcMakeCurrent(context); /* delete buffers and sources */ print("Main: delete sources"); alDeleteSources(kNumSources, source); print("Main: delete buffers"); alDeleteBuffers(kNumBuffers, buffer); /* release the context */ print("Main: release current"); alcMakeCurrent(NULL); /* shutdown */ print("Main: delete context"); alcDeleteContext(context); /* bye */ print("Main: bye"); alExit(); return 0; }
void PatternMenuButton::MouseDown (BPoint point) { // BMenuItem *selected; // point = BPoint (0, 0); // ConvertToScreen (&point); // BRect openRect = BRect (point.x - OPEN_RAD, point.y - OPEN_RAD, // point.x + OPEN_RAD, point.y + OPEN_RAD); // menu->Show(); // if ((selected = menu->Track (true, &openRect)) != NULL) // { // index = menu->IndexOf (selected); // menu->Mark (index); // menu->InvalidateWindow(); // } // menu->Hide(); // Invalidate(); Window()->Lock(); uint32 buttons = Window()->CurrentMessage()->FindInt32 ("buttons"); // uint32 clicks = Window()->CurrentMessage()->FindInt32 ("clicks"); BMenuItem *mselected; point = BPoint (0, 0); ConvertToScreen (&point); if (click != 2 && buttons & B_PRIMARY_MOUSE_BUTTON && !(modifiers() & B_CONTROL_KEY)) { BPoint bp, pbp; uint32 bt; GetMouse (&pbp, &bt, true); bigtime_t start = system_time(); while (system_time() - start < dcspeed) { snooze (20000); GetMouse (&bp, &bt, true); if (!bt && click != 2) { click = 0; } if (bt && !click) { click = 2; } if (bp != pbp) break; } if (click != 2) { BRect openRect = BRect (point.x - OPEN_RAD, point.y - OPEN_RAD, point.x + OPEN_RAD, point.y + OPEN_RAD); menu->Show(); if ((mselected = menu->Track (true, &openRect)) != NULL) { index = menu->IndexOf (mselected); menu->Mark (index); if (MenuWinOnScreen) menu->InvalidateWindow(); } menu->Hide(); if (editorshowing) { // rgb_color c = color(); // BMessage *msg = new BMessage ('SetC'); // msg->AddInt32 ("color", c.red); // msg->AddInt32 ("color", c.green); // msg->AddInt32 ("color", c.blue); // editor->PostMessage (msg); // delete msg; } click = 1; } } if (click == 2 || buttons & B_SECONDARY_MOUSE_BUTTON || modifiers() & B_CONTROL_KEY) { click = 1; if (editorshowing) { // rgb_color c = color(); // BMessage *msg = new BMessage ('SetC'); // msg->AddInt32 ("color", c.red); // msg->AddInt32 ("color", c.green); // msg->AddInt32 ("color", c.blue); // editor->PostMessage (msg); // delete msg; } else { ShowEditor(); } } Invalidate(); Window()->Unlock(); }
void CMassView::MouseDown(BPoint where) // reacts to mouse clicks { long whichButtons = 1; // used for tracking which buttons are down Window()->CurrentMessage()->FindInt32("buttons", &whichButtons); // find out which buttons are down if (inGLMode && (whichButtons & B_SECONDARY_MOUSE_BUTTON)) // if we are in GL mode, and button 2 is down { float frameWidth = Frame().Width(), frameHeight = Frame().Height(); // find the width & height dragMode = dragBall; // drag the arcball to rotate HVect vNow; // vector type for passing to ball functions vNow.x = (2.0 * where.x - frameWidth)/frameWidth; // set the vector vNow.y = -(2.0 * where.y - frameHeight)/frameHeight; // in both dimensions Ball_Mouse(&ball, vNow); // and pass it to the Ball functions Ball_BeginDrag(&ball); // start dragging while (whichButtons) // loop until drop the mouse { snooze(20 * 1000); // snooze for 20 µs GetMouse(&where, (ulong *)&whichButtons, true); // get the mouse location, &c. vNow.x = (2.0 * where.x - frameWidth)/frameWidth; // set the vector vNow.y = -(2.0 * where.y - frameHeight)/frameHeight; // in both dimensions Ball_Mouse(&ball, vNow); // and pass it to the Ball functions Draw(Frame()); // redraw the entire frame } // end of while (whichButtons) Ball_EndDrag(&ball); // stop dragging } // end of case where dragging else if (acceptClicks) // if we have "accept" switched on { long row, col; // the board coordinates of the click if (!inGLMode) // if it's the regular board { row = where.y / CELL_SIZE; // calculate which row to look in col = where.x / CELL_SIZE; // and which column } // end of normal mode else { GLubyte theColour[4]; // array for retrieving "colour" LockGL(); // lock in preparation for drawing GLfloat mNow[16]; // local matrix for ball routines Ball_Update(&ball); // update the data for the ball Ball_Value(&ball, mNow); // retrieve the ball's position as a matrix glDisable(GL_LIGHTING); // disable lighting glShadeModel(GL_FLAT); // switch to flat shading glMatrixMode(GL_MODELVIEW); // make sure that we are set to the model matrix glClearColor(0.0, 0.0, 0.0, 1.0); // and set the "clear" colour to black glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the window to black glPushMatrix(); // push the GL stack to get a new matrix glLoadIdentity(); // load the identity matrix glTranslatef(0, 0, -600.0); // translate the model matrix glMultMatrixf(mNow); // multiply by this matrix glCallList(torusPickListID); // and call the display list glReadPixels(where.x, Frame().Height() - where.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, theColour); // read a single pixel at the mouse location glPopMatrix(); // pop the matrix back off the stack glEnable(GL_LIGHTING); // re-enable lighting glShadeModel(GL_SMOOTH); // and smoothness UnlockGL(); // unlock GL Draw(Frame()); // redraw the entire picture row = theColour[1] - 128; col = theColour[0] - 128; // retrieve the row & column // (background is black & returns -128) // printf("%d %d\n", row, col); return; } // end of GL mode code if (row < 0) return; // make sure it is a legal cell else if (row >= theBoard.getHeight()) return; // i.e. not off top or bottom if (col < 0) return; // same with left & right else if (col >= theBoard.getWidth()) return; BMessage *theMessage = new BMessage(CM_MSG_MOVE_CHOSEN); // create a message for it acceptClicks = false; // turn off "accept clicks" theMessage->AddInt32("row", row); theMessage->AddInt32("column", col); // add the coordinates to the message be_app->PostMessage(theMessage); // send the message off delete theMessage; // get rid of the message when done } // end of case where we accept clicks } // end of MouseDown()
static status_t usb_disk_device_added(usb_device newDevice, void **cookie) { TRACE("device_added(0x%08lx)\n", newDevice); disk_device *device = (disk_device *)malloc(sizeof(disk_device)); device->device = newDevice; device->removed = false; device->open_count = 0; device->interface = 0xff; device->current_tag = 0; device->sync_support = SYNC_SUPPORT_RELOAD; device->tur_supported = true; device->luns = NULL; // scan through the interfaces to find our bulk-only data interface const usb_configuration_info *configuration = gUSBModule->get_configuration(newDevice); if (configuration == NULL) { free(device); return B_ERROR; } for (size_t i = 0; i < configuration->interface_count; i++) { usb_interface_info *interface = configuration->interface[i].active; if (interface == NULL) continue; if (interface->descr->interface_class == 0x08 /* mass storage */ && interface->descr->interface_subclass == 0x06 /* SCSI */ && interface->descr->interface_protocol == 0x50 /* bulk-only */) { bool hasIn = false; bool hasOut = false; for (size_t j = 0; j < interface->endpoint_count; j++) { usb_endpoint_info *endpoint = &interface->endpoint[j]; if (endpoint == NULL || endpoint->descr->attributes != USB_ENDPOINT_ATTR_BULK) continue; if (!hasIn && (endpoint->descr->endpoint_address & USB_ENDPOINT_ADDR_DIR_IN)) { device->bulk_in = endpoint->handle; hasIn = true; } else if (!hasOut && (endpoint->descr->endpoint_address & USB_ENDPOINT_ADDR_DIR_IN) == 0) { device->bulk_out = endpoint->handle; hasOut = true; } if (hasIn && hasOut) break; } if (!(hasIn && hasOut)) continue; device->interface = interface->descr->interface_number; break; } } if (device->interface == 0xff) { TRACE_ALWAYS("no valid bulk-only interface found\n"); free(device); return B_ERROR; } mutex_init(&device->lock, "usb_disk device lock"); device->notify = create_sem(0, "usb_disk callback notify"); if (device->notify < B_OK) { mutex_destroy(&device->lock); free(device); return device->notify; } device->lun_count = usb_disk_get_max_lun(device) + 1; device->luns = (device_lun **)malloc(device->lun_count * sizeof(device_lun *)); for (uint8 i = 0; i < device->lun_count; i++) device->luns[i] = NULL; status_t result = B_OK; TRACE_ALWAYS("device reports a lun count of %d\n", device->lun_count); for (uint8 i = 0; i < device->lun_count; i++) { // create the individual luns present on this device device_lun *lun = (device_lun *)malloc(sizeof(device_lun)); if (lun == NULL) { result = B_NO_MEMORY; break; } device->luns[i] = lun; lun->device = device; lun->logical_unit_number = i; lun->should_sync = false; lun->media_present = true; lun->media_changed = true; usb_disk_reset_capacity(lun); // initialize this lun result = usb_disk_inquiry(lun); for (uint32 tries = 0; tries < 3; tries++) { status_t ready = usb_disk_test_unit_ready(lun); if (ready == B_OK || ready == B_DEV_NO_MEDIA) { if (ready == B_OK) { // TODO: check for write protection //if (usb_disk_mode_sense(lun) != B_OK) lun->write_protected = false; } break; } snooze(10000); } if (result != B_OK) break; } if (result != B_OK) { TRACE_ALWAYS("failed to initialize logical units\n"); usb_disk_free_device_and_luns(device); return result; } mutex_lock(&gDeviceListLock); device->device_number = 0; disk_device *other = gDeviceList; while (other != NULL) { if (other->device_number >= device->device_number) device->device_number = other->device_number + 1; other = (disk_device *)other->link; } device->link = (void *)gDeviceList; gDeviceList = device; gLunCount += device->lun_count; for (uint8 i = 0; i < device->lun_count; i++) sprintf(device->luns[i]->name, DEVICE_NAME, device->device_number, i); mutex_unlock(&gDeviceListLock); TRACE("new device: 0x%08lx\n", (uint32)device); *cookie = (void *)device; return B_OK; }
static void Virge_WriteMode(const DisplayModeEx& mode, VirgeRegRec& regRec) { // This function writes out all of the standard VGA and extended S3 registers // needed to setup a video mode. TRACE("Virge_WriteMode()\n"); SharedInfo& si = *gInfo.sharedInfo; // First reset GE to make sure nothing is going on. if (ReadCrtcReg(si.chipType == S3_VIRGE_VX ? 0x63 : 0x66) & 0x01) Virge_GEReset(mode); // As per databook, always disable STREAMS before changing modes. if ((ReadCrtcReg(0x67) & 0x0c) == 0x0c) { // STREAMS running, disable it VerticalRetraceWait(); WriteReg32(FIFO_CONTROL_REG, 0xC000); WriteCrtcReg(0x67, 0x00, 0x0c); // disable STREAMS processor } // Restore S3 extended regs. WriteCrtcReg(0x63, regRec.CR63); WriteCrtcReg(0x66, regRec.CR66); WriteCrtcReg(0x3a, regRec.CR3A); WriteCrtcReg(0x31, regRec.CR31); WriteCrtcReg(0x58, regRec.CR58); // Extended mode timings registers. WriteCrtcReg(0x53, regRec.CR53); WriteCrtcReg(0x5d, regRec.CR5D); WriteCrtcReg(0x5e, regRec.CR5E); WriteCrtcReg(0x3b, regRec.CR3B); WriteCrtcReg(0x3c, regRec.CR3C); WriteCrtcReg(0x43, regRec.CR43); WriteCrtcReg(0x65, regRec.CR65); WriteCrtcReg(0x6d, regRec.CR6D); // Restore the desired video mode with CR67. WriteCrtcReg(0x67, 0x50, 0xf0); // possible hardware bug on VX? snooze(10000); WriteCrtcReg(0x67, regRec.CR67 & ~0x0c); // Don't enable STREAMS // Other mode timing and extended regs. WriteCrtcReg(0x34, regRec.CR34); if (si.chipType != S3_TRIO_3D && si.chipType != S3_VIRGE_MX) { WriteCrtcReg(0x40, regRec.CR40); } if (S3_VIRGE_MX_SERIES(si.chipType)) { WriteCrtcReg(0x41, regRec.CR41); } WriteCrtcReg(0x42, regRec.CR42); WriteCrtcReg(0x45, regRec.CR45); WriteCrtcReg(0x51, regRec.CR51); WriteCrtcReg(0x54, regRec.CR54); // Memory timings. WriteCrtcReg(0x68, regRec.CR68); WriteCrtcReg(0x69, regRec.CR69); WriteCrtcReg(0x33, regRec.CR33); if (si.chipType == S3_TRIO_3D_2X || S3_VIRGE_GX2_SERIES(si.chipType) /* MXTESTME */ || S3_VIRGE_MX_SERIES(si.chipType) ) { WriteCrtcReg(0x85, regRec.CR85); } if (si.chipType == S3_VIRGE_DXGX) { WriteCrtcReg(0x86, regRec.CR86); } if ( (si.chipType == S3_VIRGE_GX2) || S3_VIRGE_MX_SERIES(si.chipType) ) { WriteCrtcReg(0x7b, regRec.CR7B); WriteCrtcReg(0x7d, regRec.CR7D); WriteCrtcReg(0x87, regRec.CR87); WriteCrtcReg(0x92, regRec.CR92); WriteCrtcReg(0x93, regRec.CR93); } if (si.chipType == S3_VIRGE_DXGX || S3_VIRGE_GX2_SERIES(si.chipType) || S3_VIRGE_MX_SERIES(si.chipType) || si.chipType == S3_TRIO_3D) { WriteCrtcReg(0x90, regRec.CR90); WriteCrtcReg(0x91, regRec.CR91); } WriteSeqReg(0x08, 0x06); // unlock extended sequencer regs // Restore extended sequencer regs for DCLK. WriteSeqReg(0x12, regRec.SR12); WriteSeqReg(0x13, regRec.SR13); if (S3_VIRGE_GX2_SERIES(si.chipType) || S3_VIRGE_MX_SERIES(si.chipType)) { WriteSeqReg(0x29, regRec.SR29); } if (S3_VIRGE_MX_SERIES(si.chipType)) { WriteSeqReg(0x54, regRec.SR54); WriteSeqReg(0x55, regRec.SR55); WriteSeqReg(0x56, regRec.SR56); WriteSeqReg(0x57, regRec.SR57); } WriteSeqReg(0x18, regRec.SR18); // Load new m,n PLL values for DCLK & MCLK. uint8 tmp = ReadSeqReg(0x15) & ~0x21; WriteSeqReg(0x15, tmp | 0x03); WriteSeqReg(0x15, tmp | 0x23); WriteSeqReg(0x15, tmp | 0x03); WriteSeqReg(0x15, regRec.SR15); if (si.chipType == S3_TRIO_3D) { WriteSeqReg(0x0a, regRec.SR0A); WriteSeqReg(0x0f, regRec.SR0F); } // Now write out CR67 in full, possibly starting STREAMS. VerticalRetraceWait(); WriteCrtcReg(0x67, 0x50); // For possible bug on VX?! snooze(10000); WriteCrtcReg(0x67, regRec.CR67); uint8 cr66 = ReadCrtcReg(0x66); WriteCrtcReg(0x66, cr66 | 0x80); WriteCrtcReg(0x3a, regRec.CR3A | 0x80); // Now, before we continue, check if this mode has the graphic engine ON. // If yes, then we reset it. if (si.chipType == S3_VIRGE_VX) { if (regRec.CR63 & 0x01) Virge_GEReset(mode); } else { if (regRec.CR66 & 0x01) Virge_GEReset(mode); } VerticalRetraceWait(); if (S3_VIRGE_GX2_SERIES(si.chipType) || S3_VIRGE_MX_SERIES(si.chipType) ) { WriteCrtcReg(0x85, 0x1f); // primary stream threshold } // Set the standard CRTC vga regs. WriteCrtcReg(0x11, 0x00, 0x80); // unlock CRTC reg's 0-7 by clearing bit 7 of cr11 for (int j = 0; j < NUM_ELEMENTS(regRec.CRTC); j++) { WriteCrtcReg(j, regRec.CRTC[j]); } // Setup HSYNC & VSYNC polarity and select clock source 2 (0x0c) for // programmable PLL. uint8 miscOutReg = 0x23 | 0x0c; if (!(mode.timing.flags & B_POSITIVE_HSYNC)) miscOutReg |= 0x40; if (!(mode.timing.flags & B_POSITIVE_VSYNC)) miscOutReg |= 0x80; WriteMiscOutReg(miscOutReg); WriteCrtcReg(0x66, cr66); WriteCrtcReg(0x3a, regRec.CR3A); return ; }
void TVideoPreviewView::DisplayThread() { FUNCTION("TVideoPreviewView::DisplayThread\n"); bigtime_t timeout = 5000; bigtime_t realTimeNow = 0; bigtime_t perfTimeNow = 0; bigtime_t halfPeriod = (bigtime_t) (500000./29.97); bool timeSourceRunning = false; while (!mDisplayQuit) { if (acquire_sem(mServiceLock) == B_NO_ERROR) { timeSourceRunning = TimeSource()->IsRunning(); realTimeNow = BTimeSource::RealTime(); perfTimeNow = TimeSource()->Now(); release_sem(mServiceLock); } snooze(timeout); if (timeSourceRunning) { // if we received a Stop, deal with it if (mStopping) { PROGRESS("VidConsumer::DisplayThread - STOP\n"); if (perfTimeNow >= mStopTime) { mRunning = false; mStopping = false; // deal with any pending Seek if (mSeeking) mSeeking = false; //if (mConnected) // SendDataStatus(B_DATA_NOT_AVAILABLE, mConnections[0], mStopTime); continue; } } // if we received a Seek, deal with it if (mSeeking) { PROGRESS("VidConsumer::DisplayThread - SEEK\n"); if (perfTimeNow >= mSeekTime) { PROGRESS("VidConsumer::DisplayThread - DO SEEK\n"); mSeeking = false; mDeltaTime = mMediaTime; continue; } } // if we received a Start, deal with it if (mStarting) { PROGRESS("BBt848Controllable::CaptureRun mStartTime = %.4f TimeNow = %.4f\n", (double)mStartTime/M1, (double)perfTimeNow/M1); if (perfTimeNow >= mStartTime) { mRunning = true; mStarting = false; mDeltaTime = mStartTime; //if (mConnected) // SendDataStatus(B_DATA_AVAILABLE, mConnections[0], mStartTime); continue; } } if (mRunning) { // check for buffer available. status_t err = acquire_sem_etc(mBufferAvailable, 1, B_TIMEOUT, halfPeriod * 2); if (err == B_TIMED_OUT || !mConnected) { ERROR("VidConsumer::DisplayThread - Error from acquire_sem_etc: 0x%lx\n", err); continue; } BBuffer* buffer = mBufferQueue->PopFirstBuffer(0); LOOP("Popped buffer %08x, Start time: %.4f, system time: %.4f diff: %.4f\n", buffer, (double) buffer->Header()->start_time/M1, (double) perfTimeNow/M1, (double) (buffer->Header()->start_time - perfTimeNow)/M1); // Display frame if we're in B_OFFLINE mode or // within +/- a half frame time of start time if ( (mRunMode == B_OFFLINE) || ((perfTimeNow > (buffer->Header()->start_time - halfPeriod)) && (perfTimeNow < (buffer->Header()->start_time + halfPeriod))) ) { uint32 bpp = (mColorspace == B_RGB32 ? 4 : 2); memcpy(m_Bitmap->Bits(), buffer->Data(), mRowBytes * mYSize * bpp); buffer->Header()->start_time = system_time(); buffer->Recycle(); bigtime_t t1 = system_time(); // Update view if (LockLooper()) { DrawBitmap(m_Bitmap, Bounds()); UnlockLooper(); } t1 = system_time() - t1; if (t1/M1 > .030) printf("Draw time = %.4f\n",t1/M1); continue; } else { // If we're too early, push frame back on stack if (perfTimeNow < buffer->Header()->start_time) { LOOP("push buffer back on stack!\n"); mBufferQueue->PushBuffer(buffer, buffer->Header()->start_time); release_sem(mBufferAvailable); continue; } else { // if we've already passed a half frame time past the buffer start time // and RunMode = INCREASE_LATENCY, increase latency and display the frame if ( (perfTimeNow > buffer->Header()->start_time) && (mRunMode == B_INCREASE_LATENCY)) { mMyLatency += halfPeriod; ERROR("VidConsumer::DisplayThread - Increased latency to: %.4f\n", mMyLatency); ERROR(" Performance time: %.4f @ %.4f\n", (double)buffer->Header()->start_time/M1, (double)perfTimeNow/M1); uint32 bpp = (mColorspace == B_RGB32 ? 4 : 2); memcpy(m_Bitmap->Bits(), buffer->Data(), mRowBytes * mYSize * bpp); buffer->Recycle(); // should send late notice if (LockLooper()) { DrawBitmap(m_Bitmap, Bounds()); UnlockLooper(); } continue; } else { // we're more than a half frame time past the buffer start time // drop the frame ERROR("VidConsumer::DisplayThread - dropped late frame: %.4f @ %.4f\n", (double)buffer->Header()->start_time/M1, (double)perfTimeNow/M1); buffer->Recycle(); // should send late notice continue; } } } } snooze(timeout); } else snooze(timeout); // if TimeSource stopped } // while (!mTimeToQuit) }
status_t AX88772Device::_SetupAX88772() { size_t actualLength = 0; // enable GPIO2 - magic from FreeBSD's if_axe uint16 GPIOs = GPIO_OO_2EN | GPIO_IO_2 | GPIO_RSE; status_t result = gUSBModule->send_request(fDevice, USB_REQTYPE_VENDOR | USB_REQTYPE_DEVICE_OUT, WRITE_GPIOS, GPIOs, 0, 0, 0, &actualLength); if (result != B_OK) { TRACE_ALWAYS("Error of wrinting GPIOs: %#010x\n", result); return result; } // select PHY bool useEmbeddedPHY = fMII.PHYID() == PHYIDEmbedded; uint16 selectPHY = useEmbeddedPHY ? SW_PHY_SEL_STATUS_INT : SW_PHY_SEL_STATUS_EXT; result = gUSBModule->send_request(fDevice, USB_REQTYPE_VENDOR | USB_REQTYPE_DEVICE_OUT, WRITE_PHY_SEL, selectPHY, 0, 0, 0, &actualLength); snooze(10000); TRACE("Selecting %s PHY[%#02x].\n", useEmbeddedPHY ? "embedded" : "external", selectPHY); if (result != B_OK) { TRACE_ALWAYS("Error of selecting PHY:%#010x\n", result); return result; } struct SWReset { uint16 reset; bigtime_t delay; } resetCommands[] = { // EMBEDDED PHY // power down and reset state, pin reset state { SW_RESET_CLR, 60000 }, // power down/reset state, pin operating state { SW_RESET_PRL | SW_RESET_IPPD, 150000 }, // power up, reset { SW_RESET_PRL, 0 }, // power up, operating { SW_RESET_PRL | SW_RESET_IPRL, 0 }, // EXTERNAL PHY // power down/reset state, pin operating state { SW_RESET_PRL | SW_RESET_IPPD, 0 } }; size_t from = useEmbeddedPHY ? 0 : 4; size_t to = useEmbeddedPHY ? 3 : 4; for (size_t i = from; i <= to; i++) { result = gUSBModule->send_request(fDevice, USB_REQTYPE_VENDOR | USB_REQTYPE_DEVICE_OUT, WRITE_SOFT_RESET, resetCommands[i].reset, 0, 0, 0, &actualLength); snooze(resetCommands[i].delay); if (result != B_OK) { TRACE_ALWAYS("Error of SW reset command %d:[%#04x]: %#010x\n", i, resetCommands[i].reset, result); return result; } } snooze(150000); result = WriteRXControlRegister(0); if (result != B_OK) { TRACE_ALWAYS("Error of writing %#04x RX Control:%#010x\n", 0, result); return result; } return B_OK; }
static void *handleDatagrams(void *parm) { /* Main loop for UDP datagram reception and handling. */ ReceiverThreadParms *rtp = (ReceiverThreadParms *) parm; char *procName = "udplsi"; char *buffer; int segmentLength; struct sockaddr_in fromAddr; socklen_t fromSize; snooze(1); /* Let main thread become interruptable. */ buffer = MTAKE(UDPLSA_BUFSZ); if (buffer == NULL) { putErrmsg("udplsi can't get UDP buffer.", NULL); ionKillMainThread(procName); return NULL; } /* Can now start receiving bundles. On failure, take * down the LSI. */ while (rtp->running) { fromSize = sizeof fromAddr; segmentLength = irecvfrom(rtp->linkSocket, buffer, UDPLSA_BUFSZ, 0, (struct sockaddr *) &fromAddr, &fromSize); switch (segmentLength) { case -1: putSysErrmsg("Can't acquire segment", NULL); ionKillMainThread(procName); /* Intentional fall-through to next case. */ case 1: /* Normal stop. */ rtp->running = 0; continue; } if (ltpHandleInboundSegment(buffer, segmentLength) < 0) { putErrmsg("Can't handle inbound segment.", NULL); ionKillMainThread(procName); rtp->running = 0; continue; } /* Make sure other tasks have a chance to run. */ sm_TaskYield(); } writeErrmsgMemos(); writeMemo("[i] udplsi receiver thread has ended."); /* Free resources. */ MRELEASE(buffer); return NULL; }
static void *receiveBundles(void *parm) { /* Main loop for bundle reception thread */ ReceiveThreadParms *parms = (ReceiveThreadParms *) parm; int threadRunning = 1; AcqWorkArea *work; char *buffer; buffer = MTAKE(TCPCLA_BUFSZ); if (buffer == NULL) { putErrmsg("tcpclo receiver can't get TCP buffer", NULL); return NULL; } work = bpGetAcqArea(parms->vduct); if (work == NULL) { putErrmsg("tcpclo receiver can't get acquisition work area", NULL); MRELEASE(buffer); return NULL; } iblock(SIGTERM); while (threadRunning && *(parms->cloRunning)) { if(*(parms->bundleSocket) < 0) { snooze(1); /*Retry later*/ continue; } if (bpBeginAcq(work, 0, NULL) < 0) { putErrmsg("Can't begin acquisition of bundle.", NULL); threadRunning = 0; continue; } switch (receiveBundleByTcpCL(*(parms->bundleSocket), work, buffer)) { case -1: putErrmsg("Can't acquire bundle.", NULL); pthread_mutex_lock(parms->mutex); closesocket(*(parms->bundleSocket)); *(parms->bundleSocket) = -1; pthread_mutex_unlock(parms->mutex); continue; case 0: /* Shutdown message */ /* Go back to the start of the while loop */ pthread_mutex_lock(parms->mutex); closesocket(*(parms->bundleSocket)); *(parms->bundleSocket) = -1; pthread_mutex_unlock(parms->mutex); continue; default: break; /* Out of switch. */ } if (bpEndAcq(work) < 0) { putErrmsg("Can't end acquisition of bundle.", NULL); threadRunning = 0; } /* Make sure other tasks have a chance to run. */ sm_TaskYield(); } /* End of receiver thread; release resources. */ bpReleaseAcqArea(work); MRELEASE(buffer); return NULL; }
void AmFilterTest1::TestBasic01() { int i; printf("Making a vector.\n"); vector<int, allocator<int> > myVect(2); myVect[0] = 1; printf("Making a map.\n"); map< int, int, less<int>, allocator<int> > myMap; myMap[0] = 1; printf("Creating example filter object...\n"); fflush(stdout); ArpExampleFilterAddon* exAddon = new ArpExampleFilterAddon; AmFilterHolder* exHolder = new AmFilterHolder; exHolder->SetFilter(exAddon->NewInstance(exHolder)); printf("Creating BSynth filter object...\n"); fflush(stdout); #if 1 AmConsumerFilterAddon* syAddon = new AmConsumerFilterAddon(); #else AmConsumerFilterAddon* syAddon = new AmConsumerFilterAddon("<midi port name>"); #endif /* NOTE: The second consumer filter is not valid. You need to * supply the name of the midi port you want to use. */ AmFilterHolder* syHolder = new AmFilterHolder; syHolder->SetFilter(syAddon->NewInstance(syHolder)); printf("Creating debug filter object...\n"); fflush(stdout); ArpDebugFilterAddon* dbAddon = new ArpDebugFilterAddon(true); AmFilterHolder* dbHolder = new AmFilterHolder; dbHolder->SetFilter(dbAddon->NewInstance(dbHolder)); printf("Attaching BSynth filter to example filter...\n"); fflush(stdout); exHolder->AddSuccessor(syHolder); printf("Attaching debug filter to BSynth filter...\n"); fflush(stdout); syHolder->AddSuccessor(dbHolder); printf("Creating a chain of NoteOn events...\n"); fflush(stdout); AmEventI* evHead=NULL; AmEventI* evTail=NULL; for( i=1; i<=4; i++ ) { { AmProgramChange* ev = new AmProgramChange((i-1)*10, PPQN*4*i-((PPQN*3)/2)); if( !evHead ) { evHead = ev; } else { evTail->AppendEvent(ev); } ev->SetNextFilter(exHolder); evTail = ev; } { AmNoteOn* ev = new AmNoteOn(60+5*i,100,PPQN*4*i); ev->SetRelVelocity(80); if( !evHead ) { evHead = ev; } else { evTail->AppendEvent(ev); } ev->SetNextFilter(exHolder); evTail = ev; } { AmTempoChange* ev = new AmTempoChange(120 + 40*i,PPQN*4*i); if( !evHead ) { evHead = ev; } else { evTail->AppendEvent(ev); } ev->SetNextFilter(exHolder); evTail = ev; } } printf("Initial Event Chain:\n"); fflush(stdout); PrintEventChain(evHead); fflush(stdout); printf("Processing filters on event chain...\n"); fflush(stdout); evHead = ArpExecFilters(evHead); printf("Final event chain:\n"); fflush(stdout); PrintEventChain(evHead); fflush(stdout); printf("Performing the song!\n"); fflush(stdout); { AmPerformer p; p.Start(evHead); // this is a bit of a hack to wait for it to finish; // it will be better when we flesh out the performer // interface to be able to send messages. do { snooze(1 * 1000000); // wait for a sec } while( p.IsPlaying() ); } fflush(stdout); printf("Placing the BSynth filter in its own list...\n"); fflush(stdout); exHolder->RemoveSuccessor(syHolder); syHolder->RemoveSuccessor(dbHolder); printf("Creating a chain of sixteenth notes...\n"); fflush(stdout); evHead = evTail = new AmProgramChange(B_KALIMBA, 0); evTail->SetNextFilter(syHolder); evTail->AppendEvent(new AmTempoChange(480, 0)); evTail = evTail->TailEvent(); evTail->SetNextFilter(syHolder); for( i=1; i<=4*4*4; i++ ) { { AmNoteOn* ev = new AmNoteOn(70+2*(i/(4*4)),100,PPQN*i/4); ev->SetDuration(PPQN/8); ev->SetRelVelocity(80); if( !evHead ) { evHead = ev; } else { evTail->AppendEvent(ev); } ev->SetNextFilter(syHolder); evTail = ev; } } printf("Performing the next song!\n"); fflush(stdout); { AmPerformer p; p.Start(evHead); // this is a bit of a hack to wait for it to finish; // it will be better when we flesh out the performer // interface to be able to send messages. do { snooze(1 * 1000000); // wait for a sec } while( p.IsPlaying() ); } fflush(stdout); printf("Deleting filters -- WHICH FOR SOME REASON IS CRASHING, SO IT'S BEEN REMOVED.\n"); #if 0 exHolder->Delete(); exAddon->RemReference(); syHolder->Delete(); syAddon->RemReference(); dbHolder->Delete(); dbAddon->RemReference(); #endif DoBigTest(); printf("Repeating test...\n"); fflush(stdout); DoBigTest(); }
void BTranslatorRoster::Private::MessageReceived(BMessage* message) { switch (message->what) { case B_NODE_MONITOR: { BAutolock locker(this); printf("translator roster node monitor: "); message->PrintToStream(); int32 opcode; if (message->FindInt32("opcode", &opcode) != B_OK) return; switch (opcode) { case B_ENTRY_CREATED: { const char* name; node_ref nodeRef; if (message->FindInt32("device", &nodeRef.device) != B_OK || message->FindInt64("directory", &nodeRef.node) != B_OK || message->FindString("name", &name) != B_OK) break; // TODO: make this better (possible under Haiku) snooze(100000); // let the font be written completely before trying to // open it _EntryAdded(nodeRef, name); break; } case B_ENTRY_MOVED: { // has the entry been moved into a monitored directory or // has it been removed from one? const char* name; node_ref toNodeRef; node_ref fromNodeRef; node_ref nodeRef; if (message->FindInt32("device", &nodeRef.device) != B_OK || message->FindInt64("to directory", &toNodeRef.node) != B_OK || message->FindInt64("from directory", (int64*)&fromNodeRef.node) != B_OK || message->FindInt64("node", (int64*)&nodeRef.node) != B_OK || message->FindString("name", &name) != B_OK) break; fromNodeRef.device = nodeRef.device; toNodeRef.device = nodeRef.device; // Do we know this one yet? translator_item* item = _FindTranslator(nodeRef); if (item == NULL) { // it's a new one! if (_IsKnownDirectory(toNodeRef)) _EntryAdded(toNodeRef, name); break; } if (!_IsKnownDirectory(toNodeRef)) { // translator got removed _RemoveTranslators(&nodeRef); break; } // the name may have changed item->ref.set_name(name); item->ref.directory = toNodeRef.node; if (_IsKnownDirectory(fromNodeRef) && _IsKnownDirectory(toNodeRef)) { // TODO: we should rescan for the name, there might be // name clashes with translators in other directories // (as well as old ones revealed) break; } break; } case B_ENTRY_REMOVED: { node_ref nodeRef; uint64 directoryNode; if (message->FindInt32("device", &nodeRef.device) != B_OK || message->FindInt64("directory", (int64*)&directoryNode) != B_OK || message->FindInt64("node", &nodeRef.node) != B_OK) break; translator_item* item = _FindTranslator(nodeRef); if (item != NULL) _RemoveTranslators(&nodeRef); break; } } break; } default: BHandler::MessageReceived(message); break; } }
int bpclock(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10) { #else int main(int argc, char *argv[]) { #endif Sdr sdr; BpDB *bpConstants; int state = 1; time_t currentTime; if (bpAttach() < 0) { putErrmsg("bpclock can't attach to BP.", NULL); return 1; } sdr = getIonsdr(); bpConstants = getBpConstants(); isignal(SIGTERM, shutDown); /* Main loop: wait for event occurrence time, then * execute applicable events. */ oK(_running(&state)); writeMemo("[i] bpclock is running."); while (_running(NULL)) { /* Sleep for 1 second, then dispatch all events * whose executions times have now been reached. */ snooze(1); currentTime = getUTCTime(); if (dispatchEvents(sdr, bpConstants->timeline, currentTime) < 0) { putErrmsg("Can't dispatch events.", NULL); state = 0; /* Terminate loop. */ oK(_running(&state)); continue; } /* Also adjust throttles in response to rate * changes noted in the shared ION database. */ if (adjustThrottles() < 0) { putErrmsg("Can't adjust throttles.", NULL); state = 0; /* Terminate loop. */ oK(_running(&state)); continue; } /* Then apply rate control. */ applyRateControl(sdr); } writeErrmsgMemos(); writeMemo("[i] bpclock has ended."); ionDetach(); return 0; }
/*program the pixpll - frequency in kHz*/ status_t eng_dac2_set_pix_pll(display_mode target) { uint8 m=0,n=0,p=0; // uint time = 0; float pix_setting, req_pclk; status_t result; /* we offer this option because some panels have very tight restrictions, * and there's no overlapping settings range that makes them all work. * note: * this assumes the cards BIOS correctly programmed the panel (is likely) */ //fixme: when VESA DDC EDID stuff is implemented, this option can be deleted... if (si->ps.tmds2_active && !si->settings.pgm_panel) { LOG(4,("DAC2: Not programming DFP refresh (specified in skel.settings)\n")); return B_OK; } /* fix a DVI or laptop flatpanel to 60Hz refresh! */ /* Note: * The pixelclock drives the flatpanel modeline, not the CRTC modeline. */ if (si->ps.tmds2_active) { LOG(4,("DAC2: Fixing DFP refresh to 60Hz!\n")); /* use the panel's modeline to determine the needed pixelclock */ target.timing.pixel_clock = si->ps.p2_timing.pixel_clock; } req_pclk = (target.timing.pixel_clock)/1000.0; LOG(4,("DAC2: Setting PIX PLL for pixelclock %f\n", req_pclk)); /* signal that we actually want to set the mode */ result = eng_dac2_pix_pll_find(target,&pix_setting,&m,&n,&p, 1); if (result != B_OK) { return result; } /*reprogram (disable,select,wait for stability,enable)*/ // DXIW(PIXCLKCTRL,(DXIR(PIXCLKCTRL)&0x0F)|0x04); /*disable the PIXPLL*/ // DXIW(PIXCLKCTRL,(DXIR(PIXCLKCTRL)&0x0C)|0x01); /*select the PIXPLL*/ /* program new frequency */ DAC2W(PIXPLLC, ((p << 16) | (n << 8) | m)); /* program 2nd set N and M scalers if they exist (b31=1 enables them) */ if (si->ps.ext_pll) DAC2W(PIXPLLC2, 0x80000401); /* Wait for the PIXPLL frequency to lock until timeout occurs */ //fixme: do NV cards have a LOCK indication bit?? /* while((!(DXIR(PIXPLLSTAT)&0x40)) & (time <= 2000)) { time++; snooze(1); } if (time > 2000) LOG(2,("DAC: PIX PLL frequency not locked!\n")); else LOG(2,("DAC: PIX PLL frequency locked\n")); DXIW(PIXCLKCTRL,DXIR(PIXCLKCTRL)&0x0B); //enable the PIXPLL */ //for now: /* Give the PIXPLL frequency some time to lock... */ snooze(1000); LOG(2,("DAC2: PIX PLL frequency should be locked now...\n")); return B_OK; }
void BubbleHelper::Helper() { // Wait until the BApplication becomes valid, in case // someone creates this as a global variable. while(!be_app_messenger.IsValid()) snooze(200000); // wait a little longer, until the BApplication is really up to speed while(be_app->IsLaunching()) snooze(200000); textwin=new BWindow(BRect(-100,-100,-50,-50),"",B_BORDERED_WINDOW_LOOK, B_FLOATING_ALL_WINDOW_FEEL, B_NOT_MOVABLE|B_AVOID_FOCUS); textview=new BTextView(BRect(0,0,50,50),"",BRect(2,2,48,48),B_FOLLOW_ALL_SIDES,B_WILL_DRAW); textview->MakeEditable(false); textview->MakeSelectable(false); textview->SetWordWrap(false); #ifdef __HAIKU__ textview->SetHighColor(ui_color(B_TOOL_TIP_TEXT_COLOR)); textview->SetLowColor(ui_color(B_TOOL_TIP_BACKGROUND_COLOR)); textview->SetViewColor(ui_color(B_TOOL_TIP_BACKGROUND_COLOR)); #else textview->SetLowColor(240,240,100); textview->SetViewColor(240,240,100); textview->SetHighColor(0,0,0); #endif textwin->AddChild(textview); textwin->Run(); textwin->Lock(); textwin->Activate(false); rename_thread(textwin->Thread(),"bubble"); textwin->Unlock(); ulong delaycounter=0; BPoint lastwhere; while(be_app_messenger.IsValid()) { BPoint where; ulong buttons; if(enabled) { if(textwin->Lock()) { textview->GetMouse(&where,&buttons); textview->ConvertToScreen(&where); if(lastwhere!=where || buttons) { delaycounter=0; } else { // mouse didn't move if(delaycounter++>5) { delaycounter=0; // mouse didn't move for a while BView *view=FindView(where); char *text=NULL; while(view && (text=GetHelp(view))==NULL) view=view->Parent(); if(text) { DisplayHelp(text,where); // wait until mouse moves out of view, or wait // for timeout long displaycounter=0; BPoint where2; long displaytime=max_c(20,strlen(text)); do { textwin->Unlock(); snooze(100000); if(!textwin->Lock()) goto end; //window is apparently gone textview->GetMouse(&where2,&buttons); textview->ConvertToScreen(&where2); } while(!buttons && where2==where && (displaycounter++<displaytime)); HideBubble(); do { textwin->Unlock(); snooze(100000); if(!textwin->Lock()) goto end; //window is apparently gone textview->GetMouse(&where2,&buttons); textview->ConvertToScreen(&where2); } while(where2==where); } } } lastwhere=where; textwin->Unlock(); } } end: snooze(100000); } // (this thread normally gets killed by the destructor before arriving here) }
void TLevelsSlider::MouseDown(BPoint where) { // Check for which button is pressed uint32 buttons = 0; Window()->CurrentMessage()->FindInt32("buttons", (long *)&buttons); // Determine which button has been clicked switch(buttons) { case B_PRIMARY_MOUSE_BUTTON: { const BRect bounds = Bounds(); // Get old positions BRect oldLeftRect = m_LeftSliderRect; BRect oldRightRect = m_RightSliderRect; // Move both left and right slider under mouse const uint32 leftHeight = m_LeftSlider->Bounds().IntegerHeight(); const uint32 rightHeight = m_RightSlider->Bounds().IntegerHeight(); m_LeftSliderRect.top = where.y - leftHeight/2; m_LeftSliderRect.bottom = m_LeftSliderRect.top + leftHeight; m_RightSliderRect.top = where.y - rightHeight/2; m_RightSliderRect.bottom = m_RightSliderRect.top + rightHeight; // Now clip the location of the slider if out of bounds ClipSliders(); // Clean up old position BRect updateRect = oldLeftRect; updateRect.right = oldRightRect.right; Draw(Bounds()); // Draw updated position DrawLeftSlider(); DrawRightSlider(); // Update the volumes UpdateVolumes(where); // Wait a while for the mouse button to be realeased snooze(100 * 1000); // Is button down? They are dragging or resizing the cue... // Check to see if button is down Window()->CurrentMessage()->FindInt32("buttons", (long *)&buttons); if (buttons) { //StartMouseWatcher(this); TrackSliders(); } } break; // User is dragging one half of the slider case B_SECONDARY_MOUSE_BUTTON: { const BRect bounds = Bounds(); // Determine area mouse is in for slider drag // // Left Side if (where.x <= bounds.Width()/2) { // Get old positions BRect oldRect = m_LeftSliderRect; // Move both left slider under mouse const uint32 leftHeight = m_LeftSlider->Bounds().IntegerHeight(); m_LeftSliderRect.top = where.y - leftHeight/2; m_LeftSliderRect.bottom = m_LeftSliderRect.top + leftHeight; // Now clip the location of the slider if out of bounds ClipLeftSlider(); // Clean up old position Draw(oldRect); // Draw updated position DrawLeftSlider(); // Update the volume UpdateLeftVolume(where); // Wait a while for the mouse button to be realeased snooze(100 * 1000); // Is button down? They are dragging or resizing the cue... // Check to see if button is down Window()->CurrentMessage()->FindInt32("buttons", (long *)&buttons); if (buttons) { TrackLeftSlider(); } } // Right Side else { const BRect bounds = Bounds(); // Get old positions BRect oldRect = m_RightSliderRect; // Move both left and right slider under mouse const uint32 rightHeight = m_RightSlider->Bounds().IntegerHeight(); m_RightSliderRect.top = where.y - rightHeight/2; m_RightSliderRect.bottom = m_RightSliderRect.top + rightHeight; // Now clip the location of the slider if out of bounds ClipRightSlider(); // Clean up old position Draw(oldRect); // Draw updated position DrawRightSlider(); // Update the volume UpdateRightVolume(where); // Wait a while for the mouse button to be realeased snooze(100 * 1000); // Is button down? They are dragging or resizing the cue... // Check to see if button is down Window()->CurrentMessage()->FindInt32("buttons", (long *)&buttons); if (buttons) { TrackRightSlider(); } } } break; } }
static void SetClockRegisters(const DisplayModeEx& mode) { SharedInfo& si = *gInfo.sharedInfo; M64_Params& params = si.m64Params; int p; int postDiv; bool extendedDiv = false; uint32 pixelClock = mode.timing.pixel_clock; if (pixelClock > params.maxPixelClock) pixelClock = params.maxPixelClock; double q = ((pixelClock / 10.0) * params.refDivider) / (2.0 * params.refFreq); if (si.chipType >= MACH64_264VTB) { if (q > 255) { TRACE("SetClockRegisters(): Warning: q > 255\n"); q = 255; p = 0; postDiv = 1; } else if (q > 127.5) { p = 0; postDiv = 1; } else if (q > 85) { p = 1; postDiv = 2; } else if (q > 63.75) { p = 0; postDiv = 3; extendedDiv = true; } else if (q > 42.5) { p = 2; postDiv = 4; } else if (q > 31.875) { p = 2; postDiv = 6; extendedDiv = true; } else if (q > 21.25) { p = 3; postDiv = 8; } else if (q >= 10.6666666667) { p = 3; postDiv = 12; extendedDiv = true; } else { TRACE("SetClockRegisters(): Warning: q < 10.66666667\n"); p = 3; postDiv = 12; extendedDiv = true; } } else { if (q > 255) { TRACE("SetClockRegisters(): Warning: q > 255\n"); q = 255; p = 0; } else if (q > 127.5) p = 0; else if (q > 63.75) p = 1; else if (q > 31.875) p = 2; else if (q >= 16) p = 3; else { TRACE("SetClockRegisters(): Warning: q < 16\n"); p = 3; } postDiv = 1 << p; } uint8 fbDiv = uint8(q * postDiv); // With some chips such as those with ID's 4750 & 475A, the display has // ripples when using resolution 1440x900 at 60 Hz refresh rate. // Decrementing fbDiv by 1 seems to fix this problem. if (mode.timing.h_display == 1440 && pixelClock < 108000) fbDiv--; int clkNum = params.clockNumberToProgram; OUTREG8(CLOCK_CNTL, clkNum | CLOCK_STROBE); // Temporarily switch to accelerator mode. uint32 crtc_gen_cntl = INREG(CRTC_GEN_CNTL); if (!(crtc_gen_cntl & CRTC_EXT_DISP_EN)) OUTREG(CRTC_GEN_CNTL, crtc_gen_cntl | CRTC_EXT_DISP_EN); // Reset VCLK generator. uint8 vclkCntl = Mach64_GetPLLReg(PLL_VCLK_CNTL); Mach64_SetPLLReg(PLL_VCLK_CNTL, vclkCntl | PLL_VCLK_RESET); // Set post-divider. uint8 tmp = Mach64_GetPLLReg(PLL_VCLK_POST_DIV); Mach64_SetPLLReg(PLL_VCLK_POST_DIV, (tmp & ~(0x03 << (2 * clkNum))) | (p << (2 * clkNum))); // Set feedback divider. Mach64_SetPLLReg(PLL_VCLK0_FB_DIV + clkNum, fbDiv); // Set extended post-divider. if (si.chipType >= MACH64_264VTB) { tmp = Mach64_GetPLLReg(PLL_XCLK_CNTL); if (extendedDiv) Mach64_SetPLLReg(PLL_XCLK_CNTL, tmp | (0x10 << clkNum)); else Mach64_SetPLLReg(PLL_XCLK_CNTL, tmp & ~(0x10 << clkNum)); } // End VCLK generator reset. Mach64_SetPLLReg(PLL_VCLK_CNTL, vclkCntl & ~PLL_VCLK_RESET); snooze(5000); INREG8(DAC_W_INDEX); // Clear DAC counter if (!(crtc_gen_cntl & CRTC_EXT_DISP_EN)) OUTREG(CRTC_GEN_CNTL, crtc_gen_cntl); // Restore register // Save parameters that will be used for computing the DSP parameters. params.vClkPostDivider = postDiv; params.vClkFeedbackDivider = fbDiv; return; }
int main(int argc, char** argv) { bool periodically = false; bigtime_t rate = 1000000LL; int c; while ((c = getopt_long(argc, argv, "pr:h", kLongOptions, NULL)) != -1) { switch (c) { case 0: break; case 'p': periodically = true; break; case 'r': rate = atoi(optarg) * 1000LL; if (rate <= 0) { fprintf(stderr, "%s: Invalid rate: %s\n", kProgramName, optarg); return 1; } periodically = true; break; case 'h': usage(0); break; default: usage(1); break; } } system_memory_info info; status_t status = __get_system_info_etc(B_MEMORY_INFO, &info, sizeof(system_memory_info)); if (status != B_OK) { fprintf(stderr, "%s: cannot get system info: %s\n", kProgramName, strerror(status)); return 1; } printf("max memory:\t\t%Lu\n", info.max_memory); printf("free memory:\t\t%Lu\n", info.free_memory); printf("needed memory:\t\t%Lu\n", info.needed_memory); printf("block cache memory:\t%Lu\n", info.block_cache_memory); printf("max swap space:\t\t%Lu\n", info.max_swap_space); printf("free swap space:\t%Lu\n", info.free_swap_space); printf("page faults:\t\t%lu\n", info.page_faults); if (periodically) { puts("\npage faults used memory used swap block cache"); system_memory_info lastInfo = info; while (true) { snooze(rate); __get_system_info_etc(B_MEMORY_INFO, &info, sizeof(system_memory_info)); printf("%11ld %11Ld %11Ld %11Ld\n", (int32)info.page_faults - lastInfo.page_faults, (info.max_memory - info.free_memory) - (lastInfo.max_memory - lastInfo.free_memory), (info.max_swap_space - info.free_swap_space) - (lastInfo.max_swap_space - lastInfo.free_swap_space), info.block_cache_memory - lastInfo.block_cache_memory); lastInfo = info; } } return 0; }
status_t GlSpectrumAnalyzerWindow::Render(const short *buf, int32 framecount) { if(!keeprunning) return B_ERROR; /* if (needResize) FrameResized(float(Frame().IntegerWidth() + 1), float(Frame().IntegerHeight() + 1)); */ // fprintf(stderr, "GlSpectrumAnalyzerWindow::Render()\n"); const uint16 *fft = controller->GetFFTForBuffer(buf,SP_MONO_CHANNEL); // The actual OpenGL scene. MakeCurrent(); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glLoadIdentity(); #if 1 // Move 5.0 units into the screen. // glTranslatef( 0.0, 0.0, -5.0 ); glTranslatef( 0.0, 0.0, -35.0 ); // Rotate before drawing the cube. glRotatef( xrot, 1.0, 0.0, 0.0 ); // X rotation glRotatef( yrot, 0.0, 1.0, 0.0 ); // Y rotation glRotatef( zrot, 0.0, 0.0, 1.0 ); // Z rotation glTranslatef( -19.0, 0.0, 0.0 ); for(int x=0;x<20;x++) { uint32 total=0; for(int i=0;i<3+x;i++) total+=*fft++; total/=4*512-x*90; if(total>110) total=110; if(total<lastpeak[x]) total=(total+lastpeak[x]*3)/4; lastpeak[x]=total; if(total) { //glColor3f(0.0, 1.0, 0.0); glColor3f(0.0, (float(total+100) / (110+100)), 0.0); float cubeHeight = total / 11; // Create a bar myglVerticalBar(0.8, 0.8, 0.0, cubeHeight); } if(total>peak[x]) { peak[x]=total; peakdelay[x]=20; } if(peakdelay[x]) peakdelay[x]--; if(peakdelay[x]==0) if(peak[x]) peak[x]--; glColor3f(1.0, 0.0, 0.0); float peakHeight = (peak[x] + 2) / 11; myglVerticalBar(0.8, 0.8, peakHeight, peakHeight+0.1); glTranslatef( 2.0, 0.0, 0.0 ); } /* glColor3f(1.0f,1.0f,0.0f); // Set Color To Yellow glTranslated(10,10,0); // Position The Text (0,0 - Bottom Left) int set = 0; glListBase(64-32+(128*set)); // Choose The Font Set (0 or 1) glCallLists(strlen(name),GL_UNSIGNED_BYTE, name); // Write The Text To The Screen */ #endif ReleaseCurrent(); SwapBuffers(); // show what we drew, else it's useless :-) snooze(5000); // Rotate things a bit. /* xrot += 0.3; yrot += 0.2; zrot += 0.4; */ xrot += 0.3; yrot += 0.4; zrot += 0.2; /* bView->Sync(); rView->DrawBitmapAsync(bitmap,bitmap->Bounds(),rView->Bounds()); rView->Flush(); rView->Sync(); bitmap->Unlock(); */ // fprintf(stderr, "<GlSpectrumAnalyzerWindow::Render()\n"); return B_OK; }