1 /*
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
13 #include "rtc_base/checks.h"
14 #include "rtc_base/logging.h"
15
16 namespace webrtc {
17
ScopedCOMInitializer()18 ScopedCOMInitializer::ScopedCOMInitializer() {
19 RTC_DLOG(LS_INFO) << "Single-Threaded Apartment (STA) COM thread";
20 Initialize(COINIT_APARTMENTTHREADED);
21 }
22
23 // Constructor for MTA initialization.
ScopedCOMInitializer(SelectMTA mta)24 ScopedCOMInitializer::ScopedCOMInitializer(SelectMTA mta) {
25 RTC_DLOG(LS_INFO) << "Multi-Threaded Apartment (MTA) COM thread";
26 Initialize(COINIT_MULTITHREADED);
27 }
28
~ScopedCOMInitializer()29 ScopedCOMInitializer::~ScopedCOMInitializer() {
30 if (Succeeded()) {
31 CoUninitialize();
32 }
33 }
34
Initialize(COINIT init)35 void 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) {
49 RTC_DLOG(LS_INFO)
50 << "The COM library was initialized successfully on this thread";
51 } else if (hr_ == S_FALSE) {
52 RTC_DLOG(LS_WARNING)
53 << "The COM library is already initialized on this thread";
54 }
55 }
56
57 } // namespace webrtc
58