Chromium Code Reviews

Side by Side Diff: chrome/browser/media/webrtc_rtp_dump_writer.cc

Issue 264793017: Implements RTP header dumping. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: for tommi's Created 6 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff |
OLDNEW
(Empty)
1 // Copyright 2014 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 "chrome/browser/media/webrtc_rtp_dump_writer.h"
6
7 #include "base/big_endian.h"
8 #include "base/file_util.h"
9 #include "base/logging.h"
10 #include "content/public/browser/browser_thread.h"
11 #include "third_party/zlib/zlib.h"
12
13 using content::BrowserThread;
14
15 namespace {
16
17 // The header of the dump file.
18 struct RtpDumpFileHeader {
Henrik Grunell 2014/05/23 12:17:51 This is more than a data container, make it a clas
jiayl 2014/05/23 17:48:36 Good point. Changed to helper functions.
19 static const unsigned char kFirstLine[];
20 static const size_t kRtpDumpFileHeaderSize = 16;
21
22 explicit RtpDumpFileHeader(const base::TimeTicks& start)
23 : start_time(start - base::TimeTicks()), source(0), port(0), padding(0) {}
24
25 // Append the RTP dump file header to |output|.
26 void WriteBigEndian(std::vector<uint8>* output) {
27 size_t buffer_start_pos = output->size();
28 output->resize(output->size() + kRtpDumpFileHeaderSize);
29
30 char* buffer = reinterpret_cast<char*>(output->data() + buffer_start_pos);
31
32 uint32 start_sec = start_time.InSeconds();
33 base::WriteBigEndian(buffer, start_sec);
34 buffer += sizeof(start_sec);
35
36 uint32 start_usec =
37 start_time.InMilliseconds() * base::Time::kMicrosecondsPerMillisecond;
38 base::WriteBigEndian(buffer, start_usec);
39 buffer += sizeof(start_usec);
40
41 base::WriteBigEndian(buffer, source);
42 buffer += sizeof(source);
43
44 base::WriteBigEndian(buffer, port);
45 buffer += sizeof(port);
46
47 base::WriteBigEndian(buffer, padding);
48 }
49
50 const base::TimeDelta start_time; // start of recording.
51 const uint32 source; // network source (multicast address). Always 0.
52 const uint16 port; // UDP port. Always 0.
53 const uint16 padding; // 2 bytes padding.
54 };
55
56 const unsigned char RtpDumpFileHeader::kFirstLine[] =
57 "#!rtpplay1.0 0.0.0.0/0\n";
58
59 // The header for each packet dump.
60 struct PacketDumpHeader {
Henrik Grunell 2014/05/23 12:17:51 Same here.
jiayl 2014/05/23 17:48:36 Done.
61 static const size_t kPacketDumpHeaderSize = 8;
62
63 PacketDumpHeader(const base::TimeTicks& start,
64 uint16 dump_length,
65 uint16 packet_length)
66 : packet_dump_length(dump_length),
67 packet_length(packet_length),
68 offset_ms((base::TimeTicks::Now() - start).InMilliseconds()) {}
69
70 void WriteBigEndian(std::vector<uint8>* output) {
71 size_t buffer_start_pos = output->size();
72 output->resize(output->size() + kPacketDumpHeaderSize);
73
74 char* buffer = reinterpret_cast<char*>(output->data() + buffer_start_pos);
75
76 base::WriteBigEndian(buffer, packet_dump_length);
77 buffer += sizeof(packet_dump_length);
78
79 base::WriteBigEndian(buffer, packet_length);
80 buffer += sizeof(packet_length);
81
82 base::WriteBigEndian(buffer, offset_ms);
83 }
84
85 // Length of the packet dump including this header.
86 const uint16 packet_dump_length;
87
88 // Length of header + payload of the RTP packet.
89 const uint16 packet_length;
90
91 // Milliseconds since the start of recording.
92 const uint32 offset_ms;
93 };
94
95 // Append |src_len| bytes from |src| to |dest|.
96 bool AppendToBuffer(const uint8* src,
97 size_t src_len,
98 std::vector<uint8>* dest) {
99 if (dest->capacity() < dest->size() + src_len)
100 return false;
101
102 for (size_t i = 0; i < src_len; ++i)
Henrik Grunell 2014/05/23 12:17:51 This should be optimizable. Use resize and pointer
jiayl 2014/05/23 17:48:36 Done.
103 dest->push_back(src[i]);
104
105 return true;
106 }
107
108 static const size_t kMinimumGzipOutputBufferSize = 256;
109
110 } // namespace
111
112 // This class is running on the FILE thread for compressing and writing the
113 // dump buffer to disk.
114 class WebRtcRtpDumpWriter::FileThreadWorker {
115 public:
116 explicit FileThreadWorker(const base::FilePath& dump_path)
117 : dump_path_(dump_path), stream_initialized_(false) {
118 thread_checker_.DetachFromThread();
119 }
120
121 ~FileThreadWorker() { DCHECK(thread_checker_.CalledOnValidThread()); }
122
123 // Compresses the data in |buffer| write to the dump file. If |end_stream| is
124 // true, the compression stream will be ended and the dump file cannot be
125 // written to any more.
126 void CompressAndWriteToFileOnFileThread(
127 scoped_ptr<std::vector<uint8> > buffer,
128 bool end_stream,
129 FlushResult* result,
130 size_t* bytes_written) {
131 DCHECK(thread_checker_.CalledOnValidThread());
132
133 *result = FLUSH_RESULT_SUCCESS;
134 *bytes_written = 0;
135
136 if (buffer->size()) {
137 *bytes_written = CompressAndWriteBufferToFile(buffer.get(), result);
138 } else if (!base::PathExists(dump_path_)) {
139 *result = FLUSH_RESULT_NO_DATA;
140 }
141
142 if (end_stream) {
143 if (!EndDumpFile())
144 *result = FLUSH_RESULT_FAILURE;
145 }
146 }
147
148 private:
149 // Helper for CompressAndWriteToFileOnFileThread to compress and write one
150 // dump.
151 size_t CompressAndWriteBufferToFile(std::vector<uint8>* buffer,
152 FlushResult* result) {
153 DCHECK(thread_checker_.CalledOnValidThread());
154 DCHECK(buffer->size());
155
156 *result = FLUSH_RESULT_SUCCESS;
157
158 std::vector<uint8> compressed_buffer;
159 if (!Compress(buffer, &compressed_buffer)) {
160 DVLOG(2) << "Compressing buffer failed.";
161 *result = FLUSH_RESULT_FAILURE;
162 return 0;
163 }
164
165 int bytes_written = -1;
166
167 if (base::PathExists(dump_path_)) {
168 bytes_written = base::AppendToFile(
169 dump_path_,
170 reinterpret_cast<const char*>(compressed_buffer.data()),
171 compressed_buffer.size());
172 } else {
173 bytes_written = base::WriteFile(
174 dump_path_,
175 reinterpret_cast<const char*>(compressed_buffer.data()),
176 compressed_buffer.size());
177 }
178
179 if (bytes_written == -1) {
180 DVLOG(2) << "Writing file failed: " << dump_path_.value();
181 *result = FLUSH_RESULT_FAILURE;
182 return 0;
183 }
184
185 DCHECK_EQ(static_cast<size_t>(bytes_written), compressed_buffer.size());
186
187 return bytes_written;
188 }
189
190 // Compresses |input| into |output|.
191 bool Compress(std::vector<uint8>* input, std::vector<uint8>* output) {
192 DCHECK(thread_checker_.CalledOnValidThread());
193 int result = Z_OK;
194
195 output->resize(std::max(kMinimumGzipOutputBufferSize, input->size()));
196
197 if (!stream_initialized_) {
198 memset(&stream_, 0, sizeof(stream_));
199 result = deflateInit2(&stream_,
200 Z_DEFAULT_COMPRESSION,
201 Z_DEFLATED,
202 // windowBits = 15 is default, 16 is added to
203 // produce a gzip header + trailer.
204 15 + 16,
205 8, // memLevel = 8 is default.
206 Z_DEFAULT_STRATEGY);
207 DCHECK_EQ(Z_OK, result);
208 stream_initialized_ = true;
209 }
210
211 stream_.next_in = input->data();
212 stream_.avail_in = input->size();
213 stream_.next_out = output->data();
214 stream_.avail_out = output->size();
215
216 result = deflate(&stream_, Z_SYNC_FLUSH);
217 DCHECK_EQ(Z_OK, result);
218 DCHECK_EQ(0U, stream_.avail_in);
219
220 output->resize(output->size() - stream_.avail_out);
221
222 stream_.next_in = NULL;
223 stream_.next_out = NULL;
224 stream_.avail_out = 0;
225 return true;
226 }
227
228 // Ends the compression stream and completes the dump file.
229 bool EndDumpFile() {
230 DCHECK(thread_checker_.CalledOnValidThread());
231
232 if (!stream_initialized_)
233 return true;
234
235 std::vector<uint8> output_buffer;
236 output_buffer.resize(kMinimumGzipOutputBufferSize);
237
238 stream_.next_in = NULL;
239 stream_.avail_in = 0;
240 stream_.next_out = output_buffer.data();
241 stream_.avail_out = output_buffer.size();
242
243 int result = deflate(&stream_, Z_FINISH);
244 DCHECK_EQ(Z_STREAM_END, result);
245
246 result = deflateEnd(&stream_);
247 DCHECK_EQ(Z_OK, result);
248
249 output_buffer.resize(output_buffer.size() - stream_.avail_out);
250
251 int bytes_written =
252 base::AppendToFile(dump_path_,
253 reinterpret_cast<const char*>(output_buffer.data()),
254 output_buffer.size());
255
256 return bytes_written > 0;
257 }
258
259 const base::FilePath dump_path_;
260
261 z_stream stream_;
262 bool stream_initialized_;
263
264 base::ThreadChecker thread_checker_;
265
266 DISALLOW_COPY_AND_ASSIGN(FileThreadWorker);
267 };
268
269 WebRtcRtpDumpWriter::WebRtcRtpDumpWriter(
270 const base::FilePath& incoming_dump_path,
271 const base::FilePath& outgoing_dump_path,
272 size_t max_dump_size,
273 const base::Closure& max_dump_size_reached_callback)
274 : max_dump_size_(max_dump_size),
275 max_dump_size_reached_callback_(max_dump_size_reached_callback),
276 total_dump_size_on_disk_(0),
277 incoming_file_thread_worker_(new FileThreadWorker(incoming_dump_path)),
278 outgoing_file_thread_worker_(new FileThreadWorker(outgoing_dump_path)),
279 weak_ptr_factory_(this) {
280 }
281
282 WebRtcRtpDumpWriter::~WebRtcRtpDumpWriter() {
283 DCHECK(thread_checker_.CalledOnValidThread());
284 if (!BrowserThread::DeleteSoon(BrowserThread::FILE,
285 FROM_HERE,
286 incoming_file_thread_worker_.release())) {
287 DCHECK(false);
288 }
289
290 if (!BrowserThread::DeleteSoon(BrowserThread::FILE,
291 FROM_HERE,
292 outgoing_file_thread_worker_.release())) {
293 DCHECK(false);
294 }
295 }
296
297 void WebRtcRtpDumpWriter::WriteRtpPacket(const uint8* packet_header,
298 size_t header_length,
299 size_t packet_length,
300 bool incoming) {
301 DCHECK(thread_checker_.CalledOnValidThread());
302
303 static const size_t kMaxInMemoryBufferSize = 65536; // 64KB
304
305 std::vector<uint8>* dest_buffer =
306 incoming ? &incoming_buffer_ : &outgoing_buffer_;
307 bool succeeded = true;
308 if (!dest_buffer->capacity()) {
309 dest_buffer->reserve(std::min(kMaxInMemoryBufferSize, max_dump_size_));
310
311 start_time_ = base::TimeTicks::Now();
312
313 // Writes the dump file header.
314 succeeded = AppendToBuffer(RtpDumpFileHeader::kFirstLine,
315 arraysize(RtpDumpFileHeader::kFirstLine) - 1,
316 dest_buffer);
317 DCHECK(succeeded);
318
319 RtpDumpFileHeader header(start_time_);
320 header.WriteBigEndian(dest_buffer);
321 }
322
323 size_t packet_dump_length = sizeof(PacketDumpHeader) + header_length;
324
325 // Flushes the buffer to disk if the buffer is full.
326 if (dest_buffer->capacity() < dest_buffer->size() + packet_dump_length)
327 FlushBuffer(incoming, false, FlushDoneCallback());
328
329 // Writes the packet dump header.
330 PacketDumpHeader packet_dump_header(
331 start_time_, packet_dump_length, packet_length);
332 packet_dump_header.WriteBigEndian(dest_buffer);
333
334 // Writes the actual RTP packet header.
335 succeeded = AppendToBuffer(packet_header, header_length, dest_buffer);
336 DCHECK(succeeded);
337 }
338
339 void WebRtcRtpDumpWriter::EndDump(RtpDumpType type,
340 const EndDumpCallback& finished_callback) {
341 DCHECK(thread_checker_.CalledOnValidThread());
342
343 bool incoming = (type == RTP_DUMP_BOTH || type == RTP_DUMP_INCOMING);
344 EndDumpContext context(type, finished_callback);
345
346 FlushBuffer(incoming,
347 true,
348 base::Bind(&WebRtcRtpDumpWriter::OnDumpEnded,
349 weak_ptr_factory_.GetWeakPtr(),
350 context,
351 incoming));
352 }
353
354 size_t WebRtcRtpDumpWriter::max_dump_size() const {
355 DCHECK(thread_checker_.CalledOnValidThread());
356 return max_dump_size_;
357 }
358
359 WebRtcRtpDumpWriter::EndDumpContext::EndDumpContext(
360 RtpDumpType type,
361 const EndDumpCallback& callback)
362 : type(type),
363 incoming_succeeded(false),
364 outgoing_succeeded(false),
365 callback(callback) {
366 }
367
368 WebRtcRtpDumpWriter::EndDumpContext::~EndDumpContext() {
369 }
370
371 void WebRtcRtpDumpWriter::FlushBuffer(bool incoming,
372 bool end_stream,
373 const FlushDoneCallback& callback) {
374 DCHECK(thread_checker_.CalledOnValidThread());
375
376 scoped_ptr<std::vector<uint8> > new_buffer(new std::vector<uint8>());
377
378 if (incoming) {
379 new_buffer->reserve(incoming_buffer_.capacity());
380 new_buffer->swap(incoming_buffer_);
381 } else {
382 new_buffer->reserve(outgoing_buffer_.capacity());
383 new_buffer->swap(outgoing_buffer_);
384 }
385
386 scoped_ptr<FlushResult> result(new FlushResult(FLUSH_RESULT_FAILURE));
387
388 scoped_ptr<size_t> bytes_written(new size_t(0));
389
390 FileThreadWorker* worker = incoming ? incoming_file_thread_worker_.get()
391 : outgoing_file_thread_worker_.get();
392
393 // Using "Unretained(worker)" because |worker| is owner by this object and it
394 // guaranteed to be deleted on the FILE thread before this object goes away.
395 BrowserThread::PostTaskAndReply(
396 BrowserThread::FILE,
397 FROM_HERE,
398 base::Bind(&FileThreadWorker::CompressAndWriteToFileOnFileThread,
399 base::Unretained(worker),
400 Passed(&new_buffer),
401 end_stream,
402 result.get(),
403 bytes_written.get()),
404 // OnFlushDone is necessary to avoid running the callback after this
405 // object is gone.
406 base::Bind(&WebRtcRtpDumpWriter::OnFlushDone,
407 weak_ptr_factory_.GetWeakPtr(),
408 callback,
409 Passed(&result),
410 Passed(&bytes_written)));
411 }
412
413 void WebRtcRtpDumpWriter::OnFlushDone(const FlushDoneCallback& callback,
414 const scoped_ptr<FlushResult>& result,
415 const scoped_ptr<size_t>& bytes_written) {
416 DCHECK(thread_checker_.CalledOnValidThread());
417
418 total_dump_size_on_disk_ += *bytes_written;
419
420 if (total_dump_size_on_disk_ >= max_dump_size_ &&
421 !max_dump_size_reached_callback_.is_null()) {
422 max_dump_size_reached_callback_.Run();
423 }
424
425 // Returns success for FLUSH_RESULT_MAX_SIZE_REACHED since the dump is still
426 // valid.
427 if (!callback.is_null()) {
428 callback.Run(*result != FLUSH_RESULT_FAILURE &&
429 *result != FLUSH_RESULT_NO_DATA);
430 }
431 }
432
433 void WebRtcRtpDumpWriter::OnDumpEnded(EndDumpContext context,
434 bool incoming,
435 bool success) {
436 DCHECK(thread_checker_.CalledOnValidThread());
437
438 DVLOG(2) << "Dump ended, incoming = " << incoming
439 << ", succeeded = " << success;
440
441 if (incoming)
442 context.incoming_succeeded = success;
443 else
444 context.outgoing_succeeded = success;
445
446 // End the outgoing dump if needed.
447 if (incoming && context.type == RTP_DUMP_BOTH) {
448 FlushBuffer(false,
449 true,
450 base::Bind(&WebRtcRtpDumpWriter::OnDumpEnded,
451 weak_ptr_factory_.GetWeakPtr(),
452 context,
453 false));
454 return;
455 }
456
457 context.callback.Run(context.incoming_succeeded, context.outgoing_succeeded);
458 }
OLDNEW

Powered by Google App Engine