コード例 #1
0
static void test_metadata_tEXt(void)
{
    HRESULT hr;
    IWICMetadataReader *reader;
    IWICEnumMetadataItem *enumerator;
    PROPVARIANT schema, id, value;
    ULONG items_returned, count;
    GUID format;

    PropVariantInit(&schema);
    PropVariantInit(&id);
    PropVariantInit(&value);

    hr = CoCreateInstance(&CLSID_WICPngTextMetadataReader, NULL, CLSCTX_INPROC_SERVER,
        &IID_IWICMetadataReader, (void**)&reader);
    todo_wine ok(hr == S_OK, "CoCreateInstance failed, hr=%x\n", hr);
    if (FAILED(hr)) return;

    hr = IWICMetadataReader_GetCount(reader, NULL);
    ok(hr == E_INVALIDARG, "GetCount failed, hr=%x\n", hr);

    hr = IWICMetadataReader_GetCount(reader, &count);
    ok(hr == S_OK, "GetCount failed, hr=%x\n", hr);
    ok(count == 0, "unexpected count %i\n", count);

    load_stream((IUnknown*)reader, metadata_tEXt, sizeof(metadata_tEXt));

    hr = IWICMetadataReader_GetCount(reader, &count);
    ok(hr == S_OK, "GetCount failed, hr=%x\n", hr);
    ok(count == 1, "unexpected count %i\n", count);

    hr = IWICMetadataReader_GetEnumerator(reader, NULL);
    ok(hr == E_INVALIDARG, "GetEnumerator failed, hr=%x\n", hr);

    hr = IWICMetadataReader_GetEnumerator(reader, &enumerator);
    ok(hr == S_OK, "GetEnumerator failed, hr=%x\n", hr);

    if (SUCCEEDED(hr))
    {
        hr = IWICEnumMetadataItem_Next(enumerator, 1, &schema, &id, &value, &items_returned);
        ok(hr == S_OK, "Next failed, hr=%x\n", hr);
        ok(items_returned == 1, "unexpected item count %i\n", items_returned);

        if (hr == S_OK && items_returned == 1)
        {
            ok(schema.vt == VT_EMPTY, "unexpected vt: %i\n", schema.vt);
            ok(id.vt == VT_LPSTR, "unexpected vt: %i\n", id.vt);
            ok(!strcmp(id.pszVal, "winetest"), "unexpected id: %s\n", id.pszVal);
            ok(value.vt == VT_LPSTR, "unexpected vt: %i\n", id.vt);
            ok(!strcmp(value.pszVal, "value"), "unexpected value: %s\n", id.pszVal);

            PropVariantClear(&schema);
            PropVariantClear(&id);
            PropVariantClear(&value);
        }

        hr = IWICEnumMetadataItem_Next(enumerator, 1, &schema, &id, &value, &items_returned);
        ok(hr == S_FALSE, "Next failed, hr=%x\n", hr);
        ok(items_returned == 0, "unexpected item count %i\n", items_returned);

        IWICEnumMetadataItem_Release(enumerator);
    }

    hr = IWICMetadataReader_GetMetadataFormat(reader, &format);
    ok(hr == S_OK, "GetMetadataFormat failed, hr=%x\n", hr);
    ok(IsEqualGUID(&format, &GUID_MetadataFormatChunktEXt), "unexpected format %s\n", debugstr_guid(&format));

    hr = IWICMetadataReader_GetMetadataFormat(reader, NULL);
    ok(hr == E_INVALIDARG, "GetMetadataFormat failed, hr=%x\n", hr);

    id.vt = VT_LPSTR;
    id.pszVal = CoTaskMemAlloc(strlen("winetest") + 1);
    strcpy(id.pszVal, "winetest");

    hr = IWICMetadataReader_GetValue(reader, NULL, &id, NULL);
    ok(hr == S_OK, "GetValue failed, hr=%x\n", hr);

    hr = IWICMetadataReader_GetValue(reader, &schema, NULL, &value);
    ok(hr == E_INVALIDARG, "GetValue failed, hr=%x\n", hr);

    hr = IWICMetadataReader_GetValue(reader, &schema, &id, &value);
    ok(hr == S_OK, "GetValue failed, hr=%x\n", hr);
    ok(value.vt == VT_LPSTR, "unexpected vt: %i\n", id.vt);
    ok(!strcmp(value.pszVal, "value"), "unexpected value: %s\n", id.pszVal);
    PropVariantClear(&value);

    strcpy(id.pszVal, "test");

    hr = IWICMetadataReader_GetValue(reader, &schema, &id, &value);
    ok(hr == WINCODEC_ERR_PROPERTYNOTFOUND, "GetValue failed, hr=%x\n", hr);

    PropVariantClear(&id);

    hr = IWICMetadataReader_GetValueByIndex(reader, 0, NULL, NULL, NULL);
    ok(hr == S_OK, "GetValueByIndex failed, hr=%x\n", hr);

    hr = IWICMetadataReader_GetValueByIndex(reader, 0, &schema, NULL, NULL);
    ok(hr == S_OK, "GetValueByIndex failed, hr=%x\n", hr);
    ok(schema.vt == VT_EMPTY, "unexpected vt: %i\n", schema.vt);

    hr = IWICMetadataReader_GetValueByIndex(reader, 0, NULL, &id, NULL);
    ok(hr == S_OK, "GetValueByIndex failed, hr=%x\n", hr);
    ok(id.vt == VT_LPSTR, "unexpected vt: %i\n", id.vt);
    ok(!strcmp(id.pszVal, "winetest"), "unexpected id: %s\n", id.pszVal);
    PropVariantClear(&id);

    hr = IWICMetadataReader_GetValueByIndex(reader, 0, NULL, NULL, &value);
    ok(hr == S_OK, "GetValueByIndex failed, hr=%x\n", hr);
    ok(value.vt == VT_LPSTR, "unexpected vt: %i\n", id.vt);
    ok(!strcmp(value.pszVal, "value"), "unexpected value: %s\n", id.pszVal);
    PropVariantClear(&value);

    hr = IWICMetadataReader_GetValueByIndex(reader, 1, NULL, NULL, NULL);
    ok(hr == E_INVALIDARG, "GetValueByIndex failed, hr=%x\n", hr);

    IWICMetadataReader_Release(reader);
}
コード例 #2
0
ファイル: datainit.c プロジェクト: AlexSteel/wine
static HRESULT get_dbpropset_from_proplist(struct dbprops *props, DBPROPSET **propset)
{
    struct dbprop_pair *pair;
    int i = 0;
    HRESULT hr;

    *propset = CoTaskMemAlloc(sizeof(DBPROPSET));
    if (!*propset)
        return E_OUTOFMEMORY;

    (*propset)->rgProperties = CoTaskMemAlloc(props->count*sizeof(DBPROP));
    if (!(*propset)->rgProperties)
    {
        CoTaskMemFree(*propset);
        *propset = NULL;
        return E_OUTOFMEMORY;
    }

    (*propset)->cProperties = 0;
    LIST_FOR_EACH_ENTRY(pair, &props->props, struct dbprop_pair, entry)
    {
        const struct dbproperty *descr = get_known_dprop_descr(pair->name);
        VARIANT dest, src;

        if (!descr)
        {
            static const WCHAR eqW[] = {'=',0};
            BSTR str;
            int len;

            /* provider specific property is always VT_BSTR */
            len = SysStringLen(pair->name) + SysStringLen(pair->value) + 1 /* for '=' */;
            str = SysAllocStringLen(NULL, len);
            strcpyW(str, pair->name);
            strcatW(str, eqW);
            strcatW(str, pair->value);

            (*propset)->cProperties++;
            (*propset)->guidPropertySet = DBPROPSET_DBINIT;
            (*propset)->rgProperties[i].dwPropertyID = DBPROP_INIT_PROVIDERSTRING;
            (*propset)->rgProperties[i].dwOptions = DBPROPOPTIONS_REQUIRED;
            (*propset)->rgProperties[i].dwStatus = 0;
            memset(&(*propset)->rgProperties[i].colid, 0, sizeof(DBID));
            V_VT(&(*propset)->rgProperties[i].vValue) = VT_BSTR;
            V_BSTR(&(*propset)->rgProperties[i].vValue) = str;
            i++;
            continue;
        }

        V_VT(&src) = VT_BSTR;
        V_BSTR(&src) = pair->value;

        VariantInit(&dest);
        hr = VariantChangeType(&dest, &src, 0, descr->type);
        if (FAILED(hr))
        {
            ERR("failed to init property %s value as type %d\n", debugstr_w(pair->name), descr->type);
            free_dbpropset(1, *propset);
            *propset = NULL;
            return hr;
        }

        (*propset)->cProperties++;
        (*propset)->guidPropertySet = DBPROPSET_DBINIT;
        (*propset)->rgProperties[i].dwPropertyID = descr->id;
        (*propset)->rgProperties[i].dwOptions = descr->options;
        (*propset)->rgProperties[i].dwStatus = 0;
        memset(&(*propset)->rgProperties[i].colid, 0, sizeof(DBID));
        (*propset)->rgProperties[i].vValue = dest;
        i++;
    }

    return S_OK;
}
コード例 #3
0
ファイル: datainit.c プロジェクト: AlexSteel/wine
static HRESULT WINAPI datainit_GetInitializationString(IDataInitialize *iface, IUnknown *datasource,
                                boolean include_pass, LPWSTR *init_string)
{
    static const WCHAR provW[] = {'P','r','o','v','i','d','e','r','=',0};
    static const WCHAR colW[] = {';',0};
    datainit *This = impl_from_IDataInitialize(iface);
    DBPROPINFOSET *propinfoset;
    IDBProperties *props;
    DBPROPIDSET propidset;
    ULONG count, infocount;
    WCHAR *progid, *desc;
    DBPROPSET *propset;
    IPersist *persist;
    HRESULT hr;
    CLSID clsid;
    ULONG i, len;

    TRACE("(%p)->(%p %d %p)\n", This, datasource, include_pass, init_string);

    /* IPersist support is mandatory for data sources */
    hr = IUnknown_QueryInterface(datasource, &IID_IPersist, (void**)&persist);
    if (FAILED(hr)) return hr;

    memset(&clsid, 0, sizeof(clsid));
    hr = IPersist_GetClassID(persist, &clsid);
    IPersist_Release(persist);
    if (FAILED(hr)) return hr;

    progid = NULL;
    ProgIDFromCLSID(&clsid, &progid);
    TRACE("clsid=%s, progid=%s\n", debugstr_guid(&clsid), debugstr_w(progid));

    /* now get initialization properties */
    hr = IUnknown_QueryInterface(datasource, &IID_IDBProperties, (void**)&props);
    if (FAILED(hr))
    {
        WARN("IDBProperties not supported\n");
        CoTaskMemFree(progid);
        return hr;
    }

    propidset.rgPropertyIDs = NULL;
    propidset.cPropertyIDs = 0;
    propidset.guidPropertySet = DBPROPSET_DBINIT;
    propset = NULL;
    count = 0;
    hr = IDBProperties_GetProperties(props, 1, &propidset, &count, &propset);
    if (FAILED(hr))
    {
        WARN("failed to get data source properties, 0x%08x\n", hr);
        CoTaskMemFree(progid);
        return hr;
    }

    infocount = 0;
    IDBProperties_GetPropertyInfo(props, 1, &propidset, &infocount, &propinfoset, &desc);
    IDBProperties_Release(props);

    /* check if we need to skip password */
    len = strlenW(progid) + strlenW(provW) + 1; /* including ';' */
    for (i = 0; i < count; i++)
    {
        WCHAR *descr = get_propinfo_descr(&propset->rgProperties[i], propinfoset);
        if (descr)
        {
            /* include '=' and ';' */
            len += strlenW(descr) + 2;
            len += get_propvalue_length(&propset->rgProperties[i]);
        }

        if ((propset->rgProperties[i].dwPropertyID == DBPROP_AUTH_PERSIST_SENSITIVE_AUTHINFO) &&
            (V_BOOL(&propset->rgProperties[i].vValue) == VARIANT_FALSE))
           include_pass = FALSE;
    }

    len *= sizeof(WCHAR);
    *init_string = CoTaskMemAlloc(len);
    *init_string[0] = 0;

    /* provider name */
    strcatW(*init_string, provW);
    strcatW(*init_string, progid);
    strcatW(*init_string, colW);
    CoTaskMemFree(progid);

    for (i = 0; i < count; i++)
    {
        WCHAR *descr;

        if (!include_pass && propset->rgProperties[i].dwPropertyID == DBPROP_AUTH_PASSWORD) continue;

        descr = get_propinfo_descr(&propset->rgProperties[i], propinfoset);
        if (descr)
        {
            static const WCHAR eqW[] = {'=',0};
            strcatW(*init_string, descr);
            strcatW(*init_string, eqW);
            write_propvalue_str(*init_string, &propset->rgProperties[i]);
            strcatW(*init_string, colW);
        }
    }

    free_dbpropset(count, propset);
    free_dbpropinfoset(infocount, propinfoset);
    CoTaskMemFree(desc);

    if (!include_pass)
        TRACE("%s\n", debugstr_w(*init_string));
    return S_OK;
}
コード例 #4
0
void* Allocator::operator new( size_t size )
{
	return CoTaskMemAlloc( size);
}
コード例 #5
0
ファイル: bandsite.cpp プロジェクト: GYGit/reactos
HRESULT STDMETHODCALLTYPE CBandSiteBase::AddBand(IUnknown *punk)
{
    LONG                                    NewAllocated;
    struct BandObject                       *NewBand = NULL;
    CComPtr<IDeskBand>                      DeskBand;
    CComPtr<IObjectWithSite>                ObjWithSite;
    CComPtr<IOleWindow>                     OleWindow;
    CComPtr<IWinEventHandler>               WndEvtHandler;
    REBARBANDINFOW                          rbi;
    HRESULT                                 hRet;
    UINT                                    uBand;

    TRACE("(%p, %p)\n", this, punk);

    if (punk == NULL || fRebarWindow == NULL)
        return E_FAIL;

    hRet = punk->QueryInterface(IID_PPV_ARG(IDeskBand, &DeskBand));
    if (!SUCCEEDED(hRet) || DeskBand == NULL)
        goto Cleanup;
    hRet = punk->QueryInterface(IID_PPV_ARG(IObjectWithSite, &ObjWithSite));
    if (!SUCCEEDED(hRet) || ObjWithSite == NULL)
        goto Cleanup;
    hRet = punk->QueryInterface(IID_PPV_ARG(IOleWindow, &OleWindow));
    if (!SUCCEEDED(hRet) || OleWindow == NULL)
        goto Cleanup;
    hRet = punk->QueryInterface(IID_PPV_ARG(IWinEventHandler, &WndEvtHandler));
    if (!SUCCEEDED(hRet) || WndEvtHandler == NULL)
        goto Cleanup;

    hRet = S_OK;
    if (fBandsAllocated > fBandsCount)
    {
        /* Search for a free band object */
        for (INT i = 0; i < fBandsAllocated; i++)
        {
            if (fBands[i].DeskBand == NULL)
            {
                NewBand = &fBands[i];
                break;
            }
        }
    }
    else if (fBandsAllocated > 0)
    {
        ASSERT (fBands != NULL);

        /* Reallocate the band object array */
        NewAllocated = fBandsAllocated + 8;
        if (NewAllocated > 0xFFFF)
            NewAllocated = 0xFFFF;
        if (NewAllocated == fBandsAllocated)
        {
            hRet = E_OUTOFMEMORY;
            goto Cleanup;
        }


        NewBand = static_cast<struct BandObject *>(CoTaskMemAlloc(NewAllocated * sizeof(struct BandObject)));
        if (NewBand == NULL)
        {
            hRet = E_OUTOFMEMORY;
            goto Cleanup;
        }

        /* Copy the old array */
        memcpy(NewBand, fBands, fBandsAllocated * sizeof(struct BandObject));

        /* Initialize the added bands */
        memset(&NewBand[fBandsAllocated], 0, (NewAllocated - fBandsAllocated) * sizeof(struct BandObject));

        fBandsAllocated = NewAllocated;
        CoTaskMemFree(fBands);
        fBands = NewBand;
    }
    else
    {
        ASSERT(fBands == NULL);
        ASSERT(fBandsAllocated == 0);
        ASSERT(fBandsCount == 0);

        /* Allocate new array */
        fBands = static_cast<struct BandObject *>(CoTaskMemAlloc(8 * sizeof(struct BandObject)));
        if (fBands == NULL)
        {
            hRet = E_OUTOFMEMORY;
            goto Cleanup;
        }

        /* Initialize the added bands */
        memset(fBands, 0, 8 * sizeof(struct BandObject));

        fBandsAllocated += 8;
        NewBand = &fBands[0];
    }

    if (SUCCEEDED(hRet))
    {
        ASSERT(NewBand != NULL);

        fBandsCount++;
        NewBand->DeskBand = DeskBand.Detach();
        NewBand->OleWindow = OleWindow.Detach();
        NewBand->WndEvtHandler = WndEvtHandler.Detach();

        /* Create the ReBar band */
        hRet = ObjWithSite->SetSite(static_cast<IOleWindow *>(this));
        if (SUCCEEDED(hRet))
        {
            uBand = 0xffffffff;
            if (SUCCEEDED(UpdateSingleBand(NewBand)))
            {
                if (NewBand->dbi.dwMask & DBIM_MODEFLAGS)
                {
                    if (NewBand->dbi.dwModeFlags & DBIMF_ADDTOFRONT)
                        uBand = 0;
                }
            }

            BuildRebarBandInfo(NewBand, &rbi);

            if (SUCCEEDED(NewBand->OleWindow->GetWindow(&rbi.hwndChild)) &&
                rbi.hwndChild != NULL)
            {
                rbi.fMask |= RBBIM_CHILD;
                WARN ("ReBar band uses child window 0x%p\n", rbi.hwndChild);
            }

            if (!SendMessageW(fRebarWindow, RB_INSERTBANDW, (WPARAM)uBand, reinterpret_cast<LPARAM>(&rbi)))
                return E_FAIL;

            hRet = (HRESULT)((USHORT)GetBandID(NewBand));
        }
        else
        {
            WARN("IBandSite::AddBand(): Call to IDeskBand::SetSite() failed: %x\n", hRet);

            /* Remove the band from the ReBar control */
            BuildRebarBandInfo(NewBand, &rbi);
            uBand = (UINT)SendMessageW(fRebarWindow, RB_IDTOINDEX, (WPARAM)rbi.wID, 0);
            if (uBand != (UINT)-1)
            {
                if (!SendMessageW(fRebarWindow, RB_DELETEBAND, (WPARAM)uBand, 0))
                {
                    ERR("Failed to delete band!\n");
                }
            }
            else
                ERR("Failed to map band id to index!\n");

            FreeBand(NewBand);

            hRet = E_FAIL;
            /* goto Cleanup; */
        }
    }
Cleanup:
    return hRet;
}
コード例 #6
0
ファイル: showpropdlg.cpp プロジェクト: vasilenkomike/xray
void App::GetProperties()
{
    LPSTORAGE				pStorage = NULL;
    IPropertySetStorage*	pPropertySetStorage = NULL;
    IPropertyStorage*		pSummaryInfoStorage = NULL;
    IPropertyStorage*		pDocumentSummaryInfoStorage = NULL;
    IPropertyStorage*		pUserDefinedPropertyStorage = NULL;
    wchar_t					wfilename[_MAX_PATH];
    char					szBuf[256];
    char					filename[MAX_PATH];

    SendMessage(GetDlgItem(hPropDialog, IDC_TITLE), WM_SETTEXT, 0, (LPARAM)"");
    SendMessage(GetDlgItem(hPropDialog, IDC_SUBJECT), WM_SETTEXT, 0, (LPARAM)"");
    SendMessage(GetDlgItem(hPropDialog, IDC_AUTHOR), WM_SETTEXT, 0, (LPARAM)"");
    SendMessage(GetDlgItem(hPropDialog, IDC_MANAGER), WM_SETTEXT, 0, (LPARAM)"");
    SendMessage(GetDlgItem(hPropDialog, IDC_COMPANY), WM_SETTEXT, 0, (LPARAM)"");
    SendMessage(GetDlgItem(hPropDialog, IDC_CATEGORY), WM_SETTEXT, 0, (LPARAM)"");
    SendMessage(GetDlgItem(hPropDialog, IDC_KEYWORDS), WM_SETTEXT, 0, (LPARAM)"");
    SendMessage(GetDlgItem(hPropDialog, IDC_COMMENTS), WM_SETTEXT, 0, (LPARAM)"");
    SendMessage(GetDlgItem(hPropDialog, IDC_CONTENTS), LB_RESETCONTENT, 0, 0);
    ListView_DeleteAllItems(GetDlgItem(hPropDialog, IDC_CUSTOM));

    int idx = SendMessage(hListBox, LB_GETCURSEL, 0, 0);

    SendMessage(hListBox, LB_GETTEXT, idx, (LPARAM)filename);
    SetWindowText(hPropDialog, filename);

    MultiByteToWideChar(CP_ACP, 0, filename, -1, wfilename, _MAX_PATH);
    HRESULT	res = StgOpenStorage(wfilename, (LPSTORAGE)0, STGM_DIRECT|STGM_READ|STGM_SHARE_EXCLUSIVE,	NULL,0,&pStorage);
    if (res!=S_OK) {
        return;
    }


    // Get the Storage interface
    if (S_OK != pStorage->QueryInterface(IID_IPropertySetStorage, (void**)&pPropertySetStorage)) {
        pStorage->Release();
        return;
    }

    // Get the SummaryInfo property set interface
    if (S_OK == pPropertySetStorage->Open(FMTID_SummaryInformation, STGM_READ|STGM_SHARE_EXCLUSIVE, &pSummaryInfoStorage)) {
        BOOL bFound = FALSE;

        PROPSPEC	PropSpec[5];
        PROPVARIANT	PropVar[5];

        PropSpec[0].ulKind = PRSPEC_PROPID;
        PropSpec[0].propid = PID_TITLE;

        PropSpec[1].ulKind = PRSPEC_PROPID;
        PropSpec[1].propid = PID_SUBJECT;

        PropSpec[2].ulKind = PRSPEC_PROPID;
        PropSpec[2].propid = PID_AUTHOR;

        PropSpec[3].ulKind = PRSPEC_PROPID;
        PropSpec[3].propid = PID_KEYWORDS;

        PropSpec[4].ulKind = PRSPEC_PROPID;
        PropSpec[4].propid = PID_COMMENTS;

        HRESULT hr = pSummaryInfoStorage->ReadMultiple(5, PropSpec, PropVar);
        if (S_OK == hr) {
            if (PropVar[0].vt == VT_LPSTR) {
                SendMessage(GetDlgItem(hPropDialog, IDC_TITLE), WM_SETTEXT, 0, (LPARAM)PropVar[0].pszVal);
            }
            if (PropVar[1].vt == VT_LPSTR) {
                SendMessage(GetDlgItem(hPropDialog, IDC_SUBJECT), WM_SETTEXT, 0, (LPARAM)PropVar[1].pszVal);
            }
            if (PropVar[2].vt == VT_LPSTR) {
                SendMessage(GetDlgItem(hPropDialog, IDC_AUTHOR), WM_SETTEXT, 0, (LPARAM)PropVar[2].pszVal);
            }
            if (PropVar[3].vt == VT_LPSTR) {
                SendMessage(GetDlgItem(hPropDialog, IDC_KEYWORDS), WM_SETTEXT, 0, (LPARAM)PropVar[3].pszVal);
            }
            if (PropVar[4].vt == VT_LPSTR) {
                SendMessage(GetDlgItem(hPropDialog, IDC_COMMENTS), WM_SETTEXT, 0, (LPARAM)PropVar[4].pszVal);
            }
        }

        FreePropVariantArray(5, PropVar);
        pSummaryInfoStorage->Release();
    }


    // Get the DocumentSummaryInfo property set interface
    if (S_OK == pPropertySetStorage->Open(FMTID_DocSummaryInformation, STGM_READ|STGM_SHARE_EXCLUSIVE, &pDocumentSummaryInfoStorage)) {
        BOOL bFound = FALSE;

        PROPSPEC	PropSpec[5];
        PROPVARIANT	PropVar[5];

        PropSpec[0].ulKind = PRSPEC_PROPID;
        PropSpec[0].propid = PID_MANAGER;

        PropSpec[1].ulKind = PRSPEC_PROPID;
        PropSpec[1].propid = PID_COMPANY;

        PropSpec[2].ulKind = PRSPEC_PROPID;
        PropSpec[2].propid = PID_CATEGORY;

        PropSpec[3].ulKind = PRSPEC_PROPID;
        PropSpec[3].propid = PID_HEADINGPAIR;

        PropSpec[4].ulKind = PRSPEC_PROPID;
        PropSpec[4].propid = PID_DOCPARTS;

        HRESULT hr = pDocumentSummaryInfoStorage->ReadMultiple(5, PropSpec, PropVar);
        if (S_OK == hr) {
            if (PropVar[0].vt == VT_LPSTR) {
                SendMessage(GetDlgItem(hPropDialog, IDC_MANAGER), WM_SETTEXT, 0, (LPARAM)PropVar[0].pszVal);
            }
            if (PropVar[1].vt == VT_LPSTR) {
                SendMessage(GetDlgItem(hPropDialog, IDC_COMPANY), WM_SETTEXT, 0, (LPARAM)PropVar[1].pszVal);
            }
            if (PropVar[2].vt == VT_LPSTR) {
                SendMessage(GetDlgItem(hPropDialog, IDC_CATEGORY), WM_SETTEXT, 0, (LPARAM)PropVar[2].pszVal);
            }
            if ((PropVar[3].vt == (VT_VARIANT | VT_VECTOR)) && (PropVar[4].vt == (VT_LPSTR | VT_VECTOR))) {
                CAPROPVARIANT*	pHeading = &PropVar[3].capropvar;
                CALPSTR*		pDocPart = &PropVar[4].calpstr;

                // Headings:
                // =========
                // 0  - General
                // 2  - Mesh Totals
                // 4  - Scene Totals
                // 6  - External Dependencies
                // 8  - Objects
                // 10 - Materials
                // 12 - Plug-Ins

                int nDocPart = 0;
                for (UINT i=0; i<pHeading->cElems; i+=2) {
                    SendMessage(GetDlgItem(hPropDialog, IDC_CONTENTS), LB_ADDSTRING, 0, (LPARAM)pHeading->pElems[i].pszVal);
                    for (int j=0; j<pHeading->pElems[i+1].lVal; j++) {
                        sprintf(szBuf, "\t%s", pDocPart->pElems[nDocPart]);
                        SendMessage(GetDlgItem(hPropDialog, IDC_CONTENTS), LB_ADDSTRING, 0, (LPARAM)szBuf);
                        nDocPart++;
                    }
                }

            }

        }

        FreePropVariantArray(5, PropVar);
        pDocumentSummaryInfoStorage->Release();
    }

    if (S_OK == pPropertySetStorage->Open(FMTID_UserDefinedProperties, STGM_READ|STGM_SHARE_EXCLUSIVE, &pUserDefinedPropertyStorage)) {
        int		numUserProps = 0;

        // First we need to count the properties
        IEnumSTATPROPSTG*	pIPropertyEnum;
        if (S_OK == pUserDefinedPropertyStorage->Enum(&pIPropertyEnum)) {
            STATPROPSTG property;
            while (pIPropertyEnum->Next(1, &property, NULL) == S_OK) {
                if (property.lpwstrName) {
                    CoTaskMemFree(property.lpwstrName);
                    property.lpwstrName = NULL;
                    numUserProps++;
                }
            }

            PROPSPEC* pPropSpec = new PROPSPEC[numUserProps];
            PROPVARIANT* pPropVar = new PROPVARIANT[numUserProps];

            ZeroMemory(pPropVar, numUserProps*sizeof(PROPVARIANT));
            ZeroMemory(pPropSpec, numUserProps*sizeof(PROPSPEC));

            pIPropertyEnum->Reset();
            int idx = 0;
            while (pIPropertyEnum->Next(1, &property, NULL) == S_OK) {
                if (property.lpwstrName) {
                    pPropSpec[idx].ulKind = PRSPEC_LPWSTR;
                    pPropSpec[idx].lpwstr = (LPWSTR)CoTaskMemAlloc(sizeof(wchar_t)*(wcslen(property.lpwstrName)+1));
                    wcscpy(pPropSpec[idx].lpwstr, property.lpwstrName);
                    idx++;
                    CoTaskMemFree(property.lpwstrName);
                    property.lpwstrName = NULL;
                }
            }
            pIPropertyEnum->Release();

            ListView_DeleteAllItems(GetDlgItem(hPropDialog, IDC_CUSTOM));
            HRESULT hr = pUserDefinedPropertyStorage->ReadMultiple(idx, pPropSpec, pPropVar);
            if (S_OK == hr) {
                for (int i=0; i<idx; i++) {
                    wcstombs(szBuf, pPropSpec[i].lpwstr, 255);
                    LV_ITEM item;
                    item.mask = LVIF_TEXT;
                    item.iItem = i;
                    item.iSubItem = 0;
                    item.pszText = szBuf;
                    item.cchTextMax = strlen(szBuf);
                    ListView_InsertItem(GetDlgItem(hPropDialog, IDC_CUSTOM), &item);

                    VariantToString(this, &pPropVar[i], szBuf, 255);
                    item.iSubItem = 1;
                    item.pszText = szBuf;
                    item.cchTextMax = strlen(szBuf);
                    ListView_SetItem(GetDlgItem(hPropDialog, IDC_CUSTOM), &item);

                    TypeNameFromVariant(this, &pPropVar[i], szBuf, 255);
                    item.iSubItem = 2;
                    item.pszText = szBuf;
                    item.cchTextMax = strlen(szBuf);
                    ListView_SetItem(GetDlgItem(hPropDialog, IDC_CUSTOM), &item);
                }
            }

            for (int i=0; i<idx; i++) {
                CoTaskMemFree(pPropSpec[i].lpwstr);
            }

            FreePropVariantArray(numUserProps, pPropVar);

            delete [] pPropSpec;
            delete [] pPropVar;
        }

        pUserDefinedPropertyStorage->Release();
    }

    pPropertySetStorage->Release();
    pStorage->Release();
}
コード例 #7
0
ファイル: Dlapi.c プロジェクト: NaldoDj/notepad2
//=============================================================================
//
//  DirList_Fill()
//
//  Snapshots a directory and displays the items in the listview control
//
int DirList_Fill(HWND hwnd,LPCWSTR lpszDir,DWORD grfFlags,LPCWSTR lpszFileSpec,
                 BOOL bExcludeFilter,BOOL bNoFadeHidden,
                 int iSortFlags,BOOL fSortRev)
{

  WCHAR wszDir[MAX_PATH];

  LPSHELLFOLDER lpsfDesktop = NULL;
  LPSHELLFOLDER lpsf = NULL;

  LPITEMIDLIST  pidl = NULL;
  LPITEMIDLIST  pidlEntry = NULL;

  LPENUMIDLIST  lpe = NULL;

  LV_ITEM       lvi;
  LPLV_ITEMDATA lplvid;

  ULONG chParsed = 0;
  ULONG dwAttributes = 0;

  DL_FILTER dlf;
  SHFILEINFO shfi;

  LPDLDATA lpdl = (LPVOID)GetProp(hwnd,pDirListProp);

  // Initialize default icons
  SHGetFileInfo(L"Icon",FILE_ATTRIBUTE_DIRECTORY,&shfi,sizeof(SHFILEINFO),
    SHGFI_USEFILEATTRIBUTES | SHGFI_SMALLICON | SHGFI_SYSICONINDEX);
  lpdl->iDefIconFolder = shfi.iIcon;

  SHGetFileInfo(L"Icon",FILE_ATTRIBUTE_NORMAL,&shfi,sizeof(SHFILEINFO),
    SHGFI_USEFILEATTRIBUTES | SHGFI_SMALLICON | SHGFI_SYSICONINDEX);
  lpdl->iDefIconFile = shfi.iIcon;

  // First of all terminate running icon thread
  DirList_TerminateIconThread(hwnd);

  // A Directory is strongly required
  if (!lpszDir || !*lpszDir)
    return(-1);

  lstrcpy(lpdl->szPath,lpszDir);

  // Init ListView
  SendMessage(hwnd,WM_SETREDRAW,0,0);
  ListView_DeleteAllItems(hwnd);

  // Init Filter
  DirList_CreateFilter(&dlf,lpszFileSpec,bExcludeFilter);

  // Init lvi
  lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
  lvi.iItem = 0;
  lvi.iSubItem = 0;
  lvi.pszText = LPSTR_TEXTCALLBACK;
  lvi.cchTextMax = MAX_PATH;
  lvi.iImage = I_IMAGECALLBACK;

  // Convert Directory to a UNICODE string
  /*MultiByteToWideChar(CP_ACP,
                      MB_PRECOMPOSED,
                      lpszDir,
                      -1,
                      wszDir,
                      MAX_PATH);*/
  lstrcpy(wszDir,lpszDir);


  // Get Desktop Folder
  if (NOERROR == SHGetDesktopFolder(&lpsfDesktop))
  {

    // Convert wszDir into a pidl
    if (NOERROR == lpsfDesktop->lpVtbl->ParseDisplayName(
                                          lpsfDesktop,
                                          hwnd,
                                          NULL,
                                          wszDir,
                                          &chParsed,
                                          &pidl,
                                          &dwAttributes))

    {

      // Bind pidl to IShellFolder
      if (NOERROR == lpsfDesktop->lpVtbl->BindToObject(
                                            lpsfDesktop,
                                            pidl,
                                            NULL,
                                            &IID_IShellFolder,
                                            &lpsf))

      {

        // Create an Enumeration object for lpsf
        if (NOERROR == lpsf->lpVtbl->EnumObjects(
                                        lpsf,
                                        hwnd,
                                        grfFlags,
                                        &lpe))

        {

          // Enumerate the contents of lpsf
          while (NOERROR == lpe->lpVtbl->Next(
                                            lpe,
                                            1,
                                            &pidlEntry,
                                            NULL))

          {

            // Add found item to the List
            // Check if it's part of the Filesystem
            dwAttributes = SFGAO_FILESYSTEM | SFGAO_FOLDER;

            lpsf->lpVtbl->GetAttributesOf(
                            lpsf,
                            1,
                            &pidlEntry,
                            &dwAttributes);

            if (dwAttributes & SFGAO_FILESYSTEM)
            {

              // Check if item matches specified filter
              if (DirList_MatchFilter(lpsf,pidlEntry,&dlf))
              {

                lplvid = CoTaskMemAlloc(sizeof(LV_ITEMDATA));

                lplvid->pidl = pidlEntry;
                lplvid->lpsf = lpsf;

                lpsf->lpVtbl->AddRef(lpsf);

                lvi.lParam = (LPARAM)lplvid;

                // Setup default Icon - Folder or File
                lvi.iImage = (dwAttributes & SFGAO_FOLDER) ?
                  lpdl->iDefIconFolder : lpdl->iDefIconFile;

                ListView_InsertItem(hwnd,&lvi);

                lvi.iItem++;

              }

            }

          } // IEnumIDList::Next()

          lpe->lpVtbl->Release(lpe);

        } // IShellFolder::EnumObjects()

      } // IShellFolder::BindToObject()

    } // IShellFolder::ParseDisplayName()

    lpsfDesktop->lpVtbl->Release(lpsfDesktop);

  } // SHGetDesktopFolder()

  if (lpdl->pidl)
    CoTaskMemFree(lpdl->pidl);

  if (lpdl->lpsf && lpdl->lpsf->lpVtbl)
    lpdl->lpsf->lpVtbl->Release(lpdl->lpsf);

  // Set lpdl
  lpdl->cbidl = IL_GetSize(pidl);
  lpdl->pidl = pidl;
  lpdl->lpsf = lpsf;
  lpdl->bNoFadeHidden = bNoFadeHidden;

  // Set column width to fit window
  ListView_SetColumnWidth(hwnd,0,LVSCW_AUTOSIZE_USEHEADER);

  // Sort before display is updated
  DirList_Sort(hwnd,iSortFlags,fSortRev);

  // Redraw Listview
  SendMessage(hwnd,WM_SETREDRAW,1,0);

  // Return number of items in the control
  return (ListView_GetItemCount(hwnd));

}
コード例 #8
0
ファイル: RowsetChange.cpp プロジェクト: CUBRID/cubrid-oledb
STDMETHODIMP CCUBRIDRowset::Update(HCHAPTER hReserved, DBCOUNTITEM cRows, const HROW rghRows[],
				DBCOUNTITEM *pcRows, HROW **prgRows, DBROWSTATUS **prgRowStatus)
{
	ATLTRACE(atlTraceDBProvider, 2, "CCUBRIDRowset::Update\n");

	ClearError();
	if(m_nStatus==1) return RaiseError(E_UNEXPECTED, 1, __uuidof(IRowsetUpdate), L"This object is in a zombie state");
	CHECK_RESTART(__uuidof(IRowsetUpdate));

	DBCOUNTITEM ulRows = 0; // update할 row 수
	bool bNotIgnore = true; // prgRows, prgRowStatus를 무시할지 여부를 나타냄

	// the following lines are used to fix the two _alloca calls below.  Those calls are risky 
	// because we may be allocating huge amounts of data.  So instead I'll allocate that data on heap.
	// But if you use _alloca you don't have to worry about cleaning this memory.  So we will use these
	// temporary variables to allocate memory on heap.  As soon as we exit the function, the memory will
	// be cleaned up, just as if we were using alloca. So now, instead of calling alloca, I'll alloc
	// memory on heap using the two smnart pointers below, and then assing it to the actual pointers.
	CHeapPtr<HROW> spTempRows;
	CHeapPtr<DBROWSTATUS> spTempRowStatus;

	if(cRows || pcRows)
	{
		if(prgRows) *prgRows = NULL;
		if(prgRowStatus) *prgRowStatus = NULL;		
	}
	else
	{
		bNotIgnore = false;		// Don't do status or row arrays
	}

	// Check to see how many changes we'll undo 
	if(pcRows)
	{
		*pcRows = NULL;
		if(prgRows==NULL) return E_INVALIDARG;
	}

	if(cRows)
	{
		if(rghRows==NULL) return E_INVALIDARG;
		ulRows = cRows;
	}
	else
		ulRows = (DBCOUNTITEM)m_rgRowHandles.GetCount();

	int hConn = GetSessionPtr()->GetConnection();
	UINT uCodepage = GetSessionPtr()->GetCodepage();
	// NULL out pointers
	{
		if(prgRows && ulRows && bNotIgnore)
		{
			// Make a temporary buffer as we may not fill up everything
			// in the case where cRows == 0
			if(cRows)
				*prgRows = (HROW*)CoTaskMemAlloc(ulRows * sizeof(HROW));
			else
			{
				spTempRows.Allocate(ulRows);
				*prgRows = spTempRows;
			}
			if (*prgRows==NULL) return E_OUTOFMEMORY;
		}

		if(prgRowStatus && ulRows && bNotIgnore)
		{
			if(cRows)
				*prgRowStatus = (DBROWSTATUS*)CoTaskMemAlloc(ulRows * sizeof(DBROWSTATUS));
			else
			{
				spTempRowStatus.Allocate(ulRows);
				*prgRowStatus = spTempRowStatus;
			}
			if(*prgRowStatus==NULL)
			{
				if(cRows) CoTaskMemFree(*prgRows);
				*prgRows = NULL;
				return E_OUTOFMEMORY;
			}
		}
	}

	bool bSucceeded = false;
	bool bFailed = false;
	ULONG ulCount = 0; // update된 row 수
	POSITION pos = m_rgRowHandles.GetStartPosition();
	for (ULONG ulRow = 0; ulRow < ulRows; ulRow++)
	{
		ULONG ulCurrentRow = ulCount;
		bool bDupRow = false; // 중복된 row
		ULONG ulAlreadyProcessed = 0; // 중복된 row의 handle의 위치

		HROW hRowUpdate = NULL; // 현재 update할 row의 handle
		{
			if(cRows)
			{	// row handle이 주어졌음
				hRowUpdate = rghRows[ulRow];
				for (ULONG ulCheckDup = 0; ulCheckDup < ulRow; ulCheckDup++)
				{
					if (hRowUpdate==rghRows[ulCheckDup] ||
						IsSameRow(hRowUpdate, rghRows[ulCheckDup]) == S_OK)
					{
						ulAlreadyProcessed = ulCheckDup;
						bDupRow = true;
						break;
					}
				}
			}
			else
			{	// 모든 row에 대해 update
				//ATLASSERT(ulRow < (ULONG)m_rgRowHandles.GetCount()); // delete된 row가 있으면 성립하지 않는다.
				ATLASSERT( pos != NULL );
				MapClass::CPair* pPair = m_rgRowHandles.GetNext(pos);
				ATLASSERT( pPair != NULL );
				hRowUpdate = pPair->m_key;
			}
		}

		if(prgRows && bNotIgnore)
			(*prgRows)[ulCurrentRow] = hRowUpdate;

		if(bDupRow)
		{
			// We've already set the row before, just copy status and
			// continue processing
			if(prgRowStatus && bNotIgnore)
				(*prgRowStatus)[ulCurrentRow] = (*prgRowStatus)[ulAlreadyProcessed];
			ulCount++;
			continue;
		}

		// Fetch the RowClass and determine if it is valid
		CCUBRIDRowsetRow *pRow;
		{
			bool bFound = m_rgRowHandles.Lookup((ULONG)hRowUpdate, pRow);
			if (!bFound || pRow == NULL)
			{
				if (prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_E_INVALID;
				bFailed = true;
				ulCount++;
				continue;
			}
		}

		// If cRows is zero we'll go through all rows fetched.  We
		// shouldn't increment the attempted count for rows that are
		// not changed
		if (cRows != 0 || (pRow != NULL &&
			pRow->m_status != 0 && pRow->m_status != DBPENDINGSTATUS_UNCHANGED
			&& pRow->m_status != DBPENDINGSTATUS_INVALIDROW))
			ulCount++;
		else
			continue;

		if(cRows==0)
			pRow->AddRefRow();

		switch (pRow->m_status)
		{
		case DBPENDINGSTATUS_INVALIDROW:	// Row is bad or deleted
			{
				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_E_DELETED;
				bFailed = true;
			}
			break;
		case DBPENDINGSTATUS_UNCHANGED:
		case 0:
			{
				// If the row's status is not changed, then just put S_OK
				// and continue.  The spec says we should not transmit the
				// request to the data source (as nothing would change).
				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_S_OK;
				bSucceeded = true;
			}
			break;
		default:
			{
				DBORDINAL cCols;
				ATLCOLUMNINFO *pColInfo = GetColumnInfo(this, &cCols);
				HRESULT hr = pRow->WriteData(hConn, uCodepage, GetRequestHandle(), m_strTableName);
				if(FAILED(hr))
				{
					DBROWSTATUS stat = DBROWSTATUS_E_FAIL;
					if(hr==DB_E_INTEGRITYVIOLATION) stat = DBROWSTATUS_E_INTEGRITYVIOLATION;
					if(prgRowStatus && bNotIgnore)
						(*prgRowStatus)[ulCurrentRow] = stat;
					bFailed = true;
				}
				else
				{
					//// m_iRowset을 적당히 조정한다.
					//if(pRow->m_status==DBPENDINGSTATUS_NEW)
					//{
					//	// NEW인 row는 항상 rowset의 뒤에 몰려있다.
					//	// 그 row 중 가장 작은 m_iRowset이 update 된 row의 m_iRowset이 되면 된다.
					//	CCUBRIDRowsetRow::KeyType key = pRow->m_iRowset;
					//	POSITION pos = m_rgRowHandles.GetStartPosition();
					//	while(pos)
					//	{
					//		CCUBRIDRowset::MapClass::CPair *pPair = m_rgRowHandles.GetNext(pos);
					//		ATLASSERT(pPair);
					//		CCUBRIDRowsetRow *pCheckRow = pPair->m_value;
					//		if( pCheckRow && pCheckRow->m_iRowset < key )
					//		{
					//			if(pCheckRow->m_iRowset<pRow->m_iRowset)
					//				pRow->m_iRowset = pCheckRow->m_iRowset;
					//			pCheckRow->m_iRowset++;
					//		}
					//	}

					//	// TODO: 북마크 업데이트가 필요한데 어떻게 해야 할지 모르겠다.

					//	// 새로 추가된 Row의 OID를 읽어들인다.
					//	pRow->ReadData(GetRequestHandle(), true);
					//}

					if(pRow->m_status==DBPENDINGSTATUS_DELETED)
						MakeRowInvalid(this, pRow);
					else
						pRow->m_status = DBPENDINGSTATUS_UNCHANGED;

					if(prgRowStatus && bNotIgnore)
						(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_S_OK;
					bSucceeded = true;

					// Check if we need to release the row because it's ref was 0
					// See the IRowset::ReleaseRows section in the spec for more
					// information
					if (pRow->m_dwRef == 0)
					{
						pRow->AddRefRow();	// Artifically bump this to remove it
						if( FAILED( RefRows(1, &hRowUpdate, NULL, NULL, false) ) )
							return E_FAIL;
					}
				}
			}
			break;
		}
	}

	// Set the output for rows undone.
	if(pcRows) *pcRows = ulCount;

	if(ulCount==0)
	{
		if(prgRows)
		{
			CoTaskMemFree(*prgRows);
			*prgRows = NULL;
		}

		if(prgRowStatus)
		{
			CoTaskMemFree(*prgRowStatus);
			*prgRowStatus = NULL;
		}
	}
	else if(cRows==0)
	{
		// In the case where cRows == 0, we need to allocate the final
		// array of data.
		if(prgRows && bNotIgnore)
		{
			HROW *prgRowsTemp = (HROW *)CoTaskMemAlloc(ulCount*sizeof(HROW));
			if(prgRowsTemp==NULL) return E_OUTOFMEMORY;
			memcpy(prgRowsTemp, *prgRows, ulCount*sizeof(HROW));
			*prgRows = prgRowsTemp;
		}

		if(prgRowStatus && bNotIgnore)
		{
			DBROWSTATUS *prgRowStatusTemp = (DBROWSTATUS *)CoTaskMemAlloc(ulCount*sizeof(DBROWSTATUS));
			if(prgRowStatusTemp==NULL)
			{
				CoTaskMemFree(*prgRows);
				*prgRows = NULL;
				return E_OUTOFMEMORY;
			}
			memcpy(prgRowStatusTemp, *prgRowStatus, ulCount*sizeof(DBROWSTATUS));
			*prgRowStatus = prgRowStatusTemp;
		}
	}

	DoCommit(this); // commit

	// Send the return value
	if(!bFailed)
		return S_OK;
	else
	{
		return bSucceeded ? DB_S_ERRORSOCCURRED : DB_E_ERRORSOCCURRED;
	}
}
コード例 #9
0
ファイル: mpvlcsource.cpp プロジェクト: Yura80/mpvlcsource
bool CMPVlcSourceStream::Load(const TCHAR* fn)
{
    char def_options[512];
    char def_sout[512];


    LogDebug("Load()");
    Clear();

    strncpy(m_fn, fn, sizeof(m_fn));

    sprintf(m_pipename, "\\\\.\\pipe\\vlc2ds_%d_%d", GetCurrentThreadId(), GetTickCount());

    LogDebug("Creating named pipe %s", m_pipename);
    m_hPipe = CreateNamedPipe(
                  m_pipename,             // pipe name
                  PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,       // read/write access
                  PIPE_TYPE_MESSAGE |       // message type pipe
                  PIPE_READMODE_BYTE |   // message-read mode
                  PIPE_WAIT,                // blocking mode
                  PIPE_UNLIMITED_INSTANCES, // max. instances
                  IPTV_BUFFER_SIZE,                  // output buffer size
                  IPTV_BUFFER_SIZE,                  // input buffer size
                  0,                        // client time-out
                  NULL);                    // default security attribute
    if (!m_hPipe)
    {
        LogError("CreateNamedPipe failed");
        return false;
    }
    /* Load the VLC engine */
    m_vlc = libvlc_new (0, NULL);
    if (!m_vlc)
    {
        LogError("libvlc_new failed");
        return false;
    }


    // parse input MRL and options
    GetPrivateProfileString("main", "options", "", def_options, sizeof(def_options), m_inifile);
    GetPrivateProfileString("main", "sout", "file{mux=ts,dst=\"\\%s\"}", def_sout, sizeof(def_sout), m_inifile);

    if (strlen(def_options) > 0)
    {
        strcat_s(m_fn, " ");
        strcat_s(m_fn, def_options);
    }

    LogInfo("Adding media: %s", m_fn);

    int argc;
    m_argv = CommandLineToArgvA(m_fn, &argc);
    m_options = (char**)CoTaskMemAlloc(argc * sizeof(char*));

    int nopt = 0;
    int noremux = -1;
    char *opt_out = 0;
    for (int n = 0; n < argc; n++)
    {
        if (m_argv[n][0] == '-' && m_argv[n][1] == '-')
            m_options[nopt] = m_argv[n] + 2;
        else if (m_argv[n][0] == ':')
            m_options[nopt] = m_argv[n] + 1;
        else
        {
            strncpy(m_input, m_argv[n], sizeof(m_input));
            continue;
        }

        if (strncmp(m_options[nopt], "sout", 4) == 0)			// disable direct ts dump if there are any sout options
            noremux = 0;

        if (strncmp(m_options[nopt], "sout=", 5) == 0)
            opt_out = m_options[nopt] + 5;
        else if (strncmp(m_options[nopt], "exec=", 5) == 0)
            m_exec = m_options[nopt] + 5;
        else if (strncmp(m_options[nopt], "exec-opt=", 9) == 0)
            m_exec_opt = m_options[nopt] + 9;
        else if (strncmp(m_options[nopt], "exec-wait=", 10) == 0)
            m_exec_wait = atoi(m_options[nopt] + 10);
        else if (strncmp(m_options[nopt], "no-remux", 8) == 0 && noremux == -1)
            noremux = 1;
        else
            nopt++;
    }


    char t_output[512];
    if (noremux == 1)
    {
        sprintf_s(m_dump_opt, "ts-dump-file=%s", m_pipename);
        m_options[nopt++] = m_dump_opt;
        strcpy_s(m_output, "#dummy");
    }
    else
    {
        sprintf_s(t_output, def_sout, m_pipename);
        if (opt_out)
            sprintf_s(m_output, "%s:%s", opt_out, t_output);
        else
            sprintf_s(m_output, "#%s", t_output);
    }

    LogDebug("input=%s", m_input);
    LogDebug("output=%s", m_output);
    for (int i = 0; i < nopt; i++)
        LogDebug("options[%d]=%s", i, m_options[i]);

    if (libvlc_vlm_add_broadcast(m_vlc, "vlc_ds_stream", m_input, m_output, nopt, m_options, true, 0) != 0)
    {
        LogError("libvlc_vlm_add_broadcast failed");
        return false;
    }
    return true;
}
コード例 #10
0
ファイル: RowsetChange.cpp プロジェクト: CUBRID/cubrid-oledb
STDMETHODIMP CCUBRIDRowset::GetPendingRows(HCHAPTER hReserved, DBPENDINGSTATUS dwRowStatus,
				DBCOUNTITEM *pcPendingRows, HROW **prgPendingRows,
				DBPENDINGSTATUS **prgPendingStatus)
{
	ATLTRACE(atlTraceDBProvider, 2, "CCUBRIDRowset::GetPendingRows\n");

	ClearError();
	if(m_nStatus==1) return RaiseError(E_UNEXPECTED, 1, __uuidof(IRowsetUpdate), L"This object is in a zombie state");

	bool bPending = false;
	CCUBRIDRowsetRow *pRow = NULL;

	if(pcPendingRows)
	{
		*pcPendingRows = 0;
		if(prgPendingRows) *prgPendingRows = NULL;
		if(prgPendingStatus) *prgPendingStatus = NULL;
	}

	// Validate input parameters
	if ((dwRowStatus & 
		~(DBPENDINGSTATUS_NEW | DBPENDINGSTATUS_CHANGED | DBPENDINGSTATUS_DELETED)) != 0)
		return E_INVALIDARG;

	// Determine how many rows we'll need to return

	POSITION pos = m_rgRowHandles.GetStartPosition();
	while( pos != NULL )
	{
		MapClass::CPair* pPair = m_rgRowHandles.GetNext( pos );
		ATLASSERT( pPair != NULL );

		// Check to see if a row has a pending status
		pRow = pPair->m_value;

		if (pRow->m_status & dwRowStatus)
		{
			if (pcPendingRows != NULL)
				(*pcPendingRows)++;
			bPending = true;
		}
	}

	// In this case, there are no pending rows that match, just exit out
	if (!bPending)
	{
		// There are no pending rows so exit immediately
		return S_FALSE;
	}
	else
	{
		// Here' the consumer just wants to see if there are pending rows
		// we know that so we can exit
		if (pcPendingRows == NULL)
			return S_OK;
	}

	// Allocate arrays for pending rows
	{
		if (prgPendingRows != NULL)
		{
			*prgPendingRows = (HROW*)CoTaskMemAlloc(*pcPendingRows * sizeof(HROW));
			if (*prgPendingRows == NULL)
			{
				*pcPendingRows = 0;
				return E_OUTOFMEMORY;
			}
		}

		if (prgPendingStatus != NULL)
		{
			*prgPendingStatus = (DBPENDINGSTATUS*)CoTaskMemAlloc(*pcPendingRows * sizeof(DBPENDINGSTATUS));
			if (*prgPendingStatus == NULL)
			{
				*pcPendingRows = 0;
				CoTaskMemFree(*prgPendingRows);
				*prgPendingRows = NULL;
				return E_OUTOFMEMORY;
			}
			memset(*prgPendingStatus, 0, *pcPendingRows * sizeof(DBPENDINGSTATUS));
		}
	}

	if (prgPendingRows || prgPendingStatus)
	{
		ULONG ulRows = 0;
		pos = m_rgRowHandles.GetStartPosition();
		while( pos != NULL )
		{
			MapClass::CPair* pPair = m_rgRowHandles.GetNext( pos );
			ATLASSERT( pPair != NULL );

			pRow = pPair->m_value;
			if (pRow->m_status & dwRowStatus)
			{
				// Add the output row
				pRow->AddRefRow();
				if (prgPendingRows)
					((*prgPendingRows)[ulRows]) = /*(HROW)*/pPair->m_key;
				if (prgPendingStatus)
					((*prgPendingStatus)[ulRows]) = (DBPENDINGSTATUS)pRow->m_status;
				ulRows++;
			}
		}
		if (pcPendingRows != NULL)
			*pcPendingRows = ulRows;
	}

	// Return code depending on
	return S_OK;
}
コード例 #11
0
ファイル: RowsetChange.cpp プロジェクト: CUBRID/cubrid-oledb
STDMETHODIMP CCUBRIDRowset::Undo(HCHAPTER hReserved, DBCOUNTITEM cRows, const HROW rghRows[],
				DBCOUNTITEM *pcRowsUndone, HROW **prgRowsUndone, DBROWSTATUS **prgRowStatus)
{
	ATLTRACE(atlTraceDBProvider, 2, "CCUBRIDRowset::Undo\n");

	ClearError();
	if(m_nStatus==1) return RaiseError(E_UNEXPECTED, 1, __uuidof(IRowsetUpdate), L"This object is in a zombie state");
	CHECK_RESTART(__uuidof(IRowsetUpdate));

	DBCOUNTITEM ulRows = 0; // undo할 row 수
	bool bNotIgnore = true; // prgRowsUndone, prgRowStatus를 무시할지 여부를 나타냄

	// the following lines are used to fix the two _alloca calls below.  Those calls are risky 
	// because we may be allocating huge amounts of data.  So instead I'll allocate that data on heap.
	// But if you use _alloca you don't have to worry about cleaning this memory.  So we will use these
	// temporary variables to allocate memory on heap.  As soon as we exit the function, the memory will
	// be cleaned up, just as if we were using alloca. So now, instead of calling alloca, I'll alloc
	// memory on heap using the two smnart pointers below, and then assing it to the actual pointers.
	CHeapPtr<HROW> spTempRowsUndone;
	CHeapPtr<DBROWSTATUS> spTempRowStatus;

	if(cRows || pcRowsUndone)
	{
		if(prgRowsUndone) *prgRowsUndone = NULL;
		if(prgRowStatus) *prgRowStatus = NULL;		
	}
	else
	{
		bNotIgnore = false;		// Don't do status or row arrays
	}

	// Check to see how many changes we'll undo 
	if(pcRowsUndone)
	{
		*pcRowsUndone = NULL;
		if(prgRowsUndone==NULL) return E_INVALIDARG;
	}

	if(cRows)
	{
		if(rghRows==NULL) return E_INVALIDARG;
		ulRows = cRows;
	}
	else
		ulRows = (DBCOUNTITEM)m_rgRowHandles.GetCount();

	// NULL out pointers
	{
		if(prgRowsUndone && ulRows && bNotIgnore)
		{
			// Make a temporary buffer as we may not fill up everything
			// in the case where cRows == 0
			if(cRows)
				*prgRowsUndone = (HROW*)CoTaskMemAlloc(ulRows * sizeof(HROW));
			else
			{
				spTempRowsUndone.Allocate(ulRows);
				*prgRowsUndone = spTempRowsUndone;
			}
			if (*prgRowsUndone==NULL) return E_OUTOFMEMORY;
		}

		if(prgRowStatus && ulRows && bNotIgnore)
		{
			if(cRows)
				*prgRowStatus = (DBROWSTATUS*)CoTaskMemAlloc(ulRows * sizeof(DBROWSTATUS));
			else
			{
				spTempRowStatus.Allocate(ulRows);
				*prgRowStatus = spTempRowStatus;
			}
			if(*prgRowStatus==NULL)
			{
				if(cRows) CoTaskMemFree(*prgRowsUndone);
				*prgRowsUndone = NULL;
				return E_OUTOFMEMORY;
			}
		}
	}

	bool bSucceeded = false;
	bool bFailed = false;
	ULONG ulUndone = 0; // undo된 row 수
	POSITION pos = m_rgRowHandles.GetStartPosition();
	for (ULONG ulUndoRow = 0; ulUndoRow < ulRows; ulUndoRow++)
	{
		ULONG ulCurrentRow = ulUndone;

		HROW hRowUndo = NULL; // 현재 undo할 row의 handle
		{
			if(cRows)
			{	// row handle이 주어졌음
				hRowUndo = rghRows[ulUndoRow];
			}
			else
			{	// 모든 row에 대해 undo
				// ATLASSERT(ulUndoRow < (ULONG)m_rgRowHandles.GetCount()); // delete된 row가 있으면 성립하지 않는다.
				ATLASSERT( pos != NULL );
				MapClass::CPair* pPair = m_rgRowHandles.GetNext(pos);
				ATLASSERT( pPair != NULL );
				hRowUndo = pPair->m_key;
			}
		}

		if(prgRowsUndone && bNotIgnore)
			(*prgRowsUndone)[ulCurrentRow] = hRowUndo;

		// Fetch the RowClass and determine if it is valid
		CCUBRIDRowsetRow *pRow;
		{
			bool bFound = m_rgRowHandles.Lookup((ULONG)hRowUndo, pRow);
			if (!bFound || pRow == NULL)
			{
				if (prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_E_INVALID;
				bFailed = true;
				ulUndone++;
				continue;
			}
		}

		// If cRows is zero we'll go through all rows fetched.  We shouldn't
		// increment the count for rows that haven't been modified.
		if (cRows != 0 || (pRow != NULL &&
			pRow->m_status != 0 && pRow->m_status != DBPENDINGSTATUS_UNCHANGED
			&& pRow->m_status != DBPENDINGSTATUS_INVALIDROW))
			ulUndone++;
		else
			continue;

		if(cRows==0)
			pRow->AddRefRow();

		switch (pRow->m_status)
		{
		case DBPENDINGSTATUS_INVALIDROW:
			// 메모리와 storage 모두 존재하지 않는 row
			{
				// provider templates에서는 DELETED인데
				// INVALID가 더 맞지 않을까 싶기도 한다.
				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_E_DELETED;
				bFailed = true;
			}
			break;
		case DBPENDINGSTATUS_NEW:
			// 메모리 상에만 존재하는 row
			{
				// If the row is newly inserted, go ahead and mark its
				// row as INVALID (according to the specification).

				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_S_OK;

				MakeRowInvalid(this, pRow);

				bSucceeded = true;
			}
			break;
		case DBPENDINGSTATUS_CHANGED:
		case DBPENDINGSTATUS_DELETED:
			// storage의 데이터를 가져와야 하는 경우
			// delete 된 경우 메모리에 데이터가 있지만, CHANGED->DELETED 인 경우도 있을 수 있다.
			{
				// read data back
				pRow->ReadData(GetRequestHandle());
				pRow->m_status = DBPENDINGSTATUS_UNCHANGED;

				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_S_OK;
				bSucceeded = true;
			}
			break;
		default: // 0, DBPENDINGSTATUS_UNCHANGED, 
			// storage의 데이터를 가져올 필요가 없는 경우
			{
				pRow->m_status = DBPENDINGSTATUS_UNCHANGED;

				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_S_OK;
				bSucceeded = true;
			}
			break;
		}

		// Check if we need to release the row because it's ref was 0
		// See the IRowset::ReleaseRows section in the spec for more
		// information
		if (pRow->m_dwRef == 0)
		{
			pRow->AddRefRow();	// Artifically bump this to remove it
			if( FAILED( RefRows(1, &hRowUndo, NULL, NULL, false) ) )
				return E_FAIL;
		}
	}

	// Set the output for rows undone.
	if(pcRowsUndone) *pcRowsUndone = ulUndone;

	if(ulUndone==0)
	{
		if(prgRowsUndone)
		{
			CoTaskMemFree(*prgRowsUndone);
			*prgRowsUndone = NULL;
		}

		if(prgRowStatus)
		{
			CoTaskMemFree(*prgRowStatus);
			*prgRowStatus = NULL;
		}
	}
	else if(cRows==0)
	{
		// In the case where cRows == 0, we need to allocate the final
		// array of data.
		if(prgRowsUndone && bNotIgnore)
		{
			HROW *prgRowsTemp = (HROW *)CoTaskMemAlloc(ulUndone*sizeof(HROW));
			if(prgRowsTemp==NULL) return E_OUTOFMEMORY;
			memcpy(prgRowsTemp, *prgRowsUndone, ulUndone*sizeof(HROW));
			*prgRowsUndone = prgRowsTemp;
		}

		if(prgRowStatus && bNotIgnore)
		{
			DBROWSTATUS *prgRowStatusTemp = (DBROWSTATUS *)CoTaskMemAlloc(ulUndone*sizeof(DBROWSTATUS));
			if(prgRowStatusTemp==NULL)
			{
				CoTaskMemFree(*prgRowsUndone);
				*prgRowsUndone = NULL;
				return E_OUTOFMEMORY;
			}
			memcpy(prgRowStatusTemp, *prgRowStatus, ulUndone*sizeof(DBROWSTATUS));
			*prgRowStatus = prgRowStatusTemp;
		}
	}

	// Send the return value
	if(!bFailed)
		return S_OK;
	else
	{
		return bSucceeded ? DB_S_ERRORSOCCURRED : DB_E_ERRORSOCCURRED;
	}
}
コード例 #12
0
bool CSoundComponent::InitXACT(const char* engine_xgs)
{
	HRESULT hr;
	CoInitializeEx( NULL, COINIT_MULTITHREADED );  // COINIT_APARTMENTTHREADED will work too
	//TODO("Create the XACT engine");
	hr=XACT3CreateEngine(0, &mpXEngine);

	if( FAILED( hr ) || mpXEngine == NULL )
	{
		FAIL("Problems creating XACT engine","InitXACT Failed");
		return false;
	}

	// Load the global settings file and pass it into XACTInitialize
	VOID* pGlobalSettingsData = NULL;
	DWORD dwGlobalSettingsFileSize = 0;
	bool bSuccess = false;
	HANDLE hFile = CreateFile( engine_xgs, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
	if( hFile!=INVALID_HANDLE_VALUE )
	{
		dwGlobalSettingsFileSize = GetFileSize( hFile, NULL );
		if( dwGlobalSettingsFileSize != INVALID_FILE_SIZE )
		{
			pGlobalSettingsData = CoTaskMemAlloc( dwGlobalSettingsFileSize );
			if( pGlobalSettingsData )
			{
				DWORD dwBytesRead;
				if( 0 != ReadFile( hFile, pGlobalSettingsData, dwGlobalSettingsFileSize, &dwBytesRead, NULL ) )
				{
					bSuccess = true;
				}
			}
		}
		CloseHandle( hFile );
	}
	if( !bSuccess )
	{
		if( pGlobalSettingsData )
			CoTaskMemFree( pGlobalSettingsData );
		pGlobalSettingsData = NULL;
		dwGlobalSettingsFileSize = 0;
		FAIL(engine_xgs,"Problems opening engine file");
		return false;
	}

	// Initialize & create the XACT runtime 
	XACT_RUNTIME_PARAMETERS xrParams = {0};
	xrParams.lookAheadTime = XACT_ENGINE_LOOKAHEAD_DEFAULT;
	xrParams.pGlobalSettingsBuffer = pGlobalSettingsData;
	xrParams.globalSettingsBufferSize = dwGlobalSettingsFileSize;
	xrParams.globalSettingsFlags = XACT_FLAG_GLOBAL_SETTINGS_MANAGEDATA; // this will tell XACT to delete[] the buffer when its unneeded
	//TODO(Initalise the XACT engine);
	hr=mpXEngine->Initialize(&xrParams);
	if( FAILED( hr ) )
	{
		FAIL(engine_xgs,"Problems Initalising XACT engine");
		return false;
	}

	X3DAUDIO_EMITTER emitter = {0};
	X3DAUDIO_LISTENER listener = {0};

	listener.OrientFront = D3DXVECTOR3( 0, 0, 1 );
	listener.OrientTop = D3DXVECTOR3( 0, 1, 0 );
	listener.Position = D3DXVECTOR3( 0, 0, 0 );
	listener.Velocity = D3DXVECTOR3( 0, 0, 0 );

	// the following need to be orthonormal
	emitter.OrientFront = D3DXVECTOR3( 0, 0, 1 );
	emitter.OrientTop = D3DXVECTOR3( 0, 1, 0 );
	emitter.Position = D3DXVECTOR3( 0, 0, 0 );
	emitter.Velocity = D3DXVECTOR3( 0, 0, 0 ); // needs to not be zero if you want to hear Doppler effect

	// emitter ChannelCount and DSP Setting's SrcChannelCount must match
	emitter.ChannelCount = 2;   

	// this will be set by XACT3DCalculate if ChannelCount > 1.
	emitter.ChannelRadius = 1.0f;   

	// will be set by XACT3DCalculate
	emitter.pChannelAzimuths = NULL;

	// will be set by XACT3DCalculate
	emitter.pVolumeCurve = emitter.pLFECurve
		= emitter.pLPFDirectCurve
		= emitter.pLPFReverbCurve
		= emitter.pReverbCurve
		= NULL;

	emitter.CurveDistanceScaler = 1.0;
	emitter.DopplerScaler = 1.0f;

	hr = XACT3DInitialize(mpXEngine, xact3dInstance);

	if( FAILED( hr ) )
	{
		FAIL(engine_xgs,"Problems Initalising XACT 3D engine");
		return false;
	}

	// check how many output channels are supported
	WAVEFORMATEXTENSIBLE format;
	hr = mpXEngine->GetFinalMixFormat(&format);
	if(FAILED(hr))
	{
		FAIL("BLABLBA");
	}
	// fill the DSP
	ZeroMemory(&dspSettings,sizeof(dspSettings));
	// different code's seem to suggest 1 or 2 channels for the emitter
	dspSettings.SrcChannelCount = 1;
	dspSettings.DstChannelCount = format.Format.nChannels;  // as supported 
	dspSettings.pMatrixCoefficients = new FLOAT32[dspSettings.SrcChannelCount * dspSettings.DstChannelCount];
	ZeroMemory(dspSettings.pMatrixCoefficients ,sizeof(FLOAT32)*dspSettings.SrcChannelCount * dspSettings.DstChannelCount);

	return true;
}
コード例 #13
0
HRESULT FindRFCOMMChannel (unsigned char *pStream, int cStream,
			   unsigned long *nChannel)
{
	ISdpRecord **pRecordArg = NULL;
	int cRecordArg          = 0;
	ISdpStream *pIStream    = NULL;
	HRESULT hr              = 0;
	ULONG ulError           = 0;

	*nChannel = 0;

	hr = CoCreateInstance(__uuidof(SdpStream),NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(ISdpStream),(LPVOID *)
		&pIStream);

	if ( FAILED(hr) || pIStream == NULL )
		return hr;

	hr = pIStream->Validate (pStream, cStream,&ulError);

	if (SUCCEEDED(hr))
	{
		hr = pIStream->VerifySequenceOf(pStream, cStream,
			SDP_TYPE_SEQUENCE,NULL,
			(ULONG *)&cRecordArg);

		if (SUCCEEDED(hr) && cRecordArg > 0)
		{
			pRecordArg =
				(ISdpRecord **) CoTaskMemAlloc(sizeof(ISdpRecord*)
				* cRecordArg);

			if (pRecordArg != NULL)
			{
				hr =
					pIStream->RetrieveRecords(pStream, cStream,
					pRecordArg,(ULONG *)
					&cRecordArg);

				if ( FAILED(hr) )
				{
					CoTaskMemFree(pRecordArg);
					pRecordArg = NULL;
					cRecordArg = 0;
				}
			}
			else
			{
				hr = E_OUTOFMEMORY;
			}
		}
	}

	if (pIStream != NULL)
	{
		pIStream->Release();
		pIStream = NULL;
	}

	if ( FAILED(hr) )
		return hr;

	for (int i = 0; (*nChannel == 0) && (i < cRecordArg); i++)
	{
		ISdpRecord *pRecord = pRecordArg[i];
		// contains SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST data,
		// if available
		NodeData protocolList;

		if (ERROR_SUCCESS !=
			pRecord->GetAttribute(SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST,
			&protocolList) ||
			(protocolList.type !=
			SDP_TYPE_CONTAINER))
		{
			if (protocolList.type == SDP_TYPE_STRING)
				CoTaskMemFree(protocolList.u.str.val);
			else if (protocolList.type == SDP_TYPE_URL)
				CoTaskMemFree(protocolList.u.url.val);
			continue;
		}

		ISdpNodeContainer *pRecordContainer = protocolList.u.container;
		int cProtocols = 0;
		NodeData protocolDescriptor;

		pRecordContainer->GetNodeCount((DWORD *)&cProtocols);
		for (int j = 0; (nChannel == 0) && (j < cProtocols); j++)
		{
			pRecordContainer->GetNode(j,&protocolDescriptor);

			if (protocolDescriptor.type != SDP_TYPE_CONTAINER)
				continue;

			ISdpNodeContainer *pProtocolContainer =
				protocolDescriptor.u.container;
			int cProtocolAtoms = 0;
			pProtocolContainer->GetNodeCount((DWORD *)&cProtocolAtoms);

			for (int k = 0; (nChannel == 0) && (k < cProtocolAtoms); k++)
			{
				NodeData nodeAtom;
				pProtocolContainer->GetNode(k,&nodeAtom);

				if (IsRfcommUuid(&nodeAtom))
				{
					if (k+1 == cProtocolAtoms)
					{
						// Error: Channel ID should follow RFCOMM uuid
						break;
					}

					NodeData channelID;
					pProtocolContainer->GetNode(k+1,&channelID);

					switch(channelID.specificType)
					{
					case SDP_ST_UINT8:
						*nChannel = channelID.u.uint8;
						break;
					case SDP_ST_INT8:
						*nChannel = channelID.u.int8;
						break;
					case SDP_ST_UINT16:
						*nChannel = channelID.u.uint16;
						break;
					case SDP_ST_INT16:
						*nChannel = channelID.u.int16;
						break;
					case SDP_ST_UINT32:
						*nChannel = channelID.u.uint32;
						break;
					case SDP_ST_INT32:
						*nChannel = channelID.u.int32;
						break;
					default:
						*nChannel = 0;
					}
					break;
				}
			}
		}
		if (protocolList.type == SDP_TYPE_STRING)
			CoTaskMemFree(protocolList.u.str.val);
		else if (protocolList.type == SDP_TYPE_URL)
			CoTaskMemFree(protocolList.u.url.val);
	}

	// cleanup
	for (int i = 0; i < cRecordArg; i++)
		pRecordArg[i]->Release();
	CoTaskMemFree(pRecordArg);

	return (*nChannel != 0) ? S_OK : S_FALSE;
}
コード例 #14
0
STDMETHODIMP
CEnumMediaTypes::Next(ULONG cMediaTypes,          // place this many types...
                      AM_MEDIA_TYPE **ppMediaTypes,   // ...in this array
                      ULONG *pcFetched)           // actual count passed
{
    CheckPointer(ppMediaTypes,E_POINTER);
    ValidateReadWritePtr(ppMediaTypes,cMediaTypes * sizeof(AM_MEDIA_TYPE *));
    /* Check we are still in sync with the pin */
    if (AreWeOutOfSync() == TRUE) {
        return VFW_E_ENUM_OUT_OF_SYNC;
    }

    if (pcFetched!=NULL) {
        ValidateWritePtr(pcFetched, sizeof(ULONG));
        *pcFetched = 0;           // default unless we succeed
    }
    // now check that the parameter is valid
    else if (cMediaTypes>1) {     // pcFetched == NULL
        return E_INVALIDARG;
    }
    ULONG cFetched = 0;           // increment as we get each one.

    /* Return each media type by asking the filter for them in turn - If we
    have an error code retured to us while we are retrieving a media type
    we assume that our internal state is stale with respect to the filter
    (for example the window size changing) so we return
    VFW_E_ENUM_OUT_OF_SYNC */

    while (cMediaTypes) {

        CMediaType cmt;

        HRESULT hr = m_pPin->GetMediaType(m_Position++, &cmt);
        if (S_OK != hr) {
            break;
        }

        /* We now have a CMediaType object that contains the next media type
        but when we assign it to the array position we CANNOT just assign
        the AM_MEDIA_TYPE structure because as soon as the object goes out of
        scope it will delete the memory we have just copied. The function
        we use is CreateMediaType which allocates a task memory block */

        /*  Transfer across the format block manually to save an allocate
        and free on the format block and generally go faster */

        *ppMediaTypes = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
        if (*ppMediaTypes == NULL) {
            break;
        }

        /*  Do a regular copy */
        **ppMediaTypes = (AM_MEDIA_TYPE)cmt;

        /*  Make sure the destructor doesn't free these */
        cmt.pbFormat = NULL;
        cmt.cbFormat = NULL;
        cmt.pUnk     = NULL;


        ppMediaTypes++;
        cFetched++;
        cMediaTypes--;
    }

    if (pcFetched!=NULL) {
        *pcFetched = cFetched;
    }

    return ( cMediaTypes==0 ? NOERROR : S_FALSE );
}
コード例 #15
0
ファイル: filemoniker.c プロジェクト: AmesianX/wine
/******************************************************************************
 *        DecomposePath (local function)
 */
int FileMonikerImpl_DecomposePath(LPCOLESTR str, LPOLESTR** stringTable)
{
    static const WCHAR bSlash[] = {'\\',0};
    LPOLESTR word;
    int i=0,j,tabIndex=0, ret=0;
    LPOLESTR *strgtable ;

    int len=lstrlenW(str);

    TRACE("%s, %p\n", debugstr_w(str), *stringTable);

    strgtable = CoTaskMemAlloc((len + 1)*sizeof(*strgtable));

    if (strgtable==NULL)
	return E_OUTOFMEMORY;

    word = CoTaskMemAlloc((len + 1)*sizeof(WCHAR));

    if (word==NULL)
    {
        ret = E_OUTOFMEMORY;
        goto lend;
    }

    while(str[i]!=0){

        if(str[i]==bSlash[0]){

            strgtable[tabIndex]=CoTaskMemAlloc(2*sizeof(WCHAR));

            if (strgtable[tabIndex]==NULL)
            {
                ret = E_OUTOFMEMORY;
                goto lend;
            }

            strcpyW(strgtable[tabIndex++],bSlash);

            i++;

        }
        else {

            for(j=0; str[i]!=0 && str[i]!=bSlash[0] ; i++,j++)
                word[j]=str[i];

            word[j]=0;

            strgtable[tabIndex]=CoTaskMemAlloc(sizeof(WCHAR)*(j+1));

            if (strgtable[tabIndex]==NULL)
            {
                ret = E_OUTOFMEMORY;
                goto lend;
            }

            strcpyW(strgtable[tabIndex++],word);
        }
    }
    strgtable[tabIndex]=NULL;

    *stringTable=strgtable;

    ret = tabIndex;

lend:
    if (ret < 0)
    {
        for (i = 0; i < tabIndex; i++)
            CoTaskMemFree(strgtable[i]);

        CoTaskMemFree(strgtable);
    }

    CoTaskMemFree(word);

    return ret;
}
コード例 #16
0
HRESULT VBoxCredProvCredential::kerberosLogonSerialize(const KERB_INTERACTIVE_LOGON *pLogonIn,
                                                       PBYTE *ppPackage, DWORD *pcbPackage)
{
    AssertPtrReturn(pLogonIn,   E_INVALIDARG);
    AssertPtrReturn(ppPackage,  E_INVALIDARG);
    AssertPtrReturn(pcbPackage, E_INVALIDARG);

    /*
     * First, allocate enough space for the logon structure itself and separate
     * string buffers right after it to store the actual user, password and domain
     * credentials.
     */
    DWORD cbLogon = sizeof(KERB_INTERACTIVE_UNLOCK_LOGON)
                  + pLogonIn->LogonDomainName.Length
                  + pLogonIn->UserName.Length
                  + pLogonIn->Password.Length;

#ifdef DEBUG /* Do not reveal any hints to credential data in release mode. */
    VBoxCredProvVerbose(1, "VBoxCredProvCredential::AllocateLogonPackage: Allocating %ld bytes (%zu bytes credentials)\n",
                        cbLogon, cbLogon - sizeof(KERB_INTERACTIVE_UNLOCK_LOGON));
#endif

    KERB_INTERACTIVE_UNLOCK_LOGON *pLogon = (KERB_INTERACTIVE_UNLOCK_LOGON*)CoTaskMemAlloc(cbLogon);
    if (!pLogon)
        return E_OUTOFMEMORY;

    /* Make sure to zero everything first. */
    RT_BZERO(pLogon, cbLogon);

    /* Let our byte buffer point to the end of our allocated structure so that it can
     * be used to store the credential data sequentially in a binary blob
     * (without terminating \0). */
    PBYTE pbBuffer = (PBYTE)pLogon + sizeof(KERB_INTERACTIVE_UNLOCK_LOGON);

    /* The buffer of the packed destination string does not contain the actual
     * string content but a relative offset starting at the given
     * KERB_INTERACTIVE_UNLOCK_LOGON structure. */
#define KERB_CRED_INIT_PACKED(StringDst, StringSrc, LogonOffset)             \
    StringDst.Length         = StringSrc.Length;                             \
    StringDst.MaximumLength  = StringSrc.Length;                             \
    if (StringDst.Length)                                                    \
    {                                                                        \
        StringDst.Buffer         = (PWSTR)pbBuffer;                          \
        memcpy(StringDst.Buffer, StringSrc.Buffer, StringDst.Length);        \
        StringDst.Buffer         = (PWSTR)(pbBuffer - (PBYTE)LogonOffset);   \
        pbBuffer                += StringDst.Length;                         \
    }

    KERB_INTERACTIVE_LOGON *pLogonOut = &pLogon->Logon;

    pLogonOut->MessageType = pLogonIn->MessageType;

    KERB_CRED_INIT_PACKED(pLogonOut->LogonDomainName, pLogonIn->LogonDomainName, pLogon);
    KERB_CRED_INIT_PACKED(pLogonOut->UserName       , pLogonIn->UserName,        pLogon);
    KERB_CRED_INIT_PACKED(pLogonOut->Password       , pLogonIn->Password,        pLogon);

    *ppPackage  = (PBYTE)pLogon;
    *pcbPackage = cbLogon;

#undef KERB_CRED_INIT_PACKED

    return S_OK;
}
コード例 #17
0
ファイル: filemoniker.c プロジェクト: AmesianX/wine
/******************************************************************************
 *        FileMoniker_CommonPrefixWith
 */
static HRESULT WINAPI
FileMonikerImpl_CommonPrefixWith(IMoniker* iface,IMoniker* pmkOther,IMoniker** ppmkPrefix)
{

    LPOLESTR pathThis = NULL, pathOther = NULL, *stringTable1 = NULL;
    LPOLESTR *stringTable2 = NULL, commonPath = NULL;
    IBindCtx *bindctx;
    DWORD mkSys;
    ULONG nb1,nb2,i,sameIdx;
    BOOL machineNameCase = FALSE;
    HRESULT ret;

    if (ppmkPrefix==NULL)
        return E_POINTER;

    if (pmkOther==NULL)
        return E_INVALIDARG;

    *ppmkPrefix=0;

    /* check if we have the same type of moniker */
    IMoniker_IsSystemMoniker(pmkOther,&mkSys);
    if (mkSys != MKSYS_FILEMONIKER)
        return MonikerCommonPrefixWith(iface, pmkOther, ppmkPrefix);

    ret = CreateBindCtx(0, &bindctx);
    if (FAILED(ret))
        return ret;

    /* create a string based on common part of the two paths */
    ret = IMoniker_GetDisplayName(iface, bindctx, NULL, &pathThis);
    if (FAILED(ret))
        goto failed;

    ret = IMoniker_GetDisplayName(pmkOther, bindctx, NULL, &pathOther);
    if (FAILED(ret))
        goto failed;

    nb1 = FileMonikerImpl_DecomposePath(pathThis, &stringTable1);
    if (FAILED(nb1)) {
        ret = nb1;
        goto failed;
    }

    nb2 = FileMonikerImpl_DecomposePath(pathOther, &stringTable2);
    if (FAILED(nb2)) {
        ret = nb2;
        goto failed;
    }

    if (nb1 == 0 || nb2 == 0) {
        ret = MK_E_NOPREFIX;
        goto failed;
    }

    commonPath = CoTaskMemAlloc(sizeof(WCHAR)*(min(lstrlenW(pathThis),lstrlenW(pathOther))+1));
    if (!commonPath) {
        ret = E_OUTOFMEMORY;
        goto failed;
    }

    *commonPath = 0;
    for(sameIdx=0; ( (stringTable1[sameIdx]!=NULL) &&
                     (stringTable2[sameIdx]!=NULL) &&
                     (lstrcmpiW(stringTable1[sameIdx],stringTable2[sameIdx])==0)); sameIdx++);

    if (sameIdx > 1 && *stringTable1[0]=='\\' && *stringTable2[1]=='\\'){
        machineNameCase = TRUE;

    for(i=2;i<sameIdx;i++)
        if( (*stringTable1[i]=='\\') && (i+1 < sameIdx) && (*stringTable1[i+1]=='\\') ){
            machineNameCase = FALSE;
            break;
        }
    }

    if (machineNameCase && *stringTable1[sameIdx-1]=='\\')
        sameIdx--;

    if (machineNameCase && (sameIdx<=3) && (nb1 > 3 || nb2 > 3) )
        ret = MK_E_NOPREFIX;
    else
    {
        for (i = 0; i < sameIdx; i++)
            strcatW(commonPath,stringTable1[i]);
        ret = CreateFileMoniker(commonPath, ppmkPrefix);
    }

failed:
    IBindCtx_Release(bindctx);
    CoTaskMemFree(pathThis);
    CoTaskMemFree(pathOther);
    CoTaskMemFree(commonPath);
    if (stringTable1) free_stringtable(stringTable1);
    if (stringTable2) free_stringtable(stringTable2);

    return ret;
}
コード例 #18
0
ファイル: usrmarshal.c プロジェクト: pstrealer/wine
static void * WINAPI user_allocate(SIZE_T size)
{
    return CoTaskMemAlloc(size);
}
コード例 #19
0
ファイル: Dlapi.c プロジェクト: NaldoDj/notepad2
int DriveBox_Fill(HWND hwnd)
{

  LPSHELLFOLDER lpsfDesktop;
  LPSHELLFOLDER lpsf; // Workspace == CSIDL_DRIVES

  LPITEMIDLIST  pidl;
  LPITEMIDLIST  pidlEntry;

  LPENUMIDLIST  lpe;

  COMBOBOXEXITEM  cbei;
  LPDC_ITEMDATA   lpdcid;

  ULONG dwAttributes = 0;

  DWORD grfFlags = SHCONTF_FOLDERS;


  // Init ComboBox
  SendMessage(hwnd,WM_SETREDRAW,0,0);
  SendMessage(hwnd,CB_RESETCONTENT,0,0);

  ZeroMemory(&cbei,sizeof(COMBOBOXEXITEM));
  cbei.mask = CBEIF_TEXT | CBEIF_IMAGE | CBEIF_SELECTEDIMAGE | CBEIF_LPARAM;
  cbei.pszText = LPSTR_TEXTCALLBACK;
  cbei.cchTextMax = MAX_PATH;
  cbei.iImage = I_IMAGECALLBACK;
  cbei.iSelectedImage = I_IMAGECALLBACK;


  // Get pidl to [My Computer]
  if (NOERROR == SHGetSpecialFolderLocation(hwnd,
                                            CSIDL_DRIVES,
                                            &pidl))
  {

    // Get Desktop Folder
    if (NOERROR == SHGetDesktopFolder(&lpsfDesktop))
    {

      // Bind pidl to IShellFolder
      if (NOERROR == lpsfDesktop->lpVtbl->BindToObject(
                                            lpsfDesktop,
                                            pidl,
                                            NULL,
                                            &IID_IShellFolder,
                                            &lpsf))

      {

        // Create an Enumeration object for lpsf
        if (NOERROR == lpsf->lpVtbl->EnumObjects(
                                        lpsf,
                                        hwnd,
                                        grfFlags,
                                        &lpe))

        {

          // Enumerate the contents of [My Computer]
          while (NOERROR == lpe->lpVtbl->Next(
                                            lpe,
                                            1,
                                            &pidlEntry,
                                            NULL))

          {

            // Add item to the List if it is part of the
            // Filesystem
            dwAttributes = SFGAO_FILESYSTEM;

            lpsf->lpVtbl->GetAttributesOf(
                            lpsf,
                            1,
                            &pidlEntry,
                            &dwAttributes);

            if (dwAttributes & SFGAO_FILESYSTEM)
            {

              // Windows XP: check if pidlEntry is a drive
              SHDESCRIPTIONID di;
              HRESULT hr;
              hr = SHGetDataFromIDList(lpsf,pidlEntry,SHGDFIL_DESCRIPTIONID,
                                        &di,sizeof(SHDESCRIPTIONID));
              if (hr != NOERROR || (di.dwDescriptionId >= SHDID_COMPUTER_DRIVE35 &&
                                    di.dwDescriptionId <= SHDID_COMPUTER_OTHER))
              {

                lpdcid = CoTaskMemAlloc(sizeof(DC_ITEMDATA));

                //lpdcid->pidl = IL_Copy(pidlEntry);
                lpdcid->pidl = pidlEntry;
                lpdcid->lpsf = lpsf;

                lpsf->lpVtbl->AddRef(lpsf);

                // Insert sorted ...
                {
                  COMBOBOXEXITEM cbei2;
                  LPDC_ITEMDATA lpdcid2;
                  HRESULT hr;
                  cbei2.mask = CBEIF_LPARAM;
                  cbei2.iItem = 0;

                  while ((SendMessage(hwnd,CBEM_GETITEM,0,(LPARAM)&cbei2)))
                  {
                    lpdcid2 = (LPDC_ITEMDATA)cbei2.lParam;
                    hr = (lpdcid->lpsf->lpVtbl->CompareIDs(
                                lpdcid->lpsf,
                                0,
                                lpdcid->pidl,
                                lpdcid2->pidl));

                    if ((short)(SCODE_CODE(GetScode(hr))) < 0)
                      break;
                    else
                      cbei2.iItem++;
                  }

                  cbei.iItem = cbei2.iItem;
                  cbei.lParam = (LPARAM)lpdcid;
                  SendMessage(hwnd,CBEM_INSERTITEM,0,(LPARAM)&cbei);

                }

              }

            }

          } // IEnumIDList::Next()

          lpe->lpVtbl->Release(lpe);

        } // IShellFolder::EnumObjects()

        lpsf->lpVtbl->Release(lpsf);

      } // IShellFolder::BindToObject()

      CoTaskMemFree(pidl);

    } // SHGetSpecialFolderLocation()

    lpsfDesktop->lpVtbl->Release(lpsfDesktop);

  } // SHGetDesktopFolder()


  SendMessage(hwnd,WM_SETREDRAW,1,0);
  // Return number of items added to combo box
  return ((int)SendMessage(hwnd,CB_GETCOUNT,0,0));

}
コード例 #20
0
HRESULT CWIACapabilityManager::AllocateCapability(_Out_ WIA_DEV_CAP_DRV **ppWIADeviceCapability)
{
    HRESULT hr = E_INVALIDARG;
    if(ppWIADeviceCapability)
    {
        *ppWIADeviceCapability                = NULL;
        WIA_DEV_CAP_DRV *pWIADeviceCapability = NULL;

#pragma prefast(suppress:__WARNING_MEMORY_LEAK, "Freed when calling FreeCapability(*ppWIADeviceCapability).")
        pWIADeviceCapability = (WIA_DEV_CAP_DRV*)CoTaskMemAlloc(sizeof(WIA_DEV_CAP_DRV));
        if(pWIADeviceCapability)
        {
            memset(pWIADeviceCapability,0,sizeof(WIA_DEV_CAP_DRV));
            //
            // attempt to allocate the GUID member of the structure
            //
			
#pragma prefast(suppress:__WARNING_MEMORY_LEAK, "Freed when calling FreeCapability(*ppWIADeviceCapability).")
            pWIADeviceCapability->guid = (GUID*)CoTaskMemAlloc(sizeof(GUID));
            if(pWIADeviceCapability->guid)
            {
                *pWIADeviceCapability->guid = GUID_NULL;
                hr = S_OK;
            }
            else
            {
                hr = E_OUTOFMEMORY;
                WIAS_ERROR((g_hInst, "Failed to allocate memory for GUID member of WIA_DEV_CAP_DRV structure, hr = 0x%lx",hr));
            }

            //
            // attempt to allocate the LPOLESTR name member of the structure
            //

            if(SUCCEEDED(hr))
            {
#pragma prefast(suppress:__WARNING_MEMORY_LEAK, "Freed when calling FreeCapability(*ppWIADeviceCapability).")
                pWIADeviceCapability->wszName = (LPOLESTR)CoTaskMemAlloc(MAX_CAPABILITY_STRING_SIZE_BYTES);
                if(pWIADeviceCapability->wszName)
                {
                    memset(pWIADeviceCapability->wszName,0,MAX_CAPABILITY_STRING_SIZE_BYTES);
                    hr = S_OK;
                }
                else
                {
                    hr = E_OUTOFMEMORY;
                    WIAS_ERROR((g_hInst, "Failed to allocate memory for LPOLESTR (wszName) member of WIA_DEV_CAP_DRV structure, hr = 0x%lx",hr));
                }
            }

            //
            // attempt to allocate the LPOLESTR description member of the structure
            //

            if(SUCCEEDED(hr))
            {
#pragma prefast(suppress:__WARNING_MEMORY_LEAK, "Freed when calling FreeCapability(*ppWIADeviceCapability).")
                pWIADeviceCapability->wszDescription = (LPOLESTR)CoTaskMemAlloc(MAX_CAPABILITY_STRING_SIZE_BYTES);
                if(pWIADeviceCapability->wszDescription)
                {
                    memset(pWIADeviceCapability->wszDescription,0,MAX_CAPABILITY_STRING_SIZE_BYTES);
                    hr = S_OK;
                }
                else
                {
                    hr = E_OUTOFMEMORY;
                    WIAS_ERROR((g_hInst, "Failed to allocate memory for LPOLESTR (wszDescription) member of WIA_DEV_CAP_DRV structure, hr = 0x%lx",hr));
                }
            }

            //
            // attempt to allocate the LPOLESTR icon member of the structure
            //

            if(SUCCEEDED(hr))
            {
#pragma prefast(suppress:__WARNING_MEMORY_LEAK, "Freed when calling FreeCapability(*ppWIADeviceCapability).")
                pWIADeviceCapability->wszIcon = (LPOLESTR)CoTaskMemAlloc(MAX_CAPABILITY_STRING_SIZE_BYTES);
                if(pWIADeviceCapability->wszIcon)
                {
                    memset(pWIADeviceCapability->wszIcon,0,MAX_CAPABILITY_STRING_SIZE_BYTES);
                    hr = S_OK;
                }
                else
                {
                    hr = E_OUTOFMEMORY;
                    WIAS_ERROR((g_hInst, "Failed to allocate memory for LPOLESTR (wszIcon) member of WIA_DEV_CAP_DRV structure, hr = 0x%lx",hr));
                }
            }

            if(SUCCEEDED(hr))
            {
                *ppWIADeviceCapability = pWIADeviceCapability;
            }
            else
            {
                FreeCapability(pWIADeviceCapability);
                pWIADeviceCapability = NULL;
            }
        }
        else
        {
            hr = E_OUTOFMEMORY;
            WIAS_ERROR((g_hInst, "Failed to allocate memory for WIA_DEV_CAP_DRV structure, hr = 0x%lx",hr));
        }
    }
    return hr;
}
コード例 #21
0
ファイル: oleproxy.c プロジェクト: howard5888/wineT
static HRESULT WINAPI RemUnkStub_Invoke(LPRPCSTUBBUFFER iface,
				     PRPCOLEMESSAGE pMsg,
				     LPRPCCHANNELBUFFER pChannel)
{
  RemUnkStub *This = (RemUnkStub *)iface;
  ULONG iMethod = pMsg->iMethod;
  LPBYTE buf = pMsg->Buffer;
  HRESULT hr = RPC_E_INVALIDMETHOD;

  TRACE("(%p)->Invoke(%p,%p) method %ld\n", This, pMsg, pChannel, iMethod);
  switch (iMethod)
  {
  case 3: /* RemQueryInterface */
  {
    IPID ipid;
    ULONG cRefs;
    USHORT cIids;
    IID *iids;
    REMQIRESULT *pQIResults = NULL;

    /* in */
    memcpy(&ipid, buf, sizeof(ipid));
    buf += sizeof(ipid);
    memcpy(&cRefs, buf, sizeof(cRefs));
    buf += sizeof(cRefs);
    memcpy(&cIids, buf, sizeof(cIids));
    buf += sizeof(cIids);
    iids = (IID *)buf;

    hr = IRemUnknown_RemQueryInterface(This->iface, &ipid, cRefs, cIids, iids, &pQIResults);

    /* out */
    pMsg->cbBuffer = cIids * sizeof(REMQIRESULT) + sizeof(HRESULT);

    I_RpcGetBuffer((RPC_MESSAGE *)pMsg);

    buf = pMsg->Buffer;
    *(HRESULT *)buf = hr;
    buf += sizeof(HRESULT);
    
    if (hr) return hr;
    /* FIXME: pQIResults is a unique pointer so pQIResults can be NULL! */
    memcpy(buf, pQIResults, cIids * sizeof(REMQIRESULT));

    break;
  }
  case 4: /* RemAddRef */
  {
    USHORT cIids;
    REMINTERFACEREF *ir;
    HRESULT *pResults;

    /* in */
    memcpy(&cIids, buf, sizeof(USHORT));
    buf += sizeof(USHORT);
    ir = (REMINTERFACEREF*)buf;
    pResults = CoTaskMemAlloc(cIids * sizeof(HRESULT));
    if (!pResults) return E_OUTOFMEMORY;

    hr = IRemUnknown_RemAddRef(This->iface, cIids, ir, pResults);

    /* out */
    pMsg->cbBuffer = cIids * sizeof(HRESULT);

    I_RpcGetBuffer((RPC_MESSAGE *)pMsg);
    if (!hr)
    {
        buf = pMsg->Buffer;
        memcpy(buf, pResults, cIids * sizeof(HRESULT));
    }

    CoTaskMemFree(pResults);

    break;
  }
  case 5: /* RemRelease */
  {
    USHORT cIids;
    REMINTERFACEREF *ir;

    /* in */
    memcpy(&cIids, buf, sizeof(USHORT));
    buf += sizeof(USHORT);
    ir = (REMINTERFACEREF*)buf;

    hr = IRemUnknown_RemRelease(This->iface, cIids, ir);

    /* out */
    pMsg->cbBuffer = 0;
    break;
  }
  }
  return hr;
}
コード例 #22
0
static HRESULT QT_Process_Video_Track(QTSplitter* filter, Track trk)
{
    AM_MEDIA_TYPE amt;
    VIDEOINFOHEADER * pvi;
    PIN_INFO piOutput;
    HRESULT hr = S_OK;
    OSErr err;
    static const WCHAR szwVideoOut[] = {'V','i','d','e','o',0};
    CFMutableDictionaryRef  pixelBufferOptions = NULL;
    CFMutableDictionaryRef  visualContextOptions = NULL;
    CFNumberRef n = NULL;
    int t;
    DWORD outputWidth, outputHeight, outputDepth;
    Fixed trackWidth, trackHeight;

    ZeroMemory(&amt, sizeof(amt));
    amt.formattype = FORMAT_VideoInfo;
    amt.majortype = MEDIATYPE_Video;
    amt.subtype = MEDIASUBTYPE_RGB24;

    GetTrackDimensions(trk, &trackWidth, &trackHeight);

    outputDepth = 3;
    outputWidth = Fix2Long(trackWidth);
    outputHeight = Fix2Long(trackHeight);
    TRACE("Width %i  Height %i\n",outputWidth, outputHeight);

    amt.cbFormat = sizeof(VIDEOINFOHEADER);
    amt.pbFormat = CoTaskMemAlloc(amt.cbFormat);
    ZeroMemory(amt.pbFormat, amt.cbFormat);
    pvi = (VIDEOINFOHEADER *)amt.pbFormat;
    pvi->bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
    pvi->bmiHeader.biWidth = outputWidth;
    pvi->bmiHeader.biHeight = outputHeight;
    pvi->bmiHeader.biPlanes = 1;
    pvi->bmiHeader.biBitCount = 24;
    pvi->bmiHeader.biCompression = BI_RGB;
    pvi->bmiHeader.biSizeImage = outputWidth * outputHeight * outputDepth;

    filter->outputSize = pvi->bmiHeader.biSizeImage;
    amt.lSampleSize = 0;

    pixelBufferOptions = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    t = k32ARGBPixelFormat;
    n = CFNumberCreate(NULL, kCFNumberIntType, &t);
    CFDictionaryAddValue(pixelBufferOptions, kCVPixelBufferPixelFormatTypeKey, n);
    CFRelease(n);

    n = CFNumberCreate(NULL, kCFNumberIntType, &outputWidth);
    CFDictionaryAddValue(pixelBufferOptions, kCVPixelBufferWidthKey, n);
    CFRelease(n);

    n = CFNumberCreate(NULL, kCFNumberIntType, &outputHeight);
    CFDictionaryAddValue(pixelBufferOptions, kCVPixelBufferHeightKey, n);
    CFRelease(n);

    t = 16;
    n = CFNumberCreate(NULL, kCFNumberIntType, &t);
    CFDictionaryAddValue(pixelBufferOptions, kCVPixelBufferBytesPerRowAlignmentKey, n);
    CFRelease(n);

    visualContextOptions = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

    CFDictionarySetValue(visualContextOptions, kQTVisualContextPixelBufferAttributesKey, pixelBufferOptions);

    err = QTPixelBufferContextCreate(NULL, visualContextOptions,&filter->vContext);
    CFRelease(pixelBufferOptions);
    CFRelease(visualContextOptions);
    if (err != noErr)
    {
        ERR("Failed to create Visual Context\n");
        return E_FAIL;
    }

    err = SetMovieVisualContext(filter->pQTMovie, filter->vContext);
    if (err != noErr)
    {
        ERR("Failed to set Visual Context\n");
        return E_FAIL;
    }

    piOutput.dir = PINDIR_OUTPUT;
    piOutput.pFilter = &filter->filter.IBaseFilter_iface;
    lstrcpyW(piOutput.achName,szwVideoOut);

    hr = QT_AddPin(filter, &piOutput, &amt, TRUE);
    if (FAILED(hr))
        ERR("Failed to add Video Track\n");
     else
        TRACE("Video Pin %p\n",filter->pVideo_Pin);

    return hr;
}
コード例 #23
0
ファイル: FileStrm.cpp プロジェクト: FieldDB/FieldWorks
/*----------------------------------------------------------------------------------------------
	Get the status of an open IStream (file).
	If the caller uses the value STATFLAG_DEFAULT for grfStatFlag then the user must free
	the memory which this method allocates for the file name at pstatstg->pwcsName.
----------------------------------------------------------------------------------------------*/
STDMETHODIMP FileStream::Stat(STATSTG * pstatstg, DWORD grfStatFlag)
{
	BEGIN_COM_METHOD;
	ChkComArgPtr(pstatstg);

#if WIN32
		if (m_hfile == NULL)
		ThrowHr(WarnHr(E_UNEXPECTED));

	BY_HANDLE_FILE_INFORMATION bhfi;

	if (!GetFileInformationByHandle(m_hfile, &bhfi))
	{
		// The caller does not have sufficient permissions for accessing statistics for this
		// stream object.
		ThrowHr(WarnHr(STG_E_ACCESSDENIED));
	}
#else
	if (m_file < 0)
		ThrowHr(WarnHr(E_UNEXPECTED));

	struct stat filestats;

	//errno = 0;
	if (fstat(m_file, &filestats)) {
		//int err = errno;
		//std::cerr << "Error number " << err << " - " << strerror(err) << '\n';
		ThrowHr(WarnHr(STG_E_ACCESSDENIED));
	}
#endif

	pstatstg->pwcsName = NULL;

	switch (grfStatFlag)
	{
		case STATFLAG_DEFAULT:
		{
			// Requests that the statistics include the pwcsName member of the STATSTG structure.
			StrUniBufPath stubpName = m_staPath.Chars();

			pstatstg->pwcsName = (wchar *)CoTaskMemAlloc(
				(stubpName.Length() + 1) * isizeof(wchar));
			if (NULL == pstatstg->pwcsName)
				ThrowHr(WarnHr(STG_E_INSUFFICIENTMEMORY));

			memcpy(pstatstg->pwcsName, stubpName.Chars(), stubpName.Length() * isizeof(wchar));
			pstatstg->pwcsName[stubpName.Length()] = 0;
		}
		// Fall Through.

		case STATFLAG_NONAME:
			// Requests that the statistics not include the pwcsName member of the STATSTG
			// structure. If the name is omitted, there is no need for the Stat methods to allocate
			// and free memory for the string value for the name and the method can save an Alloc
			// and the caller a Free operation.
			pstatstg->type = STGTY_STREAM;
#if WIN32
			pstatstg->cbSize.HighPart = bhfi.nFileSizeHigh;
			pstatstg->cbSize.LowPart = bhfi.nFileSizeLow;
			pstatstg->mtime = bhfi.ftLastWriteTime;
			pstatstg->ctime = bhfi.ftCreationTime;
			pstatstg->atime = bhfi.ftLastAccessTime;
#else
			pstatstg->cbSize.QuadPart = filestats.st_size;
			time_tToFiletime(filestats.st_mtime, &(pstatstg->mtime));
			time_tToFiletime(filestats.st_ctime, &(pstatstg->ctime));
			time_tToFiletime(filestats.st_atime, &(pstatstg->atime));
#endif
			pstatstg->grfMode = m_grfstgm;
			pstatstg->grfLocksSupported = 0;
			pstatstg->clsid = CLSID_NULL;
			pstatstg->grfStateBits = 0;
			return S_OK;

	default:
		ThrowHr(WarnHr(STG_E_INVALIDFLAG));

	}
	END_COM_METHOD(g_fact, IID_IStream);
}
コード例 #24
0
ファイル: createdevenum.c プロジェクト: GYGit/reactos
static void DEVENUM_ReadPinTypes(HKEY hkeyPinKey, REGFILTERPINS *rgPin)
{
    HKEY hkeyTypes = NULL;
    DWORD dwMajorTypes, i;
    REGPINTYPES *lpMediaType = NULL;
    DWORD dwMediaTypeSize = 0;

    if (RegOpenKeyExW(hkeyPinKey, wszTypes, 0, KEY_READ, &hkeyTypes) != ERROR_SUCCESS)
        return ;

    if (RegQueryInfoKeyW(hkeyTypes, NULL, NULL, NULL, &dwMajorTypes, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
                != ERROR_SUCCESS)
    {
        RegCloseKey(hkeyTypes);
        return ;
    }

    for (i = 0; i < dwMajorTypes; i++)
    {
        HKEY hkeyMajorType = NULL;
        WCHAR wszMajorTypeName[64];
        DWORD cName = sizeof(wszMajorTypeName) / sizeof(WCHAR);
        DWORD dwMinorTypes, i1;

        if (RegEnumKeyExW(hkeyTypes, i, wszMajorTypeName, &cName, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) continue;

        if (RegOpenKeyExW(hkeyTypes, wszMajorTypeName, 0, KEY_READ, &hkeyMajorType) != ERROR_SUCCESS) continue;

        if (RegQueryInfoKeyW(hkeyMajorType, NULL, NULL, NULL, &dwMinorTypes, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
                    != ERROR_SUCCESS)
        {
            RegCloseKey(hkeyMajorType);
            continue;
        }

        for (i1 = 0; i1 < dwMinorTypes; i1++)
        {
            WCHAR wszMinorTypeName[64];
            CLSID *clsMajorType = NULL, *clsMinorType = NULL;
            HRESULT hr;

            cName = sizeof(wszMinorTypeName) / sizeof(WCHAR);
            if (RegEnumKeyExW(hkeyMajorType, i1, wszMinorTypeName, &cName, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) continue;

            clsMinorType = CoTaskMemAlloc(sizeof(CLSID));
            if (!clsMinorType) continue;

            clsMajorType = CoTaskMemAlloc(sizeof(CLSID));
            if (!clsMajorType) goto error_cleanup_types;

            hr = CLSIDFromString(wszMinorTypeName, clsMinorType);
            if (FAILED(hr)) goto error_cleanup_types;

            hr = CLSIDFromString(wszMajorTypeName, clsMajorType);
            if (FAILED(hr)) goto error_cleanup_types;

            if (rgPin->nMediaTypes == dwMediaTypeSize)
            {
                DWORD dwNewSize = dwMediaTypeSize + (dwMediaTypeSize < 2 ? 1 : dwMediaTypeSize / 2);
                REGPINTYPES *lpNewMediaType;

                lpNewMediaType = CoTaskMemRealloc(lpMediaType, sizeof(REGPINTYPES) * dwNewSize);
                if (!lpNewMediaType) goto error_cleanup_types;

                lpMediaType = lpNewMediaType;
                dwMediaTypeSize = dwNewSize;
             }

            lpMediaType[rgPin->nMediaTypes].clsMajorType = clsMajorType;
            lpMediaType[rgPin->nMediaTypes].clsMinorType = clsMinorType;
            rgPin->nMediaTypes++;
            continue;

            error_cleanup_types:

            if (clsMajorType) CoTaskMemFree(clsMajorType);
            if (clsMinorType) CoTaskMemFree(clsMinorType);
        }

        RegCloseKey(hkeyMajorType);
    }

    RegCloseKey(hkeyTypes);

    if (lpMediaType && !rgPin->nMediaTypes)
    {
        CoTaskMemFree(lpMediaType);
        lpMediaType = NULL;
    }

    rgPin->lpMediaType = lpMediaType;
}
コード例 #25
0
/// <summary>Handle <c>ICorProfilerCallback::JITCompilationStarted</c></summary>
/// <remarks>The 'workhorse' </remarks>
HRESULT STDMETHODCALLTYPE CCodeInjection::JITCompilationStarted( 
        /* [in] */ FunctionID functionId, /* [in] */ BOOL fIsSafeToBlock) 
{
    ModuleID moduleId; mdToken funcToken;
    std::wstring methodName = GetMethodName(functionId, 
        moduleId, funcToken);
    ATLTRACE(_T("::JITCompilationStarted(%X -> %s)"), 
        functionId, W2CT(methodName.c_str()));

    if (L"ProfilerTarget.Program.OnMethodToInstrument" == methodName && 
        m_targetMethodRef !=0 ) {
        // get method body
        LPCBYTE pMethodHeader = NULL;
        ULONG iMethodSize = 0;
        COM_FAIL_RETURN(m_profilerInfo3->GetILFunctionBody(
            moduleId, funcToken, &pMethodHeader, &iMethodSize), 
            S_OK);

        CComPtr<IMetaDataEmit> metaDataEmit;
        COM_FAIL_RETURN(m_profilerInfo3->GetModuleMetaData(moduleId, 
            ofRead | ofWrite, IID_IMetaDataEmit, (IUnknown**)&metaDataEmit), S_OK);

        // parse IL
        Method instMethod((IMAGE_COR_ILMETHOD*)pMethodHeader); // <--
        instMethod.SetMinimumStackSize(3); // should be correct for this sample
        
        // NOTE: build signature (in the knowledge that the method we are instrumenting currently has no local vars)
        static COR_SIGNATURE localSignature[] = 
        {
            IMAGE_CEE_CS_CALLCONV_LOCAL_SIG,   
            0x02,                                   
            ELEMENT_TYPE_ARRAY, ELEMENT_TYPE_OBJECT, 01, 00, 00,  
            ELEMENT_TYPE_ARRAY, ELEMENT_TYPE_OBJECT, 01, 00, 00
        };
        
        mdSignature signature;
        COM_FAIL_RETURN(metaDataEmit->GetTokenFromSig(localSignature, sizeof(localSignature), &signature), S_OK);
        instMethod.m_header.LocalVarSigTok = signature;

        // insert new IL block
        InstructionList instructions; // NOTE: this IL will be different for an instance method or if the local vars signature is different
        instructions.push_back(new Instruction(CEE_NOP));
        instructions.push_back(new Instruction(CEE_LDC_I4_2));
        instructions.push_back(new Instruction(CEE_NEWARR, m_objectTypeRef));
        instructions.push_back(new Instruction(CEE_STLOC_1));
        instructions.push_back(new Instruction(CEE_LDLOC_1));
        instructions.push_back(new Instruction(CEE_LDC_I4_0));
        instructions.push_back(new Instruction(CEE_LDARG_0));
        instructions.push_back(new Instruction(CEE_STELEM_REF));
        instructions.push_back(new Instruction(CEE_LDLOC_1));
        instructions.push_back(new Instruction(CEE_LDC_I4_1));
        instructions.push_back(new Instruction(CEE_LDARG_1));
        instructions.push_back(new Instruction(CEE_STELEM_REF));
        instructions.push_back(new Instruction(CEE_LDLOC_1));
        instructions.push_back(new Instruction(CEE_STLOC_0));
        instructions.push_back(new Instruction(CEE_LDLOC_0));
        instructions.push_back(new Instruction(CEE_CALL, m_targetMethodRef));

        instMethod.InsertSequenceInstructionsAtOriginalOffset(
            0, instructions);

        instMethod.DumpIL();

        // allocate memory
        CComPtr<IMethodMalloc> methodMalloc;
        COM_FAIL_RETURN(m_profilerInfo3->GetILFunctionBodyAllocator(
            moduleId, &methodMalloc), S_OK);
        void* pNewMethod = methodMalloc->Alloc(instMethod.GetMethodSize());

        // write new method
        instMethod.WriteMethod((IMAGE_COR_ILMETHOD*)pNewMethod);
        COM_FAIL_RETURN(m_profilerInfo3->SetILFunctionBody(moduleId, 
            funcToken, (LPCBYTE) pNewMethod), S_OK);

        // update IL maps
        ULONG mapSize = instMethod.GetILMapSize();
        void* pMap = CoTaskMemAlloc(mapSize * sizeof(COR_IL_MAP));
        instMethod.PopulateILMap(mapSize, (COR_IL_MAP*)pMap);

        COM_FAIL_RETURN(m_profilerInfo3->SetILInstrumentedCodeMap(
            functionId, TRUE, mapSize, (COR_IL_MAP*)pMap), S_OK);
        CoTaskMemFree(pMap);
    }

    return S_OK;
}
コード例 #26
0
ファイル: createdevenum.c プロジェクト: GYGit/reactos
static void DEVENUM_ReadPins(HKEY hkeyFilterClass, REGFILTER2 *rgf2)
{
    HKEY hkeyPins = NULL;
    DWORD dwPinsSubkeys, i;
    REGFILTERPINS *rgPins = NULL;

    if (RegOpenKeyExW(hkeyFilterClass, wszPins, 0, KEY_READ, &hkeyPins) != ERROR_SUCCESS)
        return ;

    if (RegQueryInfoKeyW(hkeyPins, NULL, NULL, NULL, &dwPinsSubkeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
                != ERROR_SUCCESS)
    {
        RegCloseKey(hkeyPins);
        return ;
    }

    if (dwPinsSubkeys)
    {
        rgPins = CoTaskMemAlloc(sizeof(REGFILTERPINS) * dwPinsSubkeys);
        if (!rgPins)
        {
            RegCloseKey(hkeyPins);
            return ;
        }
    }

    for (i = 0; i < dwPinsSubkeys; i++)
    {
        HKEY hkeyPinKey = NULL;
        WCHAR wszPinName[MAX_PATH];
        DWORD cName = sizeof(wszPinName) / sizeof(WCHAR);
        DWORD Type, cbData;
        REGFILTERPINS *rgPin = &rgPins[rgf2->u.s1.cPins];
        LONG lRet;

        rgPin->strName = NULL;
        rgPin->clsConnectsToFilter = &GUID_NULL;
        rgPin->strConnectsToPin = NULL;
        rgPin->nMediaTypes = 0;
        rgPin->lpMediaType = NULL;

        if (RegEnumKeyExW(hkeyPins, i, wszPinName, &cName, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) continue;

        if (RegOpenKeyExW(hkeyPins, wszPinName, 0, KEY_READ, &hkeyPinKey) != ERROR_SUCCESS) continue;

        rgPin->strName = CoTaskMemAlloc((strlenW(wszPinName) + 1) * sizeof(WCHAR));
        if (!rgPin->strName) goto error_cleanup;

        strcpyW(rgPin->strName, wszPinName);

        cbData = sizeof(rgPin->bMany);
        lRet = RegQueryValueExW(hkeyPinKey, wszAllowedMany, NULL, &Type, (LPBYTE)&rgPin->bMany, &cbData);
        if (lRet != ERROR_SUCCESS || Type != REG_DWORD)
            goto error_cleanup;

        cbData = sizeof(rgPin->bZero);
        lRet = RegQueryValueExW(hkeyPinKey, wszAllowedZero, NULL, &Type, (LPBYTE)&rgPin->bZero, &cbData);
        if (lRet != ERROR_SUCCESS || Type != REG_DWORD)
            goto error_cleanup;

        cbData = sizeof(rgPin->bOutput);
        lRet = RegQueryValueExW(hkeyPinKey, wszDirection, NULL, &Type, (LPBYTE)&rgPin->bOutput, &cbData);
        if (lRet != ERROR_SUCCESS || Type != REG_DWORD)
            goto error_cleanup;

        cbData = sizeof(rgPin->bRendered);
        lRet = RegQueryValueExW(hkeyPinKey, wszIsRendered, NULL, &Type, (LPBYTE)&rgPin->bRendered, &cbData);
        if (lRet != ERROR_SUCCESS || Type != REG_DWORD)
            goto error_cleanup;

        DEVENUM_ReadPinTypes(hkeyPinKey, rgPin);

        ++rgf2->u.s1.cPins;
        continue;

        error_cleanup:

        RegCloseKey(hkeyPinKey);
        if (rgPin->strName) CoTaskMemFree(rgPin->strName);
    }

    RegCloseKey(hkeyPins);

    if (rgPins && !rgf2->u.s1.cPins)
    {
        CoTaskMemFree(rgPins);
        rgPins = NULL;
    }

    rgf2->u.s1.rgPins = rgPins;
}
コード例 #27
0
ファイル: datainit.c プロジェクト: AlexSteel/wine
static HRESULT WINAPI datainit_GetDataSource(IDataInitialize *iface, IUnknown *outer, DWORD clsctx,
                                LPWSTR initstring, REFIID riid, IUnknown **datasource)
{
    static const WCHAR providerW[] = {'P','r','o','v','i','d','e','r','=',0};
    static const WCHAR msdasqlW[] = {'M','S','D','A','S','Q','L',0};
    datainit *This = impl_from_IDataInitialize(iface);
    BOOL datasource_created = FALSE;
    IDBProperties *dbprops;
    DBPROPSET *propset;
    WCHAR *prov = NULL;
    CLSID provclsid;
    HRESULT hr;

    TRACE("(%p)->(%p 0x%x %s %s %p)\n", This, outer, clsctx, debugstr_w(initstring), debugstr_guid(riid), datasource);

    /* first get provider name */
    provclsid = IID_NULL;
    if (initstring && (prov = strstriW(initstring, providerW)))
    {
        WCHAR *start, *progid;
        int len;

        prov += sizeof(providerW)/sizeof(WCHAR)-1;
        start = prov;
        while (*prov && *prov != ';')
            ++prov;
        TRACE("got provider %s\n", debugstr_wn(start, prov-start));

        len = prov - start;
        progid = CoTaskMemAlloc((len+1)*sizeof(WCHAR));
        if (!progid) return E_OUTOFMEMORY;

        memcpy(progid, start, len*sizeof(WCHAR));
        progid[len] = 0;

        hr = CLSIDFromProgID(progid, &provclsid);
        CoTaskMemFree(progid);
        if (FAILED(hr))
        {
            ERR("provider %s not registered\n", debugstr_wn(start, prov-start));
            return hr;
        }
    }
    else
    {
        hr = CLSIDFromProgID(msdasqlW, &provclsid);
        if (FAILED(hr))
            ERR("ODBC provider for OLE DB not registered\n");
    }

    /* check for provider mismatch if it was specified in init string */
    if (*datasource && prov)
    {
        DBPROPIDSET propidset;
        enum DBPROPENUM prop;
        CLSID initprov;
        ULONG count;

        hr = IUnknown_QueryInterface(*datasource, &IID_IDBProperties, (void**)&dbprops);
        if (FAILED(hr))
        {
            WARN("provider doesn't support IDBProperties\n");
            return hr;
        }

        prop = DBPROP_INIT_DATASOURCE;
        propidset.rgPropertyIDs = &prop;
        propidset.cPropertyIDs = 1;
        propidset.guidPropertySet = DBPROPSET_DBINIT;
        count = 0;
        propset = NULL;
        hr = IDBProperties_GetProperties(dbprops, 1, &propidset, &count, &propset);
        IDBProperties_Release(dbprops);
        if (FAILED(hr))
        {
            WARN("GetProperties failed for datasource, 0x%08x\n", hr);
            return hr;
        }

        TRACE("initial data source provider %s\n", debugstr_w(V_BSTR(&propset->rgProperties[0].vValue)));
        initprov = IID_NULL;
        hr = CLSIDFromProgID(V_BSTR(&propset->rgProperties[0].vValue), &initprov);
        free_dbpropset(count, propset);

        if (FAILED(hr) || !IsEqualIID(&provclsid, &initprov)) return DB_E_MISMATCHEDPROVIDER;
    }

    if (!*datasource)
    {
        if (!IsEqualIID(&provclsid, &IID_NULL))
            hr = CoCreateInstance(&provclsid, outer, clsctx, riid, (void**)datasource);

        if (FAILED(hr) && IsEqualIID(riid, &IID_IDBInitialize))
            hr = create_db_init(datasource);

        datasource_created = *datasource != NULL;
    }

    /* now set properties */
    if (initstring)
    {
        struct dbprops props;

        hr = IUnknown_QueryInterface(*datasource, &IID_IDBProperties, (void**)&dbprops);
        if (FAILED(hr))
        {
            ERR("provider doesn't support IDBProperties\n");
            datasource_release(datasource_created, datasource);
            return hr;
        }

        hr = parse_init_string(initstring, &props);
        if (FAILED(hr))
        {
            datasource_release(datasource_created, datasource);
            return hr;
        }

        hr = get_dbpropset_from_proplist(&props, &propset);
        free_dbprop_list(&props);
        if (FAILED(hr))
        {
            datasource_release(datasource_created, datasource);
            return hr;
        }

        hr = IDBProperties_SetProperties(dbprops, 1, propset);
        IDBProperties_Release(dbprops);
        free_dbpropset(1, propset);
        if (FAILED(hr))
        {
            ERR("SetProperties failed, 0x%08x\n", hr);
            datasource_release(datasource_created, datasource);
            return hr;
        }
    }

    return hr;
}
コード例 #28
0
ファイル: createdevenum.c プロジェクト: GYGit/reactos
/**********************************************************************
 * DEVENUM_CreateSpecialCategories (INTERNAL)
 *
 * Creates the keys in the registry for the dynamic categories
 */
static HRESULT DEVENUM_CreateSpecialCategories(void)
{
    HRESULT res;
    WCHAR szDSoundNameFormat[MAX_PATH + 1];
    WCHAR szDSoundName[MAX_PATH + 1];
    DWORD iDefaultDevice = -1;
    UINT numDevs;
    IFilterMapper2 * pMapper = NULL;
    REGFILTER2 rf2;
    REGFILTERPINS2 rfp2;
    WCHAR path[MAX_PATH];
    HKEY basekey;

    if (DEVENUM_populate_handle)
        return S_OK;
    DEVENUM_populate_handle = CreateEventW(NULL, TRUE, FALSE, DEVENUM_populate_handle_nameW);
    if (GetLastError() == ERROR_ALREADY_EXISTS)
    {
        /* Webcams can take some time to scan if the driver is badly written and it enables them,
         * so have a 10 s timeout here
         */
        if (WaitForSingleObject(DEVENUM_populate_handle, 10000) == WAIT_TIMEOUT)
            WARN("Waiting for object timed out\n");
        TRACE("No need to rescan\n");
        return S_OK;
    }
    TRACE("Scanning for devices\n");

    /* Since devices can change between session, for example because you just plugged in a webcam
     * or switched from pulseaudio to alsa, delete all old devices first
     */
    if (SUCCEEDED(DEVENUM_GetCategoryKey(&CLSID_AudioRendererCategory, &basekey, path, MAX_PATH)))
        RegDeleteTreeW(basekey, path);
    if (SUCCEEDED(DEVENUM_GetCategoryKey(&CLSID_AudioInputDeviceCategory, &basekey, path, MAX_PATH)))
        RegDeleteTreeW(basekey, path);
    if (SUCCEEDED(DEVENUM_GetCategoryKey(&CLSID_VideoInputDeviceCategory, &basekey, path, MAX_PATH)))
        RegDeleteTreeW(basekey, path);
    if (SUCCEEDED(DEVENUM_GetCategoryKey(&CLSID_MidiRendererCategory, &basekey, path, MAX_PATH)))
        RegDeleteTreeW(basekey, path);
    if (SUCCEEDED(DEVENUM_GetCategoryKey(&CLSID_VideoCompressorCategory, &basekey, path, MAX_PATH)))
        RegDeleteTreeW(basekey, path);

    rf2.dwVersion = 2;
    rf2.dwMerit = MERIT_PREFERRED;
    rf2.u.s2.cPins2 = 1;
    rf2.u.s2.rgPins2 = &rfp2;
    rfp2.cInstances = 1;
    rfp2.nMediums = 0;
    rfp2.lpMedium = NULL;
    rfp2.clsPinCategory = &IID_NULL;

    if (!LoadStringW(DEVENUM_hInstance, IDS_DEVENUM_DS, szDSoundNameFormat, sizeof(szDSoundNameFormat)/sizeof(szDSoundNameFormat[0])-1))
    {
        ERR("Couldn't get string resource (GetLastError() is %d)\n", GetLastError());
        return HRESULT_FROM_WIN32(GetLastError());
    }

    res = CoCreateInstance(&CLSID_FilterMapper2, NULL, CLSCTX_INPROC,
                           &IID_IFilterMapper2, (void **) &pMapper);
    /*
     * Fill in info for devices
     */
    if (SUCCEEDED(res))
    {
        UINT i;
        WAVEOUTCAPSW wocaps;
	WAVEINCAPSW wicaps;
        MIDIOUTCAPSW mocaps;
        REGPINTYPES * pTypes;
        IPropertyBag * pPropBag = NULL;

	numDevs = waveOutGetNumDevs();

        res = DEVENUM_CreateAMCategoryKey(&CLSID_AudioRendererCategory);
        if (FAILED(res)) /* can't register any devices in this category */
            numDevs = 0;

	rfp2.dwFlags = REG_PINFLAG_B_RENDERER;
	for (i = 0; i < numDevs; i++)
	{
	    if (waveOutGetDevCapsW(i, &wocaps, sizeof(WAVEOUTCAPSW))
	        == MMSYSERR_NOERROR)
	    {
                IMoniker * pMoniker = NULL;

                rfp2.nMediaTypes = 1;
                pTypes = CoTaskMemAlloc(rfp2.nMediaTypes * sizeof(REGPINTYPES));
                if (!pTypes)
                {
                    IFilterMapper2_Release(pMapper);
                    return E_OUTOFMEMORY;
                }
                /* FIXME: Native devenum seems to register a lot more types for
                 * DSound than we do. Not sure what purpose they serve */
                pTypes[0].clsMajorType = &MEDIATYPE_Audio;
                pTypes[0].clsMinorType = &MEDIASUBTYPE_PCM;

                rfp2.lpMediaType = pTypes;

                res = IFilterMapper2_RegisterFilter(pMapper,
		                              &CLSID_AudioRender,
					      wocaps.szPname,
					      &pMoniker,
					      &CLSID_AudioRendererCategory,
					      wocaps.szPname,
					      &rf2);

                if (pMoniker)
                {
                    VARIANT var;

                    V_VT(&var) = VT_I4;
                    V_I4(&var) = i;
                    res = IMoniker_BindToStorage(pMoniker, NULL, NULL, &IID_IPropertyBag, (LPVOID)&pPropBag);
                    if (SUCCEEDED(res))
                        res = IPropertyBag_Write(pPropBag, wszWaveOutID, &var);
                    else
                        pPropBag = NULL;

                    V_VT(&var) = VT_LPWSTR;
                    V_BSTR(&var) = wocaps.szPname;
                    if (SUCCEEDED(res))
                        res = IPropertyBag_Write(pPropBag, wszFriendlyName, &var);
                    if (pPropBag)
                        IPropertyBag_Release(pPropBag);
                    IMoniker_Release(pMoniker);
                    pMoniker = NULL;
                }

		wsprintfW(szDSoundName, szDSoundNameFormat, wocaps.szPname);
	        res = IFilterMapper2_RegisterFilter(pMapper,
		                              &CLSID_DSoundRender,
					      szDSoundName,
					      &pMoniker,
					      &CLSID_AudioRendererCategory,
					      szDSoundName,
					      &rf2);

                /* FIXME: do additional stuff with IMoniker here, depending on what RegisterFilter does */

		if (pMoniker)
		    IMoniker_Release(pMoniker);

		if (i == iDefaultDevice)
		{
		    FIXME("Default device\n");
		}

                CoTaskMemFree(pTypes);
	    }
	}

        numDevs = waveInGetNumDevs();

        res = DEVENUM_CreateAMCategoryKey(&CLSID_AudioInputDeviceCategory);
        if (FAILED(res)) /* can't register any devices in this category */
            numDevs = 0;

	rfp2.dwFlags = REG_PINFLAG_B_OUTPUT;
        for (i = 0; i < numDevs; i++)
        {
            if (waveInGetDevCapsW(i, &wicaps, sizeof(WAVEINCAPSW))
                == MMSYSERR_NOERROR)
            {
                IMoniker * pMoniker = NULL;

                rfp2.nMediaTypes = 1;
                pTypes = CoTaskMemAlloc(rfp2.nMediaTypes * sizeof(REGPINTYPES));
                if (!pTypes)
                {
                    IFilterMapper2_Release(pMapper);
                    return E_OUTOFMEMORY;
                }

                /* FIXME: Not sure if these are correct */
                pTypes[0].clsMajorType = &MEDIATYPE_Audio;
                pTypes[0].clsMinorType = &MEDIASUBTYPE_PCM;

                rfp2.lpMediaType = pTypes;

                res = IFilterMapper2_RegisterFilter(pMapper,
		                              &CLSID_AudioRecord,
					      wicaps.szPname,
					      &pMoniker,
					      &CLSID_AudioInputDeviceCategory,
					      wicaps.szPname,
					      &rf2);


                if (pMoniker) {
                    VARIANT var;

                    V_VT(&var) = VT_I4;
                    V_I4(&var) = i;
                    res = IMoniker_BindToStorage(pMoniker, NULL, NULL, &IID_IPropertyBag, (LPVOID)&pPropBag);
                    if (SUCCEEDED(res))
                        res = IPropertyBag_Write(pPropBag, wszWaveInID, &var);
                    else
                        pPropBag = NULL;

                    V_VT(&var) = VT_LPWSTR;
                    V_BSTR(&var) = wicaps.szPname;
                    if (SUCCEEDED(res))
                        res = IPropertyBag_Write(pPropBag, wszFriendlyName, &var);

                    if (pPropBag)
                        IPropertyBag_Release(pPropBag);
                    IMoniker_Release(pMoniker);
                }

                CoTaskMemFree(pTypes);
	    }
	}

	numDevs = midiOutGetNumDevs();

        res = DEVENUM_CreateAMCategoryKey(&CLSID_MidiRendererCategory);
        if (FAILED(res)) /* can't register any devices in this category */
            numDevs = 0;

	rfp2.dwFlags = REG_PINFLAG_B_RENDERER;
	for (i = 0; i < numDevs; i++)
	{
	    if (midiOutGetDevCapsW(i, &mocaps, sizeof(MIDIOUTCAPSW))
	        == MMSYSERR_NOERROR)
	    {
                IMoniker * pMoniker = NULL;

                rfp2.nMediaTypes = 1;
                pTypes = CoTaskMemAlloc(rfp2.nMediaTypes * sizeof(REGPINTYPES));
                if (!pTypes)
                {
                    IFilterMapper2_Release(pMapper);
                    return E_OUTOFMEMORY;
                }

                /* FIXME: Not sure if these are correct */
                pTypes[0].clsMajorType = &MEDIATYPE_Midi;
                pTypes[0].clsMinorType = &MEDIASUBTYPE_None;

                rfp2.lpMediaType = pTypes;

                res = IFilterMapper2_RegisterFilter(pMapper,
		                              &CLSID_AVIMIDIRender,
					      mocaps.szPname,
					      &pMoniker,
					      &CLSID_MidiRendererCategory,
					      mocaps.szPname,
					      &rf2);

                /* FIXME: do additional stuff with IMoniker here, depending on what RegisterFilter does */
		/* Native version sets MidiOutId */

		if (pMoniker)
		    IMoniker_Release(pMoniker);

		if (i == iDefaultDevice)
		{
		    FIXME("Default device\n");
		}

                CoTaskMemFree(pTypes);
	    }
	}
        res = DEVENUM_CreateAMCategoryKey(&CLSID_VideoInputDeviceCategory);
        if (SUCCEEDED(res))
            for (i = 0; i < 10; i++)
            {
                WCHAR szDeviceName[32], szDeviceVersion[32], szDevicePath[10];

                if (capGetDriverDescriptionW ((WORD) i,
                                              szDeviceName, sizeof(szDeviceName)/sizeof(WCHAR),
                                              szDeviceVersion, sizeof(szDeviceVersion)/sizeof(WCHAR)))
                {
                    IMoniker * pMoniker = NULL;
                    WCHAR dprintf[] = { 'v','i','d','e','o','%','d',0 };
                    snprintfW(szDevicePath, sizeof(szDevicePath)/sizeof(WCHAR), dprintf, i);
                    /* The above code prevents 1 device with a different ID overwriting another */

                    rfp2.nMediaTypes = 1;
                    pTypes = CoTaskMemAlloc(rfp2.nMediaTypes * sizeof(REGPINTYPES));
                    if (!pTypes) {
                        IFilterMapper2_Release(pMapper);
                        return E_OUTOFMEMORY;
                    }

                    pTypes[0].clsMajorType = &MEDIATYPE_Video;
                    pTypes[0].clsMinorType = &MEDIASUBTYPE_None;

                    rfp2.lpMediaType = pTypes;

                    res = IFilterMapper2_RegisterFilter(pMapper,
                                                        &CLSID_VfwCapture,
                                                        szDeviceName,
                                                        &pMoniker,
                                                        &CLSID_VideoInputDeviceCategory,
                                                        szDevicePath,
                                                        &rf2);

                    if (pMoniker) {
                       OLECHAR wszVfwIndex[] = { 'V','F','W','I','n','d','e','x',0 };
                       VARIANT var;
                       V_VT(&var) = VT_I4;
                       V_I4(&var) = i;
                       res = IMoniker_BindToStorage(pMoniker, NULL, NULL, &IID_IPropertyBag, (LPVOID)&pPropBag);
                       if (SUCCEEDED(res)) {
                           res = IPropertyBag_Write(pPropBag, wszVfwIndex, &var);
                           IPropertyBag_Release(pPropBag);
                       }
                       IMoniker_Release(pMoniker);
                    }

                    if (i == iDefaultDevice) FIXME("Default device\n");
                    CoTaskMemFree(pTypes);
                }
            }
    }

    if (pMapper)
        IFilterMapper2_Release(pMapper);

    register_vfw_codecs();

    SetEvent(DEVENUM_populate_handle);
    return res;
}
コード例 #29
0
HRESULT WIACamera::DigitalCameraCapture(IWiaItem* pIWiaRoot, IplImage** ppIplImage)
{
	HRESULT hr = S_OK;

	IWiaItem* pIWiaItem = NULL;
	hr = pIWiaRoot->DeviceCommand( 0, &WIA_CMD_TAKE_PICTURE, &pIWiaItem );

	if (pIWiaItem==NULL) {
		cvReleaseImage(ppIplImage);
		(*ppIplImage) = NULL;
		return hr;
	}
	IStream **ppStream = NULL;
	LONG	lCount = 0;
	// Create the data callback interface
	CDataCallback *pDataCallback = new CDataCallback( &lCount,&ppStream );
	if (pDataCallback == NULL) {
		return E_OUTOFMEMORY;
	}

	{
		// Get the interface pointers
		IWiaPropertyStorage *pWiaPropertyStorage;
		hr = pIWiaItem->QueryInterface(IID_IWiaPropertyStorage,(void**)&pWiaPropertyStorage);
		if (hr != S_OK) {
			return E_NOINTERFACE;
		}

		IWiaDataTransfer *pIWiaDataTransfer;
		hr = pIWiaItem->QueryInterface(IID_IWiaDataTransfer, (void**)&pIWiaDataTransfer);
		if (hr != S_OK) {
			return E_NOINTERFACE;
		}

		// Set the transfer type
		PROPSPEC specTymed;
		specTymed.ulKind = PRSPEC_PROPID;
		specTymed.propid = WIA_IPA_TYMED;

		PROPVARIANT varTymed;
		varTymed.vt = VT_I4;
		varTymed.lVal = TYMED_CALLBACK;

		hr = pWiaPropertyStorage->WriteMultiple(1, &specTymed, &varTymed, WIA_IPA_FIRST );
		PropVariantClear(&varTymed);
		if (FAILED(hr)) {
			return hr;
		}

		// If there is no transfer format specified, use the device default
		GUID guidFormat = GUID_NULL;
		GUID *pguidFormat = &guidFormat;
		PROPSPEC specPreferredFormat;

		specPreferredFormat.ulKind = PRSPEC_PROPID;
		specPreferredFormat.propid = WIA_IPA_PREFERRED_FORMAT;

		hr = ReadPropertyGuid( pWiaPropertyStorage, &specPreferredFormat, pguidFormat );
		if (FAILED(hr))	{
			return hr;
		}

		// Set the transfer format
		PROPSPEC specFormat;
		PROPVARIANT varFormat;
		specFormat.ulKind = PRSPEC_PROPID;
		specFormat.propid = WIA_IPA_FORMAT;
		varFormat.vt = VT_CLSID;
		varFormat.puuid = (CLSID *) CoTaskMemAlloc(sizeof(CLSID));
		if (varFormat.puuid == NULL) {
			return E_OUTOFMEMORY;
		}
		*varFormat.puuid = *pguidFormat;
		hr = pWiaPropertyStorage->WriteMultiple( 1, &specFormat, &varFormat, WIA_IPA_FIRST );
		PropVariantClear(&varFormat);
		if (FAILED(hr)) {
			return hr;
		}

		// Read the transfer buffer size from the device, default to 64K
		PROPSPEC specBufferSize;
		specBufferSize.ulKind = PRSPEC_PROPID;
		specBufferSize.propid = WIA_IPA_BUFFER_SIZE;
		LONG nBufferSize;
		hr = ReadPropertyLong( pWiaPropertyStorage, &specBufferSize, &nBufferSize );
		if (FAILED(hr)) {
			nBufferSize = 64 * 1024;
		}

		// Choose double buffered transfer for better performance
		WIA_DATA_TRANSFER_INFO WiaDataTransferInfo = { 0 };
		WiaDataTransferInfo.ulSize        = sizeof(WIA_DATA_TRANSFER_INFO);
		WiaDataTransferInfo.ulBufferSize  = 2 * nBufferSize;
		WiaDataTransferInfo.bDoubleBuffer = TRUE;

		// Start the transfer
		hr = pIWiaDataTransfer->idtGetBandedData( &WiaDataTransferInfo, pDataCallback );

		if (pWiaPropertyStorage) {
			pWiaPropertyStorage->Release();
			pWiaPropertyStorage = NULL;
		}
		if (pIWiaDataTransfer) {
			pIWiaDataTransfer->Release();
			pIWiaDataTransfer = NULL;
		}
	}
	if (pIWiaItem) {
		// Delete file from DigitalCamera storage
		pIWiaItem->DeleteItem(0);
		pIWiaItem->Release();
		pIWiaItem = NULL;
	}

	if (lCount!=1) throw "Error.\n"; 

	if ( SUCCEEDED(hr) ) { 
		Gdiplus::Bitmap myBmp(ppStream[0]);
		int Width = myBmp.GetWidth();
		int Height = myBmp.GetHeight();
		Gdiplus::Rect rect(0, 0, Width, Height);
		Gdiplus::BitmapData myBitmapData;
		Gdiplus::Status res = 
			myBmp.LockBits(
			&rect, Gdiplus::ImageLockModeRead,
			PixelFormat24bppRGB, &myBitmapData
		);
		if ( (*ppIplImage)==NULL ) {
			(*ppIplImage) = cvCreateImage(cvSize(Width,Height),IPL_DEPTH_8U,3);
		} else {
			CvSize oldSize = cvGetSize((*ppIplImage));
			if ( oldSize.width!=Width || oldSize.height!=Height ) {
				throw "Warning.\n";
				cvReleaseImage(&(*ppIplImage));
				(*ppIplImage) = cvCreateImage(cvSize(Width,Height),IPL_DEPTH_8U,3);
			}
		}

		unsigned char *pIplData = (unsigned char*)(*ppIplImage)->imageData;
		for ( int h=0; h < Height; h++) {
			unsigned char *pIplLine = &pIplData[(*ppIplImage)->widthStep*h];
			unsigned char *pBitmapLine = &((unsigned char*)myBitmapData.Scan0)[myBitmapData.Stride*h];
			memcpy( pIplLine, pBitmapLine, sizeof(unsigned char)*Width*3 );
			/*
			for ( int w=0; w < Width; w++) {
				pIplLine[w*3+0] = pBitmapLine[w*3+2];
				pIplLine[w*3+1] = pBitmapLine[w*3+1];
				pIplLine[w*3+2] = pBitmapLine[w*3+0];
			}
			*/
		}

	} else {
		delete (*ppIplImage);
		(*ppIplImage) = NULL;
	}
	ppStream[0]->Release();

	return hr;
}
コード例 #30
0
ファイル: videoenc.cpp プロジェクト: mason105/red5cpp
HRESULT MakeVideoOutputType(IMediaObject   *pDMO,
							AM_MEDIA_TYPE  *pmtIn,
							VideoEncParams *pParams,
							AM_MEDIA_TYPE  *pmt      )
{

	HRESULT             hr                   = S_OK;
	VIDEOINFOHEADER2    *pvih2               = NULL;
	VIDEOINFOHEADER     vih;
	IWMCodecPrivateData *pWMCodecPrivateData = NULL;
	DWORD               cbPrivateData        = 0;
	BYTE                *pbPrivateData       = NULL;
	BYTE                *pNewFormat          = NULL;

	if( NULL == pDMO    ||
		NULL == pmtIn   ||
		NULL == pParams ||
		NULL == pmt     )
	{
		return ( E_INVALIDARG );
	}

	if( NULL == pmtIn->pbFormat || pmtIn->cbFormat < sizeof( VIDEOINFOHEADER ) )
	{
		return ( E_INVALIDARG );
	}

	// make up a partial media type
	pmt->majortype            = MEDIATYPE_Video;
	pmt->formattype           = FORMAT_VideoInfo;
	pmt->bFixedSizeSamples    = FALSE;
	pmt->bTemporalCompression = TRUE;

	if( pmtIn->formattype == FORMAT_VideoInfo )
	{
		vih = *(VIDEOINFOHEADER*)pmtIn->pbFormat;
	}
	else if( pmtIn->formattype == FORMAT_VideoInfo2 )
	{
		pvih2 = (VIDEOINFOHEADER2*)pmtIn->pbFormat;
		vih.rcSource        = pvih2->rcSource;
		vih.rcTarget        = pvih2->rcTarget;
		vih.AvgTimePerFrame = pvih2->AvgTimePerFrame;
		vih.bmiHeader       = pvih2->bmiHeader;
	}
	else
		return ( E_VIDEO_INVALID_INPUT_TYPE );

	vih.dwBitRate            = (DWORD)pParams->nBitrate;
	vih.dwBitErrorRate       = 0;
	vih.bmiHeader.biPlanes   = 1;
	vih.bmiHeader.biBitCount = 24;
	pmt->subtype = WMCMEDIASUBTYPE_WMV1;
	pmt->subtype.Data1=pParams->dwTag;
	vih.bmiHeader.biCompression = pParams->dwTag;
	//
	//use the partial format above to get the private data
	//
	pmt->pbFormat = (BYTE*)CoTaskMemAlloc( sizeof( VIDEOINFOHEADER));
	memcpy( pmt->pbFormat , &vih, sizeof( VIDEOINFOHEADER));
	pmt->cbFormat = sizeof( vih );

	do
	{
		hr = pDMO->QueryInterface(IID_IWMCodecPrivateData, (void**)&pWMCodecPrivateData);
		if( FAILED( hr ) )
		{
			hr = E_NO_PRIVATE_DATA;
			break;
		}

		hr = pWMCodecPrivateData->SetPartialOutputType( pmt );
		if( FAILED( hr ) )
		{
			hr = E_PARTIAL_TYPE_REJECTED;
			break;
		}

		hr = pWMCodecPrivateData->GetPrivateData( NULL, &cbPrivateData );
		if( FAILED( hr ) )
		{
			hr = E_NO_PRIVATE_DATA_COUNT;
			break;
		}

		if( 0 == cbPrivateData )
		{ // No private data
			hr = S_OK;
			break;
		}
		pbPrivateData = new BYTE[ cbPrivateData ];
		if( pbPrivateData == NULL )
		{
			hr = E_OUTOFMEMORY;
			break;
		}
		//
		// get the private data
		//
		hr = pWMCodecPrivateData->GetPrivateData( pbPrivateData, &cbPrivateData );
		if( FAILED( hr ) )
		{
			hr = E_PRIVATE_DATA_FAILED;
			break;
		}

		//
		//modify the media type accordingly
		//
		pNewFormat = (BYTE*)CoTaskMemAlloc( sizeof( VIDEOINFOHEADER) + cbPrivateData );
		if( NULL == pNewFormat )
		{
			hr = E_OUTOFMEMORY;
			break;
		}

		memcpy( pNewFormat, pmt->pbFormat, sizeof( VIDEOINFOHEADER));
		CoTaskMemFree(pmt->pbFormat);
		memcpy( pNewFormat + sizeof( VIDEOINFOHEADER), pbPrivateData, cbPrivateData);
		pmt->pbFormat = pNewFormat;
		pmt->cbFormat = sizeof( VIDEOINFOHEADER) + cbPrivateData;
		((VIDEOINFOHEADER*)pmt->pbFormat)->bmiHeader.biSize         += cbPrivateData;
		((VIDEOINFOHEADER*)pmt->pbFormat)->bmiHeader.biClrUsed       = 0;
		((VIDEOINFOHEADER*)pmt->pbFormat)->bmiHeader.biClrImportant  = 0;
		((VIDEOINFOHEADER*)pmt->pbFormat)->bmiHeader.biXPelsPerMeter = 0;
		((VIDEOINFOHEADER*)pmt->pbFormat)->bmiHeader.biYPelsPerMeter = 0;
	}
	while( FALSE );

	SAFERELEASE( pWMCodecPrivateData );
	SAFEDELETE( pbPrivateData );

	return ( hr );
}