OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "media/audio/async_socket_io_handler.h" |
| 6 |
| 7 namespace media { |
| 8 |
| 9 AsyncSocketIoHandler::AsyncSocketIoHandler() |
| 10 : socket_(base::SyncSocket::kInvalidHandle), |
| 11 context_(NULL) {} |
| 12 |
| 13 AsyncSocketIoHandler::~AsyncSocketIoHandler() { |
| 14 // We need to be deleted on the correct thread to avoid racing with the |
| 15 // message loop thread. |
| 16 DCHECK(CalledOnValidThread()); |
| 17 |
| 18 if (context_) { |
| 19 if (!read_complete_.is_null()) { |
| 20 // Make the context be deleted by the message pump when done. |
| 21 context_->handler = NULL; |
| 22 } else { |
| 23 delete context_; |
| 24 } |
| 25 } |
| 26 } |
| 27 |
| 28 // Implementation of IOHandler on Windows. |
| 29 void AsyncSocketIoHandler::OnIOCompleted(MessageLoopForIO::IOContext* context, |
| 30 DWORD bytes_transfered, |
| 31 DWORD error) { |
| 32 DCHECK(CalledOnValidThread()); |
| 33 DCHECK_EQ(context_, context); |
| 34 if (!read_complete_.is_null()) { |
| 35 read_complete_.Run(error == ERROR_SUCCESS ? bytes_transfered : 0); |
| 36 read_complete_.Reset(); |
| 37 } |
| 38 } |
| 39 |
| 40 bool AsyncSocketIoHandler::Read(char* buffer, int buffer_len, |
| 41 const ReadCompleteCallback& callback) { |
| 42 DCHECK(CalledOnValidThread()); |
| 43 DCHECK(read_complete_.is_null()); |
| 44 DCHECK_NE(socket_, base::SyncSocket::kInvalidHandle); |
| 45 |
| 46 read_complete_ = callback; |
| 47 |
| 48 DWORD bytes_read = 0; |
| 49 BOOL ok = ::ReadFile(socket_, buffer, buffer_len, &bytes_read, |
| 50 &context_->overlapped); |
| 51 // The completion port will be signaled regardless of completing the read |
| 52 // straight away or asynchronously (ERROR_IO_PENDING). OnIOCompleted() will |
| 53 // be called regardless and we don't need to explicitly run the callback |
| 54 // in the case where ok is FALSE and GLE==ERROR_IO_PENDING. |
| 55 return ok || GetLastError() == ERROR_IO_PENDING; |
| 56 } |
| 57 |
| 58 bool AsyncSocketIoHandler::Initialize(base::SyncSocket::Handle socket) { |
| 59 DCHECK(!context_); |
| 60 DCHECK_EQ(socket_, base::SyncSocket::kInvalidHandle); |
| 61 |
| 62 DetachFromThread(); |
| 63 |
| 64 socket_ = socket; |
| 65 MessageLoopForIO::current()->RegisterIOHandler(socket, this); |
| 66 |
| 67 context_ = new MessageLoopForIO::IOContext(); |
| 68 context_->handler = this; |
| 69 memset(&context_->overlapped, 0, sizeof(context_->overlapped)); |
| 70 |
| 71 return true; |
| 72 } |
| 73 |
| 74 } // namespace media. |
OLD | NEW |