bool wxInitQT() { #ifndef __WXMAC__ int nError; //-2093 no dll if ((nError = InitializeQTML(0)) != noErr) { wxLogSysError(wxString::Format(wxT("Couldn't Initialize Quicktime-%i"), nError)); return false; } #endif EnterMovies(); return true; }
BOOL QTCode_DoQTInit() { /* Initialize QuickTime Media Layer */ if (InitializeQTML(0L) != 0) { return (FALSE); } /* Initialize QuickTime */ if (EnterMovies() != 0) { return (FALSE); } return (TRUE); }
static OSErr QD3DSupport_QuickTimeInit (void) { #if TARGET_OS_WIN32 OSErr err; err = InitializeQTML(0L); if (err != noErr) { return err; } #endif return ( EnterMovies () ); }
static bool Setup() { OSErr err; #ifdef _WIN32 err = InitializeQTML(0L); if(err) return false; #ifdef VIBREZ qtmutex = CreateMutex(NULL,FALSE,"Local\\Quicktime"); if(!qtmutex) return false; #endif #endif err = EnterMovies(); if(err) return false; Add(New); return true; }
/* WinMain */ int CALLBACK WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { MSG msg; HANDLE hAccel; // Store our module handle ghModule = GetModuleHandle(NULL); // Initialize QuickTime Media Layer InitializeQTML(0); // Initialize QuickTime EnterMovies(); // Initialize the app if (!InitializeApp()) { MessageBox(ghwndMain, "MDI: InitializeApp failure!", "Error", MB_OK); return 0; } // Load our accelerator keys if (!(hAccel = LoadAccelerators (ghModule, MAKEINTRESOURCE(ACCEL_ID)))) MessageBox(ghwndMain, "MDI: Load Accel failure!", "Error", MB_OK); // Parse the command line for drag and drop ParseCmdLinePriv(NULL); // Loop for messages while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator( ghwndMain, hAccel, &msg) && !TranslateMDISysAccel( ghwndClient, &msg) ) { TranslateMessage(&msg); DispatchMessage(&msg); } } // Deinitialize QuickTime ExitMovies(); // Deinitialize QTML TerminateQTML(); return TRUE; }
inline bool wxInitQT () { if (wxIsQuickTime4Installed()) { #ifndef __WXMAC__ int nError; //-2093 no dll if ((nError = InitializeQTML(0)) != noErr) wxLogSysError(wxString::Format(wxT("Couldn't Initialize Quicktime-%i"), nError)); #endif EnterMovies(); return true; } else { wxLogSysError(wxT("Quicktime is not installed, or Your Version of Quicktime is <= 4.")); return false; } }
BOOL CSimplePlayerMFCApp::InitInstance() { // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. // Initialize QTML and QuickTime InitializeQTML(0); EnterMovies(); #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif LoadStdProfileSettings(0); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CSimplePlayerMFCDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CSimplePlayerMFCView)); AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE; return TRUE; }
static bool initGemWin(void) { # ifdef HAVE_QUICKTIME OSErr err = noErr; // Initialize QuickTime Media Layer err = InitializeQTML(0); if (err) { error("GEM Man: Could not initialize quicktime: error %d\n", err); return false; } // Initialize QuickTime EnterMovies(); if (err) { error("GEM Man: Could not initialize quicktime: error %d\n", err); return false; } verbose(1, "Gem Man: QT init OK"); # endif /* HAVE_QUICKTIME */ return true; }
int main(void) { void *handler; ComponentDescription desc; Component (*FindNextComponent)(Component prev,ComponentDescription* desc); long (*CountComponents)(ComponentDescription* desc); OSErr (*InitializeQTML)(long flags); OSErr (*EnterMovies)(void); OSErr ret; Setup_LDT_Keeper(); handler = LoadLibraryA("/usr/local/lib/codecs/qtmlClient.dll"); printf("***************************\n"); InitializeQTML = 0x1000c870; //GetProcAddress(handler, "InitializeQTML"); EnterMovies = 0x10003ac0; //GetProcAddress(handler, "EnterMovies"); FindNextComponent = 0x1000d5f0; //GetProcAddress(handler, "FindNextComponent"); CountComponents = 0x1000d5d0; //GetProcAddress(handler, "CountComponents"); // = GetProcAddress(handler, ""); printf("handler: %p, funcs: %p %p %p, %p\n", handler, InitializeQTML, EnterMovies, FindNextComponent,CountComponents); ret=InitializeQTML(0); printf("InitializeQTML->%d\n",ret); ret=EnterMovies(); printf("EnterMovies->%d\n",ret); memset(&desc,0,sizeof(desc)); desc.componentType= (((unsigned char)'S')<<24)| (((unsigned char)'V')<<16)| (((unsigned char)'Q')<<8)| (((unsigned char)'5')); desc.componentSubType=0; desc.componentManufacturer=0; desc.componentFlags=0; desc.componentFlagsMask=0; printf("Count = %ld\n",CountComponents(&desc)); exit(0); }
// init driver static int init(sh_video_t *sh){ OSErr result = 1; int extradata_size = sh->bih ? sh->bih->biSize - sizeof(*sh->bih) : 0; void *extradata = sh->bih + 1; if (!sh->ImageDesc) mp_msg(MSGT_DECVIDEO,MSGL_ERR,"sh->ImageDesc not set, try -demuxer mov if this fails.\n"); #ifndef CONFIG_QUICKTIME #ifdef WIN32_LOADER Setup_LDT_Keeper(); #endif //preload quicktime.qts to avoid the problems caused by the hardcoded path inside the dll qtime_qts = LoadLibraryA("QuickTime.qts"); if(!qtime_qts){ mp_msg(MSGT_DECVIDEO,MSGL_ERR,"unable to load QuickTime.qts\n" ); return 0; } handler = LoadLibraryA("qtmlClient.dll"); if(!handler){ mp_msg(MSGT_DECVIDEO,MSGL_ERR,"unable to load qtmlClient.dll\n"); return 0; } InitializeQTML = (OSErr (*)(long))GetProcAddress(handler, "InitializeQTML"); EnterMovies = (OSErr (*)(void))GetProcAddress(handler, "EnterMovies"); ExitMovies = (void (*)(void))GetProcAddress(handler, "ExitMovies"); DecompressSequenceBegin = (OSErr (*)(ImageSequence*,ImageDescriptionHandle,CGrafPtr,void *,const Rect *,MatrixRecordPtr,short,RgnHandle,CodecFlags,CodecQ,DecompressorComponent))GetProcAddress(handler, "DecompressSequenceBegin"); DecompressSequenceFrameS = (OSErr (*)(ImageSequence,Ptr,long,CodecFlags,CodecFlags*,ICMCompletionProcRecordPtr))GetProcAddress(handler, "DecompressSequenceFrameS"); GetGWorldPixMap = (PixMapHandle (*)(GWorldPtr))GetProcAddress(handler, "GetGWorldPixMap"); QTNewGWorldFromPtr = (OSErr(*)(GWorldPtr *,OSType,const Rect *,CTabHandle,void*,GWorldFlags,void *,long))GetProcAddress(handler, "QTNewGWorldFromPtr"); NewHandleClear = (OSErr(*)(Size))GetProcAddress(handler, "NewHandleClear"); DisposeHandle = (void (*)(Handle))GetProcAddress(handler, "DisposeHandle"); DisposeGWorld = (void (*)(GWorldPtr))GetProcAddress(handler, "DisposeGWorld"); CDSequenceEnd = (OSErr (*)(ImageSequence))GetProcAddress(handler, "CDSequenceEnd"); if(!InitializeQTML || !EnterMovies || !DecompressSequenceBegin || !DecompressSequenceFrameS){ mp_msg(MSGT_DECVIDEO,MSGL_ERR,"invalid qtmlClient.dll!\n"); return 0; } result=InitializeQTML(kInitializeQTMLDisableDirectSound | kInitializeQTMLUseGDIFlag | kInitializeQTMLDisableDDClippers); mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"InitializeQTML returned %d\n",result); #endif /* CONFIG_QUICKTIME */ result=EnterMovies(); mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"EnterMovies returned %d\n",result); //make a yuy2 gworld OutBufferRect.top=0; OutBufferRect.left=0; OutBufferRect.right=sh->disp_w; OutBufferRect.bottom=sh->disp_h; //Fill the imagedescription for our SVQ3 frame //we can probably get this from Demuxer if (!sh->ImageDesc && extradata_size >= sizeof(ImageDescription) && ((ImageDescription *)extradata)->idSize <= extradata_size) sh->ImageDesc = extradata; if (sh->ImageDesc) { mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"ImageDescription size: %d\n",((ImageDescription*)(sh->ImageDesc))->idSize); framedescHandle=(ImageDescriptionHandle)NewHandleClear(((ImageDescription*)(sh->ImageDesc))->idSize); memcpy(*framedescHandle,sh->ImageDesc,((ImageDescription*)(sh->ImageDesc))->idSize); } else { // assume extradata consists only of the atoms, build the other parts ImageDescription *idesc; int size = sizeof(*idesc) + extradata_size; mp_msg(MSGT_DECVIDEO, MSGL_V, "Generating a ImageDescription\n"); framedescHandle=(ImageDescriptionHandle)NewHandleClear(size); idesc = *framedescHandle; memcpy(idesc + 1, extradata, extradata_size); idesc->idSize = size; idesc->width = sh->disp_w; idesc->height = sh->disp_h; } dump_ImageDescription(*framedescHandle); (**framedescHandle).cType = bswap_32(sh->format); sh->context = (void *)kYUVSPixelFormat; { int imgfmt = sh->codec->outfmt[sh->outfmtidx]; int qt_imgfmt; switch(imgfmt) { case IMGFMT_YUY2: qt_imgfmt = kYUVSPixelFormat; break; case IMGFMT_YVU9: qt_imgfmt = 0x73797639; //kYVU9PixelFormat; break; case IMGFMT_YV12: qt_imgfmt = 0x79343230; break; case IMGFMT_UYVY: qt_imgfmt = k2vuyPixelFormat; break; case IMGFMT_YVYU: qt_imgfmt = kYVYU422PixelFormat; imgfmt = IMGFMT_YUY2; break; case IMGFMT_RGB16: qt_imgfmt = k16LE555PixelFormat; break; case IMGFMT_BGR24: qt_imgfmt = k24BGRPixelFormat; break; case IMGFMT_BGR32: qt_imgfmt = k32BGRAPixelFormat; break; case IMGFMT_RGB32: qt_imgfmt = k32RGBAPixelFormat; break; default: mp_msg(MSGT_DECVIDEO,MSGL_ERR,"Unknown requested csp\n"); return 0; } mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"imgfmt: %s qt_imgfmt: %.4s\n", vo_format_name(imgfmt), (char *)&qt_imgfmt); sh->context = (void *)qt_imgfmt; if(!mpcodecs_config_vo(sh,sh->disp_w,sh->disp_h,imgfmt)) return 0; } mpi=mpcodecs_get_image(sh, MP_IMGTYPE_STATIC, MP_IMGFLAG_PRESERVE, sh->disp_w, sh->disp_h); if(!mpi) return 0; result = QTNewGWorldFromPtr( &OutBufferGWorld, (OSType)sh->context, &OutBufferRect, //we should benchmark if yvu9 is faster for svq3, too 0, 0, 0, mpi->planes[0], mpi->stride[0]); if (result) { mp_msg(MSGT_DECVIDEO,MSGL_ERR,"QTNewGWorldFromPtr result=%d\n",result); return 0; } result = DecompressSequenceBegin(&imageSeq, framedescHandle, (CGrafPtr)OutBufferGWorld, NULL, NULL, NULL, srcCopy, NULL, 0, codecNormalQuality, 0); if(result) { mp_msg(MSGT_DECVIDEO,MSGL_ERR,"DecompressSequenceBegin result=%d\n",result); return 0; } return 1; }
int main(void) { void *handler; void *handler2; void* theqtdp=NULL; void* compcall=NULL; void* compcallws=NULL; ComponentResult (*dispatcher)(ComponentParameters *params, Globals glob); ComponentResult ret; ComponentParameters *params; ComponentDescription desc; void *globals=NULL; //unsigned int esp=0; //int i; mp_msg_init(); //mp_msg_set_level(10); Setup_LDT_Keeper(); printf("loading qts\n"); // handler = LoadLibraryA("/root/.wine/fake_windows/Windows/System/QuickTime.qts"); handler = LoadLibraryA("QuickTime.qts"); theqtdp = GetProcAddress(handler, "theQuickTimeDispatcher"); compcall = GetProcAddress(handler, "CallComponent"); compcallws = GetProcAddress(handler, "CallComponentFunctionWithStorage"); InitializeQTML = 0x6299e590;//GetProcAddress(handler, "InitializeQTML"); InitializeQTML(6+16); printf("loading svq3\n"); handler2= LoadLibraryA("/root/.wine/fake_windows/Windows/System/QuickTime/QuickTimeEssentials.qtx"); printf("done\n"); dispatcher = GetProcAddress(handler2, "SMD_ComponentDispatch"); // handler = expLoadLibraryA("/usr/local/lib/codecs/On2_VP3.qtx"); // dispatcher = GetProcAddress(handler, "CDComponentDispatcher"); printf("handler: %p, dispatcher: %p theqtdp: %p\n", handler, dispatcher, theqtdp); // printf("theQuickTimeDispatcher = %p\n",GetProcAddress(handler, "theQuickTimeDispatcher")); // patch svq3 dll: *((void**)0x63214c98) = NULL; *((void**)0x63214c9c) = theqtdp; // theQt... *((void**)0x63214ca0) = compcall; //0xdeadbeef; //dispatcher; // CallCOmponent_ptr *((void**)0x63214ca4) = compcallws; //0xdeadbef2; //dispatcher; // CallComponentWithStorage_ptr desc.componentType=0; desc.componentSubType=0; desc.componentManufacturer=0; desc.componentFlags=0; desc.componentFlagsMask=0; params = malloc(sizeof(ComponentParameters)+2048); params->flags = 0; params->paramSize = 4; params->what = kComponentOpenSelect; params->params[0] = 0x830000; //0x820000|i; //(i<<16)|0x24; //0x820024; ret = dispatcher(params, &globals); printf("!!! CDComponentDispatch() => 0x%X glob=%p\n",ret,globals); // memset(x_table,12,4*0x00001837); //for(i=0;i<=255;i++){ // params->what = kComponentVersionSelect; // params->what = kComponentRegisterSelect; // params->what = kComponentOpenSelect; // params->what = kComponentCanDoSelect; printf("params: flags: %d, paramSize: %d, what: %d, params[0] = %x\n", params->flags, params->paramSize, params->what, params->params[0]); // __asm__ volatile ("movl %%esp, %0\n\t" : "=a" (esp) :: "memory" ); // printf("ESP=%p\n",esp); *((void**)0x62b7d640) = &x_table[0]; //malloc(0x00001837 * 4); // ugly hack? printf("params=%p &glob=%p x_table=%p\n",params,&globals, &x_table[0]); ret = dispatcher(params, &globals); // __asm__ volatile ("movl %%esp, %0\n\t" : "=a" (esp) :: "memory" ); // printf("ESP=%p\n",esp); printf("!!! CDComponentDispatch() => %d glob=%p\n",ret,globals); // if(ret!=-3000) break; //} // for(i=0;i<0x00001837;i++) // if(x_table[i]) printf("x_table[0x%X] = %p\n",i,x_table[i]); exit(0); //return 0; }
// init driver static int init(sh_video_t *sh){ #ifndef CONFIG_QUICKTIME long result = 1; #endif ComponentResult cres; ComponentDescription desc; Component prev=NULL; CodecInfo cinfo; // for ImageCodecGetCodecInfo() ImageSubCodecDecompressCapabilities icap; // for ImageCodecInitialize() codec_initialized = 0; #ifdef CONFIG_QUICKTIME EnterMovies(); #else #ifdef WIN32_LOADER Setup_LDT_Keeper(); #endif //preload quicktime.qts to avoid the problems caused by the hardcoded path inside the dll qtime_qts = LoadLibraryA("QuickTime.qts"); if(!qtime_qts){ mp_msg(MSGT_DECVIDEO,MSGL_ERR,"unable to load QuickTime.qts\n" ); return 0; } handler = LoadLibraryA("qtmlClient.dll"); if(!handler){ mp_msg(MSGT_DECVIDEO,MSGL_ERR,"unable to load qtmlClient.dll\n"); return 0; } InitializeQTML = (OSErr (*)(long))GetProcAddress(handler, "InitializeQTML"); EnterMovies = (OSErr (*)(void))GetProcAddress(handler, "EnterMovies"); FindNextComponent = (Component (*)(Component,ComponentDescription*))GetProcAddress(handler, "FindNextComponent"); CountComponents = (long (*)(ComponentDescription*))GetProcAddress(handler, "CountComponents"); GetComponentInfo = (OSErr (*)(Component,ComponentDescription*,Handle,Handle,Handle))GetProcAddress(handler, "GetComponentInfo"); OpenComponent = (ComponentInstance (*)(Component))GetProcAddress(handler, "OpenComponent"); ImageCodecInitialize = (ComponentResult (*)(ComponentInstance,ImageSubCodecDecompressCapabilities *))GetProcAddress(handler, "ImageCodecInitialize"); ImageCodecGetCodecInfo = (ComponentResult (*)(ComponentInstance,CodecInfo *))GetProcAddress(handler, "ImageCodecGetCodecInfo"); ImageCodecBeginBand = (ComponentResult (*)(ComponentInstance,CodecDecompressParams *,ImageSubCodecDecompressRecord *,long))GetProcAddress(handler, "ImageCodecBeginBand"); ImageCodecPreDecompress = (ComponentResult (*)(ComponentInstance,CodecDecompressParams *))GetProcAddress(handler, "ImageCodecPreDecompress"); ImageCodecBandDecompress = (ComponentResult (*)(ComponentInstance,CodecDecompressParams *))GetProcAddress(handler, "ImageCodecBandDecompress"); GetGWorldPixMap = (PixMapHandle (*)(GWorldPtr))GetProcAddress(handler, "GetGWorldPixMap"); QTNewGWorldFromPtr = (OSErr(*)(GWorldPtr *,OSType,const Rect *,CTabHandle,void*,GWorldFlags,void *,long))GetProcAddress(handler, "QTNewGWorldFromPtr"); NewHandleClear = (OSErr(*)(Size))GetProcAddress(handler, "NewHandleClear"); // = GetProcAddress(handler, ""); if(!InitializeQTML || !EnterMovies || !FindNextComponent || !ImageCodecBandDecompress){ mp_msg(MSGT_DECVIDEO,MSGL_ERR,"invalid qtmlClient.dll!\n"); return 0; } result=InitializeQTML(6+16); // result=InitializeQTML(0); mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"InitializeQTML returned %li\n",result); // result=EnterMovies(); // printf("EnterMovies->%d\n",result); #endif /* CONFIG_QUICKTIME */ #if 0 memset(&desc,0,sizeof(desc)); while((prev=FindNextComponent(prev,&desc))){ ComponentDescription desc2; unsigned char* c1=&desc2.componentType; unsigned char* c2=&desc2.componentSubType; memset(&desc2,0,sizeof(desc2)); // printf("juhee %p (%p)\n",prev,&desc); GetComponentInfo(prev,&desc2,NULL,NULL,NULL); mp_msg(MSGT_DECVIDEO,MSGL_DGB2,"DESC: %c%c%c%c/%c%c%c%c [0x%X/0x%X] 0x%X\n", c1[3],c1[2],c1[1],c1[0], c2[3],c2[2],c2[1],c2[0], desc2.componentType,desc2.componentSubType, desc2.componentFlags); } #endif memset(&desc,0,sizeof(desc)); desc.componentType= (((unsigned char)'i')<<24)| (((unsigned char)'m')<<16)| (((unsigned char)'d')<<8)| (((unsigned char)'c')); #if 0 desc.componentSubType= (((unsigned char)'S'<<24))| (((unsigned char)'V')<<16)| (((unsigned char)'Q')<<8)| (((unsigned char)'3')); #else desc.componentSubType = bswap_32(sh->format); #endif desc.componentManufacturer=0; desc.componentFlags=0; desc.componentFlagsMask=0; mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Count = %ld\n",CountComponents(&desc)); prev=FindNextComponent(NULL,&desc); if(!prev){ mp_msg(MSGT_DECVIDEO,MSGL_ERR,"Cannot find requested component\n"); return 0; } mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Found it! ID = %p\n",prev); ci=OpenComponent(prev); mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"ci=%p\n",ci); memset(&icap,0,sizeof(icap)); cres=ImageCodecInitialize(ci,&icap); mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"ImageCodecInitialize->%#x size=%d (%d)\n",cres,icap.recordSize,icap.decompressRecordSize); memset(&cinfo,0,sizeof(cinfo)); cres=ImageCodecGetCodecInfo(ci,&cinfo); mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Flags: compr: 0x%X decomp: 0x%X format: 0x%X\n", cinfo.compressFlags, cinfo.decompressFlags, cinfo.formatFlags); mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Codec name: %.*s\n",((unsigned char*)&cinfo.typeName)[0], ((unsigned char*)&cinfo.typeName)+1); //make a yuy2 gworld OutBufferRect.top=0; OutBufferRect.left=0; OutBufferRect.right=sh->disp_w; OutBufferRect.bottom=sh->disp_h; //Fill the imagedescription for our SVQ3 frame //we can probably get this from Demuxer #if 0 framedescHandle=(ImageDescriptionHandle)NewHandleClear(sizeof(ImageDescription)+200); printf("framedescHandle=%p *p=%p\n",framedescHandle,*framedescHandle); { FILE* f=fopen("/root/.wine/fake_windows/IDesc","r"); if(!f) printf("filenot found: IDesc\n"); fread(*framedescHandle,sizeof(ImageDescription)+200,1,f); fclose(f); } #else if(!sh->ImageDesc) sh->ImageDesc=(sh->bih+1); // hack for SVQ3-in-AVI mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"ImageDescription size: %d\n",((ImageDescription*)(sh->ImageDesc))->idSize); framedescHandle=(ImageDescriptionHandle)NewHandleClear(((ImageDescription*)(sh->ImageDesc))->idSize); memcpy(*framedescHandle,sh->ImageDesc,((ImageDescription*)(sh->ImageDesc))->idSize); dump_ImageDescription(*framedescHandle); #endif //Find codecscomponent for video decompression // result = FindCodec ('SVQ1',anyCodec,&compressor,&decompressor ); // printf("FindCodec SVQ1 returned:%i compressor: 0x%X decompressor: 0x%X\n",result,compressor,decompressor); sh->context = (void *)kYUVSPixelFormat; #if 1 { int imgfmt = sh->codec->outfmt[sh->outfmtidx]; int qt_imgfmt; switch(imgfmt) { case IMGFMT_YUY2: qt_imgfmt = kYUVSPixelFormat; break; case IMGFMT_YVU9: qt_imgfmt = 0x73797639; //kYVU9PixelFormat; break; case IMGFMT_YV12: qt_imgfmt = 0x79343230; break; case IMGFMT_UYVY: qt_imgfmt = kUYVY422PixelFormat; break; case IMGFMT_YVYU: qt_imgfmt = kYVYU422PixelFormat; imgfmt = IMGFMT_YUY2; break; case IMGFMT_RGB16: qt_imgfmt = k16LE555PixelFormat; break; case IMGFMT_BGR24: qt_imgfmt = k24BGRPixelFormat; break; case IMGFMT_BGR32: qt_imgfmt = k32BGRAPixelFormat; break; case IMGFMT_RGB32: qt_imgfmt = k32RGBAPixelFormat; break; default: mp_msg(MSGT_DECVIDEO,MSGL_ERR,"Unknown requested csp\n"); return 0; } mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"imgfmt: %s qt_imgfmt: %.4s\n", vo_format_name(imgfmt), (char *)&qt_imgfmt); sh->context = (void *)qt_imgfmt; if(!mpcodecs_config_vo(sh,sh->disp_w,sh->disp_h,imgfmt)) return 0; } #else if(!mpcodecs_config_vo(sh,sh->disp_w,sh->disp_h,IMGFMT_YUY2)) return 0; #endif return 1; }
int MovDecoder_InitSubsystem() { long result = 1; ComponentResult cres; ComponentDescription desc; Component prev=NULL; CodecInfo cinfo; // for ImageCodecGetCodecInfo() //ImageSubCodecDecompressCapabilities icap; // for ImageCodecInitialize() //preload quicktime.qts to avoid the problems caused by the hardcoded path inside the dll qtime_qts = LoadLibraryA("QuickTime.qts"); if (!qtime_qts) { //mp_msg(MSGT_DECVIDEO,MSGL_ERR,"unable to load QuickTime.qts\n" ); return 0; } handler = LoadLibraryA("qtmlClient.dll"); if(!handler) { //mp_msg(MSGT_DECVIDEO,MSGL_ERR,"unable to load qtmlClient.dll\n"); return 0; } result=InitializeQTML(6+16); //mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"InitializeQTML returned %li\n",result); memset(&desc,0,sizeof(desc)); desc.componentType= (((unsigned char)'i')<<24)|(((unsigned char)'m')<<16)|(((unsigned char)'d')<<8)|(((unsigned char)'c')); desc.componentSubType = bswap_32(sh->format); desc.componentManufacturer=0; desc.componentFlags=0; desc.componentFlagsMask=0; // mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Count = %ld\n",CountComponents(&desc)); prev=FindNextComponent(NULL,&desc); if(!prev) { //mp_msg(MSGT_DECVIDEO,MSGL_ERR,"Cannot find requested component\n"); return(0); } //mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Found it! ID = %p\n",prev); ci=OpenComponent(prev); //mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"ci=%p\n",ci); memset(&icap,0,sizeof(icap)); cres=ImageCodecInitialize(ci,&icap); //mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"ImageCodecInitialize->%#x size=%d (%d)\n",cres,icap.recordSize,icap.decompressRecordSize); memset(&cinfo,0,sizeof(cinfo)); cres=ImageCodecGetCodecInfo(ci,&cinfo); //mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Flags: compr: 0x%X decomp: 0x%X format: 0x%X\n", cinfo.compressFlags, cinfo.decompressFlags, cinfo.formatFlags); //mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"Codec name: %.*s\n",((unsigned char*)&cinfo.typeName)[0], ((unsigned char*)&cinfo.typeName)+1); //make a yuy2 gworld OutBufferRect.top=0; OutBufferRect.left=0; OutBufferRect.right=sh->disp_w; OutBufferRect.bottom=sh->disp_h; //Fill the imagedescription for our SVQ3 frame //we can probably get this from Demuxer if(!sh->ImageDesc) sh->ImageDesc=(sh->bih+1); // hack for SVQ3-in-AVI mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"ImageDescription size: %d\n",((ImageDescription*)(sh->ImageDesc))->idSize); framedescHandle=(ImageDescriptionHandle)NewHandleClear(((ImageDescription*)(sh->ImageDesc))->idSize); memcpy(*framedescHandle,sh->ImageDesc,((ImageDescription*)(sh->ImageDesc))->idSize); dump_ImageDescription(*framedescHandle); //Find codecscomponent for video decompression // result = FindCodec ('SVQ1',anyCodec,&compressor,&decompressor ); // printf("FindCodec SVQ1 returned:%i compressor: 0x%X decompressor: 0x%X\n",result,compressor,decompressor); sh->context = (void *)kYUVSPixelFormat; #if 1 { int imgfmt = sh->codec->outfmt[sh->outfmtidx]; int qt_imgfmt; switch(imgfmt) { case IMGFMT_YUY2: qt_imgfmt = kYUVSPixelFormat; break; case IMGFMT_YVU9: qt_imgfmt = 0x73797639; //kYVU9PixelFormat; break; case IMGFMT_YV12: qt_imgfmt = 0x79343230; break; case IMGFMT_UYVY: qt_imgfmt = kUYVY422PixelFormat; break; case IMGFMT_YVYU: qt_imgfmt = kYVYU422PixelFormat; imgfmt = IMGFMT_YUY2; break; case IMGFMT_RGB16: qt_imgfmt = k16LE555PixelFormat; break; case IMGFMT_BGR24: qt_imgfmt = k24BGRPixelFormat; break; case IMGFMT_BGR32: qt_imgfmt = k32BGRAPixelFormat; break; case IMGFMT_RGB32: qt_imgfmt = k32RGBAPixelFormat; break; default: mp_msg(MSGT_DECVIDEO,MSGL_ERR,"Unknown requested csp\n"); return(0); } mp_msg(MSGT_DECVIDEO,MSGL_DBG2,"imgfmt: %s qt_imgfmt: %.4s\n", vo_format_name(imgfmt), (char *)&qt_imgfmt); sh->context = (void *)qt_imgfmt; if(!mpcodecs_config_vo(sh,sh->disp_w,sh->disp_h,imgfmt)) return 0; } return 1; }
QTAudioReader (InputStream* const input_, const int trackNum_) : AudioFormatReader (input_, TRANS (quickTimeFormatName)), ok (false), movie (0), trackNum (trackNum_), lastSampleRead (0), lastThreadId (0), extractor (0), dataHandle (0) { JUCE_AUTORELEASEPOOL bufferList.calloc (256, 1); #if JUCE_WINDOWS if (InitializeQTML (0) != noErr) return; #endif if (EnterMovies() != noErr) return; bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle); if (! opened) return; { const int numTracks = GetMovieTrackCount (movie); int trackCount = 0; for (int i = 1; i <= numTracks; ++i) { track = GetMovieIndTrack (movie, i); media = GetTrackMedia (track); OSType mediaType; GetMediaHandlerDescription (media, &mediaType, 0, 0); if (mediaType == SoundMediaType && trackCount++ == trackNum_) { ok = true; break; } } } if (! ok) return; ok = false; lengthInSamples = GetMediaDecodeDuration (media); usesFloatingPointData = false; samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media)); trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame / GetMediaTimeScale (media); OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor); unsigned long output_layout_size; err = MovieAudioExtractionGetPropertyInfo (extractor, kQTPropertyClass_MovieAudioExtraction_Audio, kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout, 0, &output_layout_size, 0); if (err != noErr) return; HeapBlock <AudioChannelLayout> qt_audio_channel_layout; qt_audio_channel_layout.calloc (output_layout_size, 1); err = MovieAudioExtractionGetProperty (extractor, kQTPropertyClass_MovieAudioExtraction_Audio, kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout, output_layout_size, qt_audio_channel_layout, 0); qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo; err = MovieAudioExtractionSetProperty (extractor, kQTPropertyClass_MovieAudioExtraction_Audio, kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout, output_layout_size, qt_audio_channel_layout); err = MovieAudioExtractionGetProperty (extractor, kQTPropertyClass_MovieAudioExtraction_Audio, kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription, sizeof (inputStreamDesc), &inputStreamDesc, 0); if (err != noErr) return; inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked | kAudioFormatFlagsNativeEndian; inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8; inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame); inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame; inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame; err = MovieAudioExtractionSetProperty (extractor, kQTPropertyClass_MovieAudioExtraction_Audio, kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription, sizeof (inputStreamDesc), &inputStreamDesc); if (err != noErr) return; Boolean allChannelsDiscrete = false; err = MovieAudioExtractionSetProperty (extractor, kQTPropertyClass_MovieAudioExtraction_Movie, kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete, sizeof (allChannelsDiscrete), &allChannelsDiscrete); if (err != noErr) return; bufferList->mNumberBuffers = 1; bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame; bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16); dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize); bufferList->mBuffers[0].mData = dataBuffer; sampleRate = inputStreamDesc.mSampleRate; bitsPerSample = 16; numChannels = inputStreamDesc.mChannelsPerFrame; detachThread(); ok = true; }
int main (int argc, const char * argv[]) { #if TARGET_OS_WIN32 InitializeQTML(0L); #endif const char *fpath = NULL; Float32 volume = 1; Float32 duration = -1; Float32 currentTime = 0.0; Float32 rate = 0; int rQuality = 0; bool doPrint = false; for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] != '-') { if (fpath != NULL) { fprintf(stderr, "may only specify one file to play\n"); usage(); } fpath = arg; } else { arg += 1; if (arg[0] == 'v' || !strcmp(arg, "-volume")) { if (++i == argc) MissingArgument(); arg = argv[i]; sscanf(arg, "%f", &volume); } else if (arg[0] == 't' || !strcmp(arg, "-time")) { if (++i == argc) MissingArgument(); arg = argv[i]; sscanf(arg, "%f", &duration); } else if (arg[0] == 'r' || !strcmp(arg, "-rate")) { if (++i == argc) MissingArgument(); arg = argv[i]; sscanf(arg, "%f", &rate); } else if (arg[0] == 'q' || !strcmp(arg, "-rQuality")) { if (++i == argc) MissingArgument(); arg = argv[i]; sscanf(arg, "%d", &rQuality); } else if (arg[0] == 'h' || !strcmp(arg, "-help")) { usage(); } else if (arg[0] == 'd' || !strcmp(arg, "-debug")) { doPrint = true; } else { fprintf(stderr, "unknown argument: %s\n\n", arg - 1); usage(); } } } if (fpath == NULL) usage(); if (doPrint) printf ("Playing file: %s\n", fpath); try { AQTestInfo myInfo; CFURLRef sndFile = CFURLCreateFromFileSystemRepresentation (NULL, (const UInt8 *)fpath, strlen(fpath), false); if (!sndFile) XThrowIfError (!sndFile, "can't parse file path"); OSStatus result = AudioFileOpenURL (sndFile, 0x1/*fsRdPerm*/, 0/*inFileTypeHint*/, &myInfo.mAudioFile); CFRelease (sndFile); XThrowIfError(result, "AudioFileOpen failed"); UInt32 size; XThrowIfError(AudioFileGetPropertyInfo(myInfo.mAudioFile, kAudioFilePropertyFormatList, &size, NULL), "couldn't get file's format list info"); UInt32 numFormats = size / sizeof(AudioFormatListItem); AudioFormatListItem *formatList = new AudioFormatListItem [ numFormats ]; XThrowIfError(AudioFileGetProperty(myInfo.mAudioFile, kAudioFilePropertyFormatList, &size, formatList), "couldn't get file's data format"); numFormats = size / sizeof(AudioFormatListItem); // we need to reassess the actual number of formats when we get it if (numFormats == 1) { // this is the common case myInfo.mDataFormat = formatList[0].mASBD; // see if there is a channel layout (multichannel file) result = AudioFileGetPropertyInfo(myInfo.mAudioFile, kAudioFilePropertyChannelLayout, &myInfo.mChannelLayoutSize, NULL); if (result == noErr && myInfo.mChannelLayoutSize > 0) { myInfo.mChannelLayout = (AudioChannelLayout *)new char [myInfo.mChannelLayoutSize]; XThrowIfError(AudioFileGetProperty(myInfo.mAudioFile, kAudioFilePropertyChannelLayout, &myInfo.mChannelLayoutSize, myInfo.mChannelLayout), "get audio file's channel layout"); } } else { if (doPrint) { printf ("File has a %d layered data format:\n", (int)numFormats); for (unsigned int i = 0; i < numFormats; ++i) CAStreamBasicDescription(formatList[i].mASBD).Print(); } // now we should look to see which decoders we have on the system XThrowIfError(AudioFormatGetPropertyInfo(kAudioFormatProperty_DecodeFormatIDs, 0, NULL, &size), "couldn't get decoder id's"); UInt32 numDecoders = size / sizeof(OSType); OSType *decoderIDs = new OSType [ numDecoders ]; XThrowIfError(AudioFormatGetProperty(kAudioFormatProperty_DecodeFormatIDs, 0, NULL, &size, decoderIDs), "couldn't get decoder id's"); unsigned int i = 0; for (; i < numFormats; ++i) { OSType decoderID = formatList[i].mASBD.mFormatID; bool found = false; for (unsigned int j = 0; j < numDecoders; ++j) { if (decoderID == decoderIDs[j]) { found = true; break; } } if (found) break; } delete [] decoderIDs; if (i >= numFormats) { fprintf (stderr, "Cannot play any of the formats in this file\n"); throw kAudioFileUnsupportedDataFormatError; } myInfo.mDataFormat = formatList[i].mASBD; myInfo.mChannelLayoutSize = sizeof(AudioChannelLayout); myInfo.mChannelLayout = (AudioChannelLayout*)new char [myInfo.mChannelLayoutSize]; myInfo.mChannelLayout->mChannelLayoutTag = formatList[i].mChannelLayoutTag; myInfo.mChannelLayout->mChannelBitmap = 0; myInfo.mChannelLayout->mNumberChannelDescriptions = 0; } delete [] formatList; if (doPrint) { printf ("Playing format: "); myInfo.mDataFormat.Print(); } XThrowIfError(AudioQueueNewOutput(&myInfo.mDataFormat, AQTestBufferCallback, &myInfo, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &myInfo.mQueue), "AudioQueueNew failed"); UInt32 bufferByteSize; // we need to calculate how many packets we read at a time, and how big a buffer we need // we base this on the size of the packets in the file and an approximate duration for each buffer { bool isFormatVBR = (myInfo.mDataFormat.mBytesPerPacket == 0 || myInfo.mDataFormat.mFramesPerPacket == 0); // first check to see what the max size of a packet is - if it is bigger // than our allocation default size, that needs to become larger UInt32 maxPacketSize; size = sizeof(maxPacketSize); XThrowIfError(AudioFileGetProperty(myInfo.mAudioFile, kAudioFilePropertyPacketSizeUpperBound, &size, &maxPacketSize), "couldn't get file's max packet size"); // adjust buffer size to represent about a half second of audio based on this format CalculateBytesForTime (myInfo.mDataFormat, maxPacketSize, 0.5/*seconds*/, &bufferByteSize, &myInfo.mNumPacketsToRead); if (isFormatVBR) myInfo.mPacketDescs = new AudioStreamPacketDescription [myInfo.mNumPacketsToRead]; else myInfo.mPacketDescs = NULL; // we don't provide packet descriptions for constant bit rate formats (like linear PCM) if (doPrint) printf ("Buffer Byte Size: %d, Num Packets to Read: %d\n", (int)bufferByteSize, (int)myInfo.mNumPacketsToRead); } // (2) If the file has a cookie, we should get it and set it on the AQ size = sizeof(UInt32); result = AudioFileGetPropertyInfo (myInfo.mAudioFile, kAudioFilePropertyMagicCookieData, &size, NULL); if (!result && size) { char* cookie = new char [size]; XThrowIfError (AudioFileGetProperty (myInfo.mAudioFile, kAudioFilePropertyMagicCookieData, &size, cookie), "get cookie from file"); XThrowIfError (AudioQueueSetProperty(myInfo.mQueue, kAudioQueueProperty_MagicCookie, cookie, size), "set cookie on queue"); delete [] cookie; } // set ACL if there is one if (myInfo.mChannelLayout) XThrowIfError(AudioQueueSetProperty(myInfo.mQueue, kAudioQueueProperty_ChannelLayout, myInfo.mChannelLayout, myInfo.mChannelLayoutSize), "set channel layout on queue"); // prime the queue with some data before starting myInfo.mDone = false; myInfo.mCurrentPacket = 0; for (int i = 0; i < kNumberBuffers; ++i) { XThrowIfError(AudioQueueAllocateBuffer(myInfo.mQueue, bufferByteSize, &myInfo.mBuffers[i]), "AudioQueueAllocateBuffer failed"); AQTestBufferCallback (&myInfo, myInfo.mQueue, myInfo.mBuffers[i]); if (myInfo.mDone) break; } // set the volume of the queue XThrowIfError (AudioQueueSetParameter(myInfo.mQueue, kAudioQueueParam_Volume, volume), "set queue volume"); XThrowIfError (AudioQueueAddPropertyListener (myInfo.mQueue, kAudioQueueProperty_IsRunning, MyAudioQueuePropertyListenerProc, NULL), "add listener"); #if !TARGET_OS_IPHONE if (rate > 0) { UInt32 propValue = 1; XThrowIfError (AudioQueueSetProperty (myInfo.mQueue, kAudioQueueProperty_EnableTimePitch, &propValue, sizeof(propValue)), "enable time pitch"); propValue = rQuality ? kAudioQueueTimePitchAlgorithm_Spectral : kAudioQueueTimePitchAlgorithm_TimeDomain; XThrowIfError (AudioQueueSetProperty (myInfo.mQueue, kAudioQueueProperty_TimePitchAlgorithm, &propValue, sizeof(propValue)), "time pitch algorithm"); propValue = (rate == 1.0f ? 1 : 0); // bypass rate if 1.0 XThrowIfError (AudioQueueSetProperty (myInfo.mQueue, kAudioQueueProperty_TimePitchBypass, &propValue, sizeof(propValue)), "bypass time pitch"); if (rate != 1) { XThrowIfError (AudioQueueSetParameter (myInfo.mQueue, kAudioQueueParam_PlayRate, rate), "set playback rate"); } if (doPrint) { printf ("Enable rate-scaled playback (rate = %.2f) using %s algorithm\n", rate, (rQuality ? "Spectral": "Time Domain")); } } #endif // lets start playing now - stop is called in the AQTestBufferCallback when there's // no more to read from the file XThrowIfError(AudioQueueStart(myInfo.mQueue, NULL), "AudioQueueStart failed"); do { CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.25, false); currentTime += .25; if (duration > 0 && currentTime >= duration) break; } while (gIsRunning); CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, false); XThrowIfError(AudioQueueDispose(myInfo.mQueue, true), "AudioQueueDispose(true) failed"); XThrowIfError(AudioFileClose(myInfo.mAudioFile), "AudioQueueDispose(false) failed"); } catch (CAXException e) { char buf[256]; fprintf(stderr, "Error: %s (%s)\n", e.mOperation, e.FormatError(buf)); } catch (...) { fprintf(stderr, "Unspecified exception\n"); } return 0; }
/* * PsychQTCreateMovie() -- Create a movie object. * * This function tries to open a Quicktime-Moviefile and create an * associated movie object for it. * * win = Pointer to window record of associated onscreen window. * moviename = char* with the name of the moviefile. * preloadSecs = How many seconds of the movie should be preloaded/prefetched into RAM at movie open time? * moviehandle = handle to the new movie. */ void PsychQTCreateMovie(PsychWindowRecordType *win, const char* moviename, double preloadSecs, int* moviehandle) { Movie theMovie = NULL; QTVisualContextRef QTMovieContext = NULL; QTAudioContextRef QTAudioContext = NULL; int i, slotid; OSErr error; CFStringRef movieLocation; CFURLRef movieURLLocation; CFStringRef coreAudioDeviceUID; psych_bool trueValue = TRUE; QTNewMoviePropertyElement newMovieProperties[4] = {0}; int propcount = 0; char msgerr[10000]; char errdesc[1000]; Rect movierect; psych_bool printErrors; // Suppress output of error-messages if moviehandle == 1000. That means we // run in our own Posix-Thread, not in the Matlab-Thread. Printing via Matlabs // printing facilities would likely cause a terrible crash. printErrors = (*moviehandle == -1000) ? FALSE : TRUE; // Set movie handle to "failed" initially: *moviehandle = -1; // We startup the Quicktime subsystem only on first invocation. if (firsttime) { #if PSYCH_SYSTEM == PSYCH_WINDOWS // Initialize Quicktime for Windows compatibility layer: This will fail if // QT isn't installed on the Windows machine... error = InitializeQTML(0); if (error!=noErr) { if (printErrors) { PsychErrorExitMsg(PsychError_internal, "Quicktime Media Layer initialization failed: Quicktime not properly installed?!?"); } else return; } #endif // Initialize Quicktime-Subsystem: error = EnterMovies(); if (error!=noErr) { if (printErrors) PsychErrorExitMsg(PsychError_internal, "Quicktime EnterMovies() failed!!!"); else return; } firsttime = FALSE; } if (!PsychIsOnscreenWindow(win)) { if (printErrors) PsychErrorExitMsg(PsychError_user, "Provided windowPtr is not an onscreen window."); else return; } if (NULL==moviename) { if (printErrors) PsychErrorExitMsg(PsychError_internal, "NULL-Ptr instead of moviename passed!"); else return; } if (numMovieRecords >= PSYCH_MAX_MOVIES) { *moviehandle = -2; if (printErrors) PsychErrorExitMsg(PsychError_user, "Allowed maximum number of simultaneously open movies exceeded!"); else return; } // Search first free slot in movieRecordBANK: for (i=0; (i < PSYCH_MAX_MOVIES) && (movieRecordBANK[i].theMovie); i++); if (i>=PSYCH_MAX_MOVIES) { *moviehandle = -2; if (printErrors) PsychErrorExitMsg(PsychError_user, "Allowed maximum number of simultaneously open movies exceeded!"); else return; } // Slot slotid will contain the movie record for our new movie object: slotid=i; // Create name-string for moviename: movieLocation = CFStringCreateWithCString (kCFAllocatorDefault, moviename, kCFStringEncodingASCII); // Zero-out new record in moviebank: movieRecordBANK[slotid].theMovie=NULL; movieRecordBANK[slotid].QTMovieContext=NULL; movieRecordBANK[slotid].QTAudioContext=NULL; movieRecordBANK[slotid].QTMovieGWorld=NULL; if (!PSYCH_USE_QT_GWORLDS) { // Create QTGLTextureContext: #if PSYCH_SYSTEM != PSYCH_WINDOWS error = QTOpenGLTextureContextCreate (kCFAllocatorDefault, win->targetSpecific.contextObject, win->targetSpecific.pixelFormatObject, NULL, &QTMovieContext); #endif if (error!=noErr) { if (printErrors) PsychErrorExitMsg(PsychError_internal, "OpenGL Quicktime visual context creation failed!!!"); else return; } } // The Movie location newMovieProperties[propcount].propClass = kQTPropertyClass_DataLocation; if (strstr(moviename, "http:") || strstr(moviename, "ftp:")) { // Open movie from URL, e.g., http- or ftp- server: movieURLLocation = CFURLCreateWithString(kCFAllocatorDefault, movieLocation, NULL); newMovieProperties[propcount].propID = kQTDataLocationPropertyID_CFURL; newMovieProperties[propcount].propValueSize = sizeof(movieURLLocation); newMovieProperties[propcount++].propValueAddress = (void*) &movieURLLocation; } else { // Open movie file from filesystem: newMovieProperties[propcount].propID = kQTDataLocationPropertyID_CFStringPosixPath; newMovieProperties[propcount].propValueSize = sizeof(CFStringRef); newMovieProperties[propcount++].propValueAddress = &movieLocation; } if (!PSYCH_USE_QT_GWORLDS) { // The Movie visual context newMovieProperties[propcount].propClass = kQTPropertyClass_Context; newMovieProperties[propcount].propID = kQTContextPropertyID_VisualContext; newMovieProperties[propcount].propValueSize = sizeof(QTVisualContextRef); newMovieProperties[propcount++].propValueAddress = &QTMovieContext; } if (TRUE) { // Create QTAudioContext for default CoreAudio device: coreAudioDeviceUID = NULL; // Use default audio-output device. error =QTAudioContextCreateForAudioDevice (kCFAllocatorDefault, coreAudioDeviceUID, NULL, &QTAudioContext); if (error!=noErr) { if (printErrors) PsychErrorExitMsg(PsychError_internal, "Quicktime audio context creation failed!!!"); else return; } // The Movie audio context newMovieProperties[propcount].propClass = kQTPropertyClass_Context; newMovieProperties[propcount].propID = kQTContextPropertyID_AudioContext; newMovieProperties[propcount].propValueSize = sizeof(QTAudioContextRef); newMovieProperties[propcount++].propValueAddress = &QTAudioContext; } // The Movie active newMovieProperties[propcount].propClass = kQTPropertyClass_NewMovieProperty; newMovieProperties[propcount].propID = kQTNewMoviePropertyID_Active; newMovieProperties[propcount].propValueSize = sizeof(trueValue); newMovieProperties[propcount++].propValueAddress = &trueValue; // Instantiate the Movie error = NewMovieFromProperties(propcount, newMovieProperties, 0, NULL, &theMovie); if (error!=noErr) { QTVisualContextRelease(QTMovieContext); QTAudioContextRelease(QTAudioContext); switch(error) { case -2000: case -50: case -43: sprintf(errdesc, "File not found."); break; case -2048: sprintf(errdesc, "This is not a file that Quicktime understands."); break; case -2003: sprintf(errdesc, "Can't find media handler (codec) for this movie."); break; default: sprintf(errdesc, "Unknown: Check http://developer.apple.com/documentation/QuickTime/APIREF/ErrorCodes.htm#//apple_ref/doc/constant_group/Error_Codes"); } sprintf(msgerr, "Couldn't load movie %s! Quicktime error code %i [%s]", moviename, (int) error, errdesc); *moviehandle = (int) error; if (printErrors) PsychErrorExitMsg(PsychError_user, msgerr); else return; } CFRelease(movieLocation); if (PSYCH_USE_QT_GWORLDS) { // Determine size of images in movie: GetMovieBox(theMovie, &movierect); // Only create a GWorld if movie frames contain at least 1 pixel. This way we skip GWorld // setup on "movies" which only consist of sound tracks. if ((movierect.right - movierect.left != 0) && (movierect.bottom - movierect.top != 0)) { // Create GWorld for this movie object: // error = QTNewGWorld(&movieRecordBANK[slotid].QTMovieGWorld, k32ABGRPixelFormat, &movierect, NULL, NULL, 0); error = QTNewGWorld(&movieRecordBANK[slotid].QTMovieGWorld, 0, &movierect, NULL, NULL, 0); if (error!=noErr) { QTAudioContextRelease(QTAudioContext); DisposeMovie(movieRecordBANK[slotid].theMovie); movieRecordBANK[slotid].theMovie=NULL; if (printErrors) PsychErrorExitMsg(PsychError_internal, "Quicktime GWorld creation failed!!!"); else return; } // Attach this GWorld as rendering target for Quicktime: SetMovieGWorld(theMovie, movieRecordBANK[slotid].QTMovieGWorld, NULL); } } // Preload preloadSecs seconds of movie into system RAM for faster playback: if (preloadSecs > 0) LoadMovieIntoRam(theMovie, 0, ((long) preloadSecs + 0.5) * GetMovieTimeScale(theMovie), keepInRam); // Special setting - 1 means: Load whole movie into RAM: if (preloadSecs == -1) LoadMovieIntoRam(theMovie, 0, GetMovieDuration(theMovie), keepInRam); // We don't preroll: Didn't help for async playback, but leads to failure in // manual playback mode: PrerollMovie(theMovie, 0, FloatToFixed(1)); // MoviesTask() it to make sure start of plaback will be as stutter-free as possible: MoviesTask(theMovie, 10000); // Assign new record in moviebank: movieRecordBANK[slotid].theMovie=theMovie; movieRecordBANK[slotid].QTMovieContext=QTMovieContext; movieRecordBANK[slotid].QTAudioContext=QTAudioContext; movieRecordBANK[slotid].loopflag = 0; *moviehandle = slotid; // Increase counter: numMovieRecords++; // Compute basic movie properties - Duration and fps as well as image size: // Compute duration in seconds: movieRecordBANK[slotid].movieduration = (double) GetMovieDuration(theMovie) / (double) GetMovieTimeScale(theMovie); // Compute expected framerate, assuming a linear spacing between frames: It is derived as // reciprocal of the duration of the first video frame in the movie: movieRecordBANK[slotid].fps = PsychDetermineMovieFramecountAndFps(theMovie, NULL); // Determine size of images in movie: GetMovieBox(theMovie, &movierect); movieRecordBANK[slotid].width = movierect.right - movierect.left; movieRecordBANK[slotid].height = movierect.bottom - movierect.top; // We set nrframes == -1 to indicate that this value is not yet available. // Will do counting on first query for this parameter as it is very time-consuming: movieRecordBANK[slotid].nrframes = -1; return; }
int CALLBACK WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR theCmdLine, int nCmdShow) { HANDLE myAccel; HWND myWindowFrame; MSG myMsg; WNDCLASSEX myWC; char myFileName[MAX_PATH]; DWORD myLength; OSErr myErr = noErr; ghInst = hInstance; gCmdLine = theCmdLine; if (hPrevInstance == NULL) { LoadString(hInstance, IDS_APPNAME, gAppName, sizeof(gAppName)); // register the frame window class myWC.cbSize = sizeof(WNDCLASSEX); myWC.style = CS_HREDRAW | CS_VREDRAW; myWC.lpfnWndProc = (WNDPROC)QTFrame_FrameWndProc; myWC.cbClsExtra = 0; myWC.cbWndExtra = 0; myWC.hInstance = hInstance; myWC.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPICON)); myWC.hCursor = LoadCursor(NULL, IDC_ARROW); myWC.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); myWC.lpszMenuName = gAppName; myWC.lpszClassName = gAppName; myWC.hIconSm = LoadImage(hInstance, MAKEINTRESOURCE(IDI_APPICON), IMAGE_ICON, 16, 16, 0); if (!RegisterClassEx(&myWC)) { if (!RegisterClass((LPWNDCLASS)&myWC.style)) return(0); } // register the movie child window class myWC.cbSize = sizeof(WNDCLASSEX); myWC.style = 0; myWC.lpfnWndProc = (WNDPROC)QTFrame_MovieWndProc; myWC.cbClsExtra = 0; myWC.cbWndExtra = 0; myWC.hInstance = hInstance; myWC.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CHILDICON)); // to avoid having QuickTime VR "fight" with the system over the cursor, // we set the client area cursor to NULL; this means that for QuickTime // movies, we'll need to change the cursor to an arrow manually; see the // handling of the WM_MOUSEMOVE message in QTFrame_MovieWndProc myWC.hCursor = NULL; myWC.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); myWC.lpszMenuName = NULL; myWC.lpszClassName = gChildName; myWC.hIconSm = LoadImage(hInstance, MAKEINTRESOURCE(IDI_CHILDICON), IMAGE_ICON, 16, 16, 0); if (!RegisterClassEx(&myWC)) { if (!RegisterClass((LPWNDCLASS)&myWC.style)) return(0); } } // load accelerators myAccel = LoadAccelerators(hInstance, gAppName); // initialize QuickTime Media Layer and QuickTime; alert the user and return 0 if unsuccessful myErr = InitializeQTML(0L); if (myErr != noErr) { MessageBox(NULL, "QuickTime is not installed on this computer. Exiting.", gAppName, MB_OK | MB_APPLMODAL); return(0); } myErr = EnterMovies(); if (myErr != noErr) { MessageBox(NULL, "Could not initialize QuickTime. Exiting.", gAppName, MB_OK | MB_APPLMODAL); return(0); } // get the application's resource file, if it exists myLength = GetModuleFileName(NULL, myFileName, MAX_PATH); // NULL means: the current process if (myLength != 0) { NativePathNameToFSSpec(myFileName, &gAppFSSpec, kFullNativePath); gAppResFile = FSpOpenResFile(&gAppFSSpec, fsRdWrPerm); if (gAppResFile != kInvalidFileRefNum) UseResFile(gAppResFile); } // do any application-specific initialization that must occur before the frame window is created QTApp_Init(kInitAppPhase_BeforeCreateFrameWindow); // create the main frame window myWindowFrame = CreateWindow(gAppName, gAppName, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); ghWnd = myWindowFrame; // make sure we got a frame window if (myWindowFrame == NULL) return(0); // show the window ShowWindow(myWindowFrame, nCmdShow); UpdateWindow(myWindowFrame); // do any application-specific initialization that must occur after the frame window is created QTApp_Init(kInitAppPhase_AfterCreateFrameWindow); // get and process events until the user quits while (GetMessage(&myMsg, NULL, 0, 0)) { if (!TranslateMDISysAccel(ghWndMDIClient, &myMsg)) { if (!TranslateAccelerator(myWindowFrame, myAccel, &myMsg)) { TranslateMessage(&myMsg); DispatchMessage(&myMsg); } } } // close the application's resource file, if it was previously opened if (gAppResFile != kInvalidFileRefNum) CloseResFile(gAppResFile); // terminate the QuickTime Media Layer ExitMovies(); TerminateQTML(); return(myMsg.wParam); // returns the value from PostQuitMessage }
int convertMain (int argc, char * const argv[]) { #if TARGET_OS_WIN32 QTLicenseRef aacEncoderLicenseRef = nil; QTLicenseRef amrEncoderLicenseRef = nil; OSErr localerr; #endif int result = 0; CFURLRef inputFileURL = NULL; CFURLRef outputFileURL = NULL; #if TARGET_OS_WIN32 InitializeQTML(0L); { OSErr localerr; const char *licenseDesc = "AAC Encode License Verification"; const char *amrLicenseDesc = "AMR Encode License Verification"; localerr = QTRequestLicensedTechnology("com.apple.quicktimeplayer","com.apple.aacencoder", (void *)licenseDesc,strlen(licenseDesc),&aacEncoderLicenseRef); localerr = QTRequestLicensedTechnology("com.apple.quicktimeplayer","1D07EB75-3D5E-4DA6-B749-D497C92B06D8", (void *)amrLicenseDesc,strlen(amrLicenseDesc),&amrEncoderLicenseRef); } #endif try { OSType format = 0; Float64 sampleRate = 0; AudioFileTypeID outputFileType = kAudioFileCAFType; UInt32 outputBitRate = 0; UInt32 outputBitDepth = 0; ParseArgs (argc, argv, format, sampleRate, outputFileType, inputFileURL, outputFileURL, outputBitDepth, outputBitRate); // printf ("args:%4.4s, sample rate:%.1f, outputFileType: %4.4s\n", (char*)&format, sampleRate, (char*)&outputFileType); CAStreamBasicDescription inputFormat; CAStreamBasicDescription outputFormat; ConstructOutputFormatFromArgs (inputFileURL, outputFileType, format, sampleRate, inputFormat, outputBitDepth, outputFormat); printf ("Source File format:\n\t"); inputFormat.Print(); printf ("Dest File format:\n\t"); outputFormat.Print(); result = ConvertFile (inputFileURL, inputFormat, outputFileURL, outputFileType, outputFormat, outputBitRate); CFStringRef path = CFURLCopyPath(outputFileURL); printf("done: "); fflush(stdout); CFShow(path); if (path) CFRelease(path); } catch (CAXException e) { char buf[256]; fprintf(stderr, "Error in: %s\nException thrown: %s\n", e.mOperation, e.FormatError(buf)); result = 1; } catch (...) { fprintf(stderr, "Unspecified exception\n"); result = 1; } if (inputFileURL) CFRelease(inputFileURL); if (outputFileURL) CFRelease(outputFileURL); #if TARGET_OS_WIN32 TerminateQTML(); if (aacEncoderLicenseRef) { localerr = QTReleaseLicensedTechnology(aacEncoderLicenseRef); aacEncoderLicenseRef = nil; } if(amrEncoderLicenseRef) { localerr = QTReleaseLicensedTechnology(amrEncoderLicenseRef); amrEncoderLicenseRef = nil; } #endif return result; }
QuickTimeFileReader::QuickTimeFileReader(FileSource source, DecodeMode decodeMode, CacheMode mode, size_t targetRate, ProgressReporter *reporter) : CodedAudioFileReader(mode, targetRate), m_source(source), m_path(source.getLocalFilename()), m_d(new D), m_reporter(reporter), m_cancelled(false), m_completion(0), m_decodeThread(0) { m_channelCount = 0; m_fileRate = 0; Profiler profiler("QuickTimeFileReader::QuickTimeFileReader", true); SVDEBUG << "QuickTimeFileReader: path is \"" << m_path << "\"" << endl; long QTversion; #ifdef WIN32 InitializeQTML(0); // FIXME should check QT version #else m_d->err = Gestalt(gestaltQuickTime,&QTversion); if ((m_d->err != noErr) || (QTversion < 0x07000000)) { m_error = QString("Failed to find compatible version of QuickTime (version 7 or above required)"); return; } #endif EnterMovies(); Handle dataRef; OSType dataRefType; // CFStringRef URLString = CFStringCreateWithCString // (0, m_path.toLocal8Bit().data(), 0); QByteArray ba = m_path.toLocal8Bit(); CFURLRef url = CFURLCreateFromFileSystemRepresentation (kCFAllocatorDefault, (const UInt8 *)ba.data(), (CFIndex)ba.length(), false); // m_d->err = QTNewDataReferenceFromURLCFString m_d->err = QTNewDataReferenceFromCFURL (url, 0, &dataRef, &dataRefType); if (m_d->err) { m_error = QString("Error creating data reference for QuickTime decoder: code %1").arg(m_d->err); return; } short fileID = movieInDataForkResID; short flags = 0; m_d->err = NewMovieFromDataRef (&m_d->movie, flags, &fileID, dataRef, dataRefType); DisposeHandle(dataRef); if (m_d->err) { m_error = QString("Error creating new movie for QuickTime decoder: code %1").arg(m_d->err); return; } Boolean isProtected = 0; Track aTrack = GetMovieIndTrackType (m_d->movie, 1, SoundMediaType, movieTrackMediaType | movieTrackEnabledOnly); if (aTrack) { Media aMedia = GetTrackMedia(aTrack); // get the track media if (aMedia) { MediaHandler mh = GetMediaHandler(aMedia); // get the media handler we can query if (mh) { m_d->err = QTGetComponentProperty(mh, kQTPropertyClass_DRM, kQTDRMPropertyID_IsProtected, sizeof(Boolean), &isProtected,nil); } else { m_d->err = 1; } } else { m_d->err = 1; } } else { m_d->err = 1; } if (m_d->err && m_d->err != kQTPropertyNotSupportedErr) { m_error = QString("Error checking for DRM in QuickTime decoder: code %1").arg(m_d->err); return; } else if (!m_d->err && isProtected) { m_error = QString("File is protected with DRM"); return; } else if (m_d->err == kQTPropertyNotSupportedErr && !isProtected) { std::cerr << "QuickTime: File is not protected with DRM" << std::endl; } if (m_d->movie) { SetMovieActive(m_d->movie, TRUE); m_d->err = GetMoviesError(); if (m_d->err) { m_error = QString("Error in QuickTime decoder activation: code %1").arg(m_d->err); return; } } else { m_error = QString("Error in QuickTime decoder: Movie object not valid"); return; } m_d->err = MovieAudioExtractionBegin (m_d->movie, 0, &m_d->extractionSessionRef); if (m_d->err) { m_error = QString("Error in QuickTime decoder extraction init: code %1").arg(m_d->err); return; } m_d->err = MovieAudioExtractionGetProperty (m_d->extractionSessionRef, kQTPropertyClass_MovieAudioExtraction_Audio, kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription, sizeof(m_d->asbd), &m_d->asbd, nil); if (m_d->err) { m_error = QString("Error in QuickTime decoder property get: code %1").arg(m_d->err); return; } m_channelCount = m_d->asbd.mChannelsPerFrame; m_fileRate = m_d->asbd.mSampleRate; std::cerr << "QuickTime: " << m_channelCount << " channels, " << m_fileRate << " kHz" << std::endl; m_d->asbd.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked | kAudioFormatFlagsNativeEndian; m_d->asbd.mBitsPerChannel = sizeof(float) * 8; m_d->asbd.mBytesPerFrame = sizeof(float) * m_d->asbd.mChannelsPerFrame; m_d->asbd.mBytesPerPacket = m_d->asbd.mBytesPerFrame; m_d->err = MovieAudioExtractionSetProperty (m_d->extractionSessionRef, kQTPropertyClass_MovieAudioExtraction_Audio, kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription, sizeof(m_d->asbd), &m_d->asbd); if (m_d->err) { m_error = QString("Error in QuickTime decoder property set: code %1").arg(m_d->err); m_channelCount = 0; return; } m_d->buffer.mNumberBuffers = 1; m_d->buffer.mBuffers[0].mNumberChannels = m_channelCount; m_d->buffer.mBuffers[0].mDataByteSize = sizeof(float) * m_channelCount * m_d->blockSize; m_d->data = new float[m_channelCount * m_d->blockSize]; m_d->buffer.mBuffers[0].mData = m_d->data; initialiseDecodeCache(); if (decodeMode == DecodeAtOnce) { if (m_reporter) { connect(m_reporter, SIGNAL(cancelled()), this, SLOT(cancelled())); m_reporter->setMessage (tr("Decoding %1...").arg(QFileInfo(m_path).fileName())); } while (1) { UInt32 framesRead = m_d->blockSize; UInt32 extractionFlags = 0; m_d->err = MovieAudioExtractionFillBuffer (m_d->extractionSessionRef, &framesRead, &m_d->buffer, &extractionFlags); if (m_d->err) { m_error = QString("Error in QuickTime decoding: code %1") .arg(m_d->err); break; } //!!! progress? // std::cerr << "Read " << framesRead << " frames (block size " << m_d->blockSize << ")" << std::endl; // QuickTime buffers are interleaved unless specified otherwise addSamplesToDecodeCache(m_d->data, framesRead); if (framesRead < m_d->blockSize) break; } finishDecodeCache(); endSerialised(); m_d->err = MovieAudioExtractionEnd(m_d->extractionSessionRef); if (m_d->err) { m_error = QString("Error ending QuickTime extraction session: code %1").arg(m_d->err); } m_completion = 100; } else { if (m_reporter) m_reporter->setProgress(100); if (m_channelCount > 0) { m_decodeThread = new DecodeThread(this); m_decodeThread->start(); } } std::cerr << "QuickTimeFileReader::QuickTimeFileReader: frame count is now " << getFrameCount() << ", error is \"\"" << m_error << "\"" << std::endl; }
OSErr makeMovieFromVideoFramesFile(char *inDestMovieFile) { Handle dataRef = NULL; OSType dataRefType; ImageDescriptionHandle videoDescH = NULL; OSErr err; #if TARGET_OS_WIN32 err = InitializeQTML(0); if ((err = GetMoviesError()) != noErr) goto bail; #endif err = EnterMovies(); if ((err = GetMoviesError()) != noErr) goto bail; // create a data reference from the full path to the video frames file makeDataRefFromFullPath(inDestMovieFile, &dataRef, &dataRefType); if (dataRef == NULL) goto bail; Movie m = NewMovie(0); if ((err = GetMoviesError()) != noErr) goto bail; // create the video track for the movie Track videoT = NewMovieTrack( m, Long2Fix(kFrameWidth), Long2Fix(kFrameHeight), kNoVolume); if ((err = GetMoviesError()) != noErr) goto bail; // create the video track media Media videoM = NewTrackMedia( videoT, VideoMediaType, kMediaTimeScale, dataRef, dataRefType); if ((err = GetMoviesError()) != noErr) goto bail; videoDescH = (ImageDescriptionHandle)NewHandleClear(sizeof(ImageDescription)); if (videoDescH == NULL) goto bail; // create the ImageDescription that will describe our video track media samples videoDescH[0]->idSize = sizeof(ImageDescription); videoDescH[0]->cType = kCodecType; // the codec type for your data videoDescH[0]->temporalQuality = codecNormalQuality; videoDescH[0]->spatialQuality = codecNormalQuality; videoDescH[0]->width = kFrameWidth; videoDescH[0]->height = kFrameHeight; videoDescH[0]->hRes = 72L << 16; videoDescH[0]->vRes = 72L << 16; videoDescH[0]->depth = 32; videoDescH[0]->clutID = -1; SampleReference64Record videoRef; videoRef.dataOffset.hi = 0; videoRef.dataOffset.lo = 0; videoRef.dataSize = (kFrameWidth*kFrameHeight*4) * kNumberOfSamples; videoRef.durationPerSample = kDurationPerSample; videoRef.numberOfSamples = kNumberOfSamples; videoRef.sampleFlags = 0; // now add all of our media samples to the movie data file. err = AddMediaSampleReferences64(videoM, (SampleDescriptionHandle)videoDescH, 1, &videoRef, 0); if (err != noErr) goto bail; TimeValue mediaDuration = kNumberOfSamples * kDurationPerSample; // inserts a reference to our media samples into the track. err = InsertMediaIntoTrack(videoT, 0, 0, mediaDuration, fixed1); // media's rate (1.0 = media's natural playback rate). if (err != noErr) goto bail; DataHandler outDataHandler; // opens a data handler for our movie storage (the video frames file) err = OpenMovieStorage (dataRef, dataRefType, kDataHCanWrite, &outDataHandler ); if (err != noErr) goto bail; // add a movie to our movie storage container err = AddMovieToStorage (m, outDataHandler ); if (err != noErr) goto bail; err = CloseMovieStorage (outDataHandler); outDataHandler = NULL; bail: if (videoDescH) { DisposeHandle((Handle)videoDescH); } return err; }
void __stdcall QuickTimeCheckSetup() { // Set up our Macintosh Toolbox glue code. InitializeQTML(0); }