blob: 4b56772ebf5f6663e3fff895859aa937c7d3415e [file] [log] [blame]
Austin Orion0bb354c2020-10-29 11:30:10 -07001/*
2 * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "rtc_base/win/scoped_com_initializer.h"
12
Austin Oriond19d0cf2021-01-27 09:40:21 -080013#include "rtc_base/checks.h"
14#include "rtc_base/logging.h"
15
Austin Orion0bb354c2020-10-29 11:30:10 -070016namespace webrtc {
17
18ScopedCOMInitializer::ScopedCOMInitializer() {
Harald Alvestrand97597c02021-11-04 12:01:23 +000019 RTC_DLOG(LS_INFO) << "Single-Threaded Apartment (STA) COM thread";
Austin Orion0bb354c2020-10-29 11:30:10 -070020 Initialize(COINIT_APARTMENTTHREADED);
21}
22
23// Constructor for MTA initialization.
24ScopedCOMInitializer::ScopedCOMInitializer(SelectMTA mta) {
Harald Alvestrand97597c02021-11-04 12:01:23 +000025 RTC_DLOG(LS_INFO) << "Multi-Threaded Apartment (MTA) COM thread";
Austin Orion0bb354c2020-10-29 11:30:10 -070026 Initialize(COINIT_MULTITHREADED);
27}
28
29ScopedCOMInitializer::~ScopedCOMInitializer() {
30 if (Succeeded()) {
31 CoUninitialize();
32 }
33}
34
35void ScopedCOMInitializer::Initialize(COINIT init) {
36 // Initializes the COM library for use by the calling thread, sets the
37 // thread's concurrency model, and creates a new apartment for the thread
38 // if one is required. CoInitializeEx must be called at least once, and is
39 // usually called only once, for each thread that uses the COM library.
40 hr_ = CoInitializeEx(NULL, init);
41 RTC_CHECK_NE(RPC_E_CHANGED_MODE, hr_)
42 << "Invalid COM thread model change (MTA->STA)";
43 // Multiple calls to CoInitializeEx by the same thread are allowed as long
44 // as they pass the same concurrency flag, but subsequent valid calls
45 // return S_FALSE. To close the COM library gracefully on a thread, each
46 // successful call to CoInitializeEx, including any call that returns
47 // S_FALSE, must be balanced by a corresponding call to CoUninitialize.
48 if (hr_ == S_OK) {
Harald Alvestrand97597c02021-11-04 12:01:23 +000049 RTC_DLOG(LS_INFO)
Austin Orion0bb354c2020-10-29 11:30:10 -070050 << "The COM library was initialized successfully on this thread";
51 } else if (hr_ == S_FALSE) {
Harald Alvestrandef5b21e2021-11-27 21:31:08 +000052 RTC_DLOG(LS_WARNING)
Austin Orion0bb354c2020-10-29 11:30:10 -070053 << "The COM library is already initialized on this thread";
54 }
55}
56
57} // namespace webrtc