From 14bea19efe19df2f015f0582d3a9999ce749a549 Mon Sep 17 00:00:00 2001 From: Garo Bournoutian Date: Sat, 6 Jan 2024 01:13:41 -0800 Subject: [PATCH] Deprecate SbTime APIs - Replace all remaining usages of SbTime - Deprecate the APIs in starboard/time.h b/302733082 Test-On-Device: true --- base/time/time_now_starboard.cc | 1 - base/time/time_starboard.cc | 1 - .../update_client/unzip/unzip_impl_cobalt.cc | 1 - .../java/dev/cobalt/coat/StarboardBridge.java | 4 +- .../shared/android_media_session_client.cc | 10 +- .../android/shared/application_android.cc | 13 +- .../android/shared/application_android.h | 4 +- .../shared/audio_renderer_passthrough.cc | 39 +++-- .../shared/audio_renderer_passthrough.h | 19 +- .../audio_sink_min_required_frames_tester.cc | 4 +- .../audio_sink_min_required_frames_tester.h | 2 +- .../shared/audio_track_audio_sink_type.cc | 49 +++--- .../shared/audio_track_audio_sink_type.h | 11 +- .../android/shared/audio_track_bridge.cc | 8 +- starboard/android/shared/audio_track_bridge.h | 7 +- starboard/android/shared/log_internal.cc | 4 +- starboard/android/shared/log_internal.h | 3 +- .../android/shared/media_codec_bridge.cc | 2 +- starboard/android/shared/media_codec_bridge.h | 4 +- starboard/android/shared/media_decoder.cc | 8 +- starboard/android/shared/media_decoder.h | 4 +- .../shared/player_components_factory.h | 4 +- starboard/android/shared/video_decoder.cc | 24 +-- starboard/android/shared/video_decoder.h | 6 +- .../android/shared/video_frame_tracker.cc | 9 +- .../android/shared/video_frame_tracker.h | 15 +- .../shared/video_frame_tracker_test.cc | 3 +- .../android/shared/video_render_algorithm.cc | 12 +- .../android/shared/video_render_algorithm.h | 2 +- starboard/client_porting/eztime/eztime.cc | 21 ++- starboard/client_porting/eztime/eztime.h | 21 ++- .../client_porting/eztime/eztime_test.cc | 17 +- starboard/common/condition_variable.cc | 2 +- starboard/common/condition_variable.h | 6 +- .../common/experimental/concurrency_debug.cc | 1 - starboard/common/log.cc | 1 - starboard/common/queue.h | 14 +- starboard/common/recursive_mutex.cc | 1 - starboard/common/semaphore.cc | 7 +- starboard/common/semaphore.h | 5 +- starboard/common/socket.cc | 2 +- starboard/common/socket.h | 2 +- starboard/common/thread.cc | 6 +- starboard/common/thread.h | 5 +- starboard/condition_variable.h | 7 +- starboard/doc/style.md | 5 - starboard/elf_loader/elf_loader.cc | 8 +- starboard/elf_loader/exported_symbols.cc | 4 +- starboard/event.h | 5 +- starboard/extension/demuxer.h | 17 +- starboard/extension/enhanced_audio.h | 7 +- starboard/extension/media_session.h | 5 +- starboard/file.h | 13 +- starboard/input.h | 1 - .../linux/shared/player_components_factory.cc | 4 +- starboard/loader_app/drain_file.cc | 21 ++- starboard/loader_app/drain_file.h | 9 +- starboard/loader_app/drain_file_helper.cc | 4 +- starboard/loader_app/drain_file_helper.h | 5 +- starboard/loader_app/drain_file_test.cc | 26 +-- starboard/media.h | 34 ++-- starboard/nplb/BUILD.gn | 1 + starboard/nplb/arpa_inet_test.cc | 2 +- starboard/nplb/atomic_test.cc | 3 +- starboard/nplb/audio_sink_helpers.cc | 19 +- starboard/nplb/audio_sink_helpers.h | 3 +- starboard/nplb/audio_sink_test.cc | 3 +- .../condition_variable_wait_timed_test.cc | 25 +-- starboard/nplb/drm_session_test.cc | 3 +- starboard/nplb/extern_c_test.cc | 2 + starboard/nplb/file_get_info_test.cc | 10 +- starboard/nplb/file_get_path_info_test.cc | 10 +- starboard/nplb/include_all.c | 2 + starboard/nplb/media_buffer_test.cc | 4 +- ...media_can_play_mime_and_key_system_test.cc | 14 +- starboard/nplb/media_configuration_test.cc | 5 +- .../media_set_audio_write_duration_test.cc | 35 ++-- starboard/nplb/microphone_read_test.cc | 2 +- starboard/nplb/multiple_player_test.cc | 2 +- starboard/nplb/performance_helpers.h | 14 +- starboard/nplb/player_create_test.cc | 8 +- .../player_get_audio_configuration_test.cc | 2 +- starboard/nplb/player_test_fixture.cc | 49 +++--- starboard/nplb/player_test_fixture.h | 47 +++-- starboard/nplb/player_test_util.cc | 6 +- starboard/nplb/player_test_util.h | 6 +- starboard/nplb/player_write_sample_test.cc | 57 +++--- starboard/nplb/rwlock_test.cc | 15 +- starboard/nplb/semaphore_test.cc | 23 +-- starboard/nplb/socket_accept_test.cc | 1 - starboard/nplb/socket_helpers.cc | 58 +++---- starboard/nplb/socket_helpers.h | 45 ++--- .../nplb/socket_is_connected_and_idle_test.cc | 7 +- .../nplb/socket_join_multicast_group_test.cc | 8 +- starboard/nplb/socket_receive_from_test.cc | 1 - starboard/nplb/socket_send_to_test.cc | 12 +- starboard/nplb/socket_set_options_test.cc | 6 +- starboard/nplb/socket_waiter_wait_test.cc | 1 - .../nplb/socket_waiter_wait_timed_test.cc | 1 - starboard/nplb/socket_waiter_wake_up_test.cc | 5 +- starboard/nplb/socket_wrapper_test.cc | 1 - starboard/nplb/system_get_path_test.cc | 4 +- starboard/nplb/thread_helpers.h | 3 +- starboard/nplb/thread_join_test.cc | 2 +- starboard/nplb/thread_sampler_test.cc | 18 +- starboard/nplb/thread_sleep_test.cc | 17 +- starboard/nplb/thread_test.cc | 2 +- starboard/nplb/thread_yield_test.cc | 16 +- starboard/nplb/time_constants.h | 4 + starboard/nplb/time_get_monotonic_now_test.cc | 4 + starboard/nplb/time_get_now_test.cc | 4 + starboard/nplb/time_narrow_test.cc | 4 + starboard/nplb/time_test.cc | 80 +++++++++ starboard/nplb/time_zone_get_current_test.cc | 1 - starboard/nplb/time_zone_get_name_test.cc | 1 - starboard/nplb/vertical_video_test.cc | 9 +- starboard/player.h | 19 +- .../raspi/shared/application_dispmanx.cc | 4 +- starboard/raspi/shared/application_dispmanx.h | 2 +- starboard/raspi/shared/dispmanx_util.h | 2 +- .../shared/open_max/open_max_component.cc | 2 +- .../shared/open_max/open_max_component.h | 3 +- .../open_max_image_decode_component.cc | 5 +- .../raspi/shared/open_max/video_decoder.cc | 18 +- .../raspi/shared/open_max/video_decoder.h | 2 +- .../raspi/shared/video_renderer_sink_impl.cc | 6 +- starboard/shared/alsa/alsa_audio_sink_type.cc | 12 +- starboard/shared/ffmpeg/ffmpeg_demuxer.cc | 7 +- starboard/shared/ffmpeg/ffmpeg_demuxer.h | 6 +- .../shared/ffmpeg/ffmpeg_demuxer_impl.cc | 10 +- starboard/shared/ffmpeg/ffmpeg_demuxer_impl.h | 7 +- .../shared/ffmpeg/ffmpeg_video_decoder_impl.h | 2 +- starboard/shared/libaom/aom_video_decoder.cc | 2 +- starboard/shared/libaom/aom_video_decoder.h | 2 +- .../shared/libdav1d/dav1d_video_decoder.cc | 12 +- .../shared/libdav1d/dav1d_video_decoder.h | 4 +- .../shared/libde265/de265_video_decoder.cc | 2 +- .../shared/libde265/de265_video_decoder.h | 2 +- .../shared/libevent/socket_waiter_internal.cc | 23 +-- .../shared/libevent/socket_waiter_internal.h | 2 +- .../libevent/socket_waiter_wait_timed.cc | 2 +- starboard/shared/libvpx/vpx_video_decoder.cc | 2 +- starboard/shared/libvpx/vpx_video_decoder.h | 2 +- starboard/shared/linux/dev_input/dev_input.cc | 10 +- starboard/shared/linux/dev_input/dev_input.h | 9 +- .../shared/openh264/openh264_video_decoder.h | 2 +- starboard/shared/posix/impl/file_get_info.h | 9 +- .../shared/posix/impl/file_get_path_info.h | 9 +- starboard/shared/posix/impl/file_impl.h | 16 ++ .../shared/posix/socket_set_tcp_keep_alive.cc | 4 +- starboard/shared/posix/thread_sleep.cc | 6 +- .../shared/posix/time_get_monotonic_now.cc | 4 + starboard/shared/posix/time_get_now.cc | 4 + starboard/shared/posix/time_internal.h | 24 +-- .../pthread/condition_variable_wait_timed.cc | 12 +- .../shared/pulse/pulse_audio_sink_type.cc | 12 +- starboard/shared/signal/suspend_signals.cc | 2 +- starboard/shared/starboard/application.cc | 14 +- starboard/shared/starboard/application.h | 35 ++-- .../audio_sink/audio_sink_internal.cc | 2 +- .../audio_sink/audio_sink_internal.h | 2 +- .../audio_sink/stub_audio_sink_type.cc | 9 +- starboard/shared/starboard/event_schedule.cc | 2 +- ...r_garbage_collection_duration_threshold.cc | 4 +- .../shared/starboard/media/media_util.cc | 10 +- starboard/shared/starboard/media/media_util.h | 9 +- .../shared/starboard/media/media_util_test.cc | 12 +- starboard/shared/starboard/net_args.cc | 16 +- starboard/shared/starboard/net_args.h | 7 +- starboard/shared/starboard/net_log.cc | 17 +- starboard/shared/starboard/net_log.h | 6 +- .../player/decoded_audio_internal.cc | 10 +- .../starboard/player/decoded_audio_internal.h | 16 +- .../player/decoded_audio_test_internal.cc | 31 ++-- .../player/filter/audio_frame_discarder.cc | 4 +- .../player/filter/audio_frame_discarder.h | 7 +- .../filter/audio_renderer_internal_pcm.cc | 54 +++--- .../filter/audio_renderer_internal_pcm.h | 30 ++-- .../player/filter/audio_renderer_sink.h | 5 +- .../player/filter/audio_renderer_sink_impl.cc | 6 +- .../player/filter/audio_renderer_sink_impl.h | 6 +- .../player/filter/audio_time_stretcher.cc | 3 +- .../player/filter/cpu_video_frame.cc | 2 +- .../starboard/player/filter/cpu_video_frame.h | 4 +- .../filter_based_player_worker_handler.cc | 9 +- .../filter_based_player_worker_handler.h | 3 +- .../player/filter/media_time_provider.h | 10 +- .../player/filter/media_time_provider_impl.cc | 20 +-- .../player/filter/media_time_provider_impl.h | 20 +-- .../player/filter/mock_audio_renderer_sink.h | 2 +- .../player/filter/player_components.cc | 9 +- .../filter/punchout_video_renderer_sink.cc | 2 +- .../filter/punchout_video_renderer_sink.h | 5 +- .../player/filter/stub_audio_decoder.cc | 6 +- .../player/filter/stub_video_decoder.cc | 6 +- .../player/filter/stub_video_decoder.h | 6 +- .../testing/adaptive_audio_decoder_test.cc | 29 ++-- .../filter/testing/audio_decoder_test.cc | 37 ++-- .../testing/audio_frame_discarder_test.cc | 5 +- .../testing/audio_renderer_internal_test.cc | 76 ++++---- .../filter/testing/audio_resampler_test.cc | 2 +- .../testing/media_time_provider_impl_test.cc | 60 +++---- .../filter/testing/player_components_test.cc | 163 +++++++++--------- .../player/filter/testing/test_util.cc | 12 +- .../player/filter/testing/test_util.h | 7 +- .../filter/testing/video_decoder_test.cc | 8 +- .../testing/video_decoder_test_fixture.cc | 14 +- .../testing/video_decoder_test_fixture.h | 11 +- .../video_frame_rate_estimator_test.cc | 3 +- .../player/filter/tools/audio_dmp_player.cc | 4 +- .../player/filter/video_decoder_internal.h | 12 +- .../player/filter/video_frame_internal.h | 8 +- .../filter/video_frame_rate_estimator.cc | 4 +- .../filter/video_frame_rate_estimator.h | 7 +- .../player/filter/video_render_algorithm.h | 5 +- .../filter/video_render_algorithm_impl.cc | 25 +-- .../filter/video_render_algorithm_impl.h | 9 +- .../player/filter/video_renderer_internal.h | 4 +- .../filter/video_renderer_internal_impl.cc | 48 +++--- .../filter/video_renderer_internal_impl.h | 33 ++-- .../starboard/player/input_buffer_internal.h | 4 +- .../shared/starboard/player/job_queue.cc | 38 ++-- starboard/shared/starboard/player/job_queue.h | 26 +-- .../shared/starboard/player/job_queue_test.cc | 24 +-- .../shared/starboard/player/job_thread.h | 8 +- .../starboard/player/job_thread_test.cc | 29 ++-- .../player/player_get_audio_configuration.cc | 1 - .../starboard/player/player_internal.cc | 26 +-- .../shared/starboard/player/player_internal.h | 9 +- .../shared/starboard/player/player_seek.cc | 4 +- .../shared/starboard/player/player_worker.cc | 8 +- .../shared/starboard/player/player_worker.h | 13 +- .../starboard/player/video_dmp_common.h | 2 +- .../starboard/player/video_dmp_reader.cc | 18 +- .../starboard/player/video_dmp_reader.h | 14 +- .../starboard/player/video_dmp_writer.cc | 2 +- .../shared/starboard/queue_application.cc | 25 ++- .../shared/starboard/queue_application.h | 17 +- .../shared/starboard/socket/socket_tracker.cc | 27 +-- .../shared/starboard/socket/socket_tracker.h | 7 +- .../stub/condition_variable_wait_timed.cc | 2 +- ...r_garbage_collection_duration_threshold.cc | 2 +- .../stub/media_set_audio_write_duration.cc | 4 +- starboard/shared/stub/player_seek.cc | 4 +- .../shared/stub/socket_set_tcp_keep_alive.cc | 2 +- .../shared/stub/socket_waiter_wait_timed.cc | 2 +- starboard/shared/stub/thread_sleep.cc | 2 +- .../shared/stub/time_get_monotonic_now.cc | 4 + starboard/shared/stub/time_get_now.cc | 4 + .../uwp/analog_thumbstick_input_thread.cc | 2 +- starboard/shared/uwp/application_uwp.cc | 50 +++--- starboard/shared/uwp/application_uwp.h | 4 +- .../shared/uwp/audio_renderer_passthrough.cc | 40 ++--- .../shared/uwp/audio_renderer_passthrough.h | 23 ++- starboard/shared/uwp/decoder_utils.h | 5 +- .../shared/uwp/extended_resources_manager.cc | 11 +- starboard/shared/uwp/microphone_impl.cc | 20 +-- starboard/shared/uwp/wasapi_audio_sink.cc | 8 +- starboard/shared/uwp/wasapi_audio_sink.h | 1 - starboard/shared/uwp/watchdog_log.cc | 4 +- starboard/shared/uwp/window_internal.h | 1 - .../shared/widevine/drm_system_widevine.cc | 9 +- .../shared/widevine/drm_system_widevine.h | 2 +- starboard/shared/widevine/widevine_timer.cc | 3 +- starboard/shared/win32/application_win32.cc | 4 +- starboard/shared/win32/application_win32.h | 16 +- .../shared/win32/audio_decoder_thread.cc | 2 +- starboard/shared/win32/audio_sink.cc | 4 +- .../win32/condition_variable_wait_timed.cc | 6 +- starboard/shared/win32/decrypting_decoder.cc | 2 +- starboard/shared/win32/file_get_info.cc | 9 +- starboard/shared/win32/file_get_path_info.cc | 8 +- starboard/shared/win32/media_common.cc | 6 +- starboard/shared/win32/media_common.h | 4 +- .../shared/win32/socket_set_tcp_keep_alive.cc | 2 +- .../shared/win32/socket_waiter_internal.cc | 13 +- .../shared/win32/socket_waiter_internal.h | 2 +- .../shared/win32/socket_waiter_wait_timed.cc | 2 +- starboard/shared/win32/starboard_main.cc | 6 +- starboard/shared/win32/thread_sleep.cc | 6 +- .../shared/win32/time_get_monotonic_now.cc | 4 + starboard/shared/win32/time_get_now.cc | 4 + starboard/shared/win32/time_utils.h | 19 +- starboard/shared/win32/video_decoder.cc | 11 +- starboard/shared/win32/video_decoder.h | 6 +- starboard/shared/win32/win32_audio_decoder.cc | 7 +- starboard/shared/win32/window_internal.h | 1 - starboard/shared/x11/application_x11.cc | 6 +- starboard/shared/x11/application_x11.h | 2 +- starboard/socket.h | 13 +- starboard/socket_waiter.h | 11 +- starboard/stub/application_stub.cc | 2 +- starboard/stub/application_stub.h | 2 +- starboard/thread.h | 3 +- starboard/time.h | 12 +- starboard/user.h | 1 - .../xb1/shared/gpu_base_video_decoder.cc | 9 +- starboard/xb1/shared/gpu_base_video_decoder.h | 6 +- starboard/xb1/shared/video_frame_impl.h | 2 +- .../src/base/platform/platform-starboard.cc | 1 - third_party/v8/src/base/platform/time.cc | 1 - 301 files changed, 1659 insertions(+), 1605 deletions(-) create mode 100644 starboard/nplb/time_test.cc diff --git a/base/time/time_now_starboard.cc b/base/time/time_now_starboard.cc index e7dfbafd5182..8332e5bf4683 100644 --- a/base/time/time_now_starboard.cc +++ b/base/time/time_now_starboard.cc @@ -22,7 +22,6 @@ #include "starboard/client_porting/poem/eztime_poem.h" #include "starboard/common/log.h" #include "starboard/common/time.h" -#include "starboard/time.h" #include "starboard/types.h" namespace base { diff --git a/base/time/time_starboard.cc b/base/time/time_starboard.cc index c7067c24100b..62b2f4e3a694 100644 --- a/base/time/time_starboard.cc +++ b/base/time/time_starboard.cc @@ -16,7 +16,6 @@ #include "base/logging.h" #include "starboard/client_porting/eztime/eztime.h" -#include "starboard/time.h" namespace base { diff --git a/components/update_client/unzip/unzip_impl_cobalt.cc b/components/update_client/unzip/unzip_impl_cobalt.cc index 9b7b82bec7c9..9a4bfe35f8e7 100644 --- a/components/update_client/unzip/unzip_impl_cobalt.cc +++ b/components/update_client/unzip/unzip_impl_cobalt.cc @@ -9,7 +9,6 @@ #include "base/callback.h" #include "base/files/file_path.h" -#include "starboard/time.h" #include "third_party/zlib/google/zip.h" namespace update_client { diff --git a/starboard/android/apk/app/src/main/java/dev/cobalt/coat/StarboardBridge.java b/starboard/android/apk/app/src/main/java/dev/cobalt/coat/StarboardBridge.java index 5d6e8f9a4432..36907c1778bc 100644 --- a/starboard/android/apk/app/src/main/java/dev/cobalt/coat/StarboardBridge.java +++ b/starboard/android/apk/app/src/main/java/dev/cobalt/coat/StarboardBridge.java @@ -151,7 +151,7 @@ public StarboardBridge( private native boolean nativeInitialize(); - private native long nativeSbTimeGetMonotonicNow(); + private native long nativeCurrentMonotonicTime(); protected void onActivityStart(Activity activity, KeyboardEditor keyboardEditor) { activityHolder.set(activity); @@ -800,7 +800,7 @@ protected long getAppStartTimestamp() { Activity activity = activityHolder.get(); if (activity instanceof CobaltActivity) { long javaStartTimestamp = ((CobaltActivity) activity).getAppStartTimestamp(); - long cppTimestamp = nativeSbTimeGetMonotonicNow(); + long cppTimestamp = nativeCurrentMonotonicTime(); long javaStopTimestamp = System.nanoTime(); return cppTimestamp - (javaStartTimestamp - javaStopTimestamp) / timeNanosecondsPerMicrosecond; diff --git a/starboard/android/shared/android_media_session_client.cc b/starboard/android/shared/android_media_session_client.cc index 22ade7d6e521..ddea11679f16 100644 --- a/starboard/android/shared/android_media_session_client.cc +++ b/starboard/android/shared/android_media_session_client.cc @@ -225,15 +225,15 @@ void OnMediaSessionStateChanged( } jlong durationInMilliseconds; - if (session_state.duration == kSbTimeMax) { + if (session_state.duration == kSbInt64Max) { // Set duration to negative if duration is unknown or infinite, as with live // playback. // https://developer.android.com/reference/android/support/v4/media/MediaMetadataCompat#METADATA_KEY_DURATION durationInMilliseconds = -1; } else { - // SbTime is measured in microseconds while Android MediaSession expects - // duration in milliseconds. - durationInMilliseconds = session_state.duration / kSbTimeMillisecond; + // Starboard time is measured in microseconds while Android MediaSession + // expects duration in milliseconds. + durationInMilliseconds = session_state.duration / 1000; } env->CallStarboardVoidMethodOrAbort( @@ -241,7 +241,7 @@ void OnMediaSessionStateChanged( "(IJJFLjava/lang/String;Ljava/lang/String;Ljava/lang/String;" "[Ldev/cobalt/media/MediaImage;J)V", playback_state, playback_state_actions, - session_state.current_playback_position / kSbTimeMillisecond, + session_state.current_playback_position / 1000, static_cast(session_state.actual_playback_rate), j_title.Get(), j_artist.Get(), j_album.Get(), j_artwork.Get(), durationInMilliseconds); } diff --git a/starboard/android/shared/application_android.cc b/starboard/android/shared/application_android.cc index ea550644cd1b..eddfb6da240d 100644 --- a/starboard/android/shared/application_android.cc +++ b/starboard/android/shared/application_android.cc @@ -33,6 +33,7 @@ #include "starboard/common/log.h" #include "starboard/common/mutex.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/event.h" #include "starboard/key.h" #include "starboard/shared/starboard/audio_sink/audio_sink_internal.h" @@ -206,14 +207,14 @@ bool ApplicationAndroid::DestroyWindow(SbWindow window) { return true; } -Event* ApplicationAndroid::WaitForSystemEventWithTimeout(SbTime time) { +Event* ApplicationAndroid::WaitForSystemEventWithTimeout(int64_t time) { // Limit the polling time in case some non-system event is injected. const int kMaxPollingTimeMillisecond = 10; // Convert from microseconds to milliseconds, taking the ceiling value. // If we take the floor, or round, then we end up busy looping every time // the next event time is less than one millisecond. - int timeout_millis = (time + kSbTimeMillisecond - 1) / kSbTimeMillisecond; + int timeout_millis = (time + 1000 - 1) / 1000; int looper_events; int ident = ALooper_pollAll( std::min(std::max(timeout_millis, 0), kMaxPollingTimeMillisecond), NULL, @@ -371,7 +372,7 @@ void ApplicationAndroid::ProcessAndroidCommand() { free(static_cast(deep_link)); } else { SB_LOG(INFO) << "ApplicationAndroid Inject: kSbEventTypeLink"; - Inject(new Event(kSbEventTypeLink, SbTimeGetMonotonicNow(), deep_link, + Inject(new Event(kSbEventTypeLink, CurrentMonotonicTime(), deep_link, free)); } } @@ -667,7 +668,7 @@ void ApplicationAndroid::OsNetworkStatusChange(bool became_online) { } } -SbTimeMonotonic ApplicationAndroid::GetAppStartTimestamp() { +int64_t ApplicationAndroid::GetAppStartTimestamp() { JniEnvExt* env = JniEnvExt::Get(); jlong app_start_timestamp = env->CallStarboardLongMethodOrAbort("getAppStartTimestamp", "()J"); @@ -675,11 +676,11 @@ SbTimeMonotonic ApplicationAndroid::GetAppStartTimestamp() { } extern "C" SB_EXPORT_PLATFORM jlong -Java_dev_cobalt_coat_StarboardBridge_nativeSbTimeGetMonotonicNow( +Java_dev_cobalt_coat_StarboardBridge_nativeCurrentMonotonicTime( JNIEnv* env, jobject jcaller, jboolean online) { - return SbTimeGetMonotonicNow(); + return CurrentMonotonicTime(); } void ApplicationAndroid::SendDateTimeConfigurationChangedEvent() { diff --git a/starboard/android/shared/application_android.h b/starboard/android/shared/application_android.h index bca3b1f47da2..e25cf215e04b 100644 --- a/starboard/android/shared/application_android.h +++ b/starboard/android/shared/application_android.h @@ -103,7 +103,7 @@ class ApplicationAndroid void SbWindowSendInputEvent(const char* input_text, bool is_composing); void SendLowMemoryEvent(); void OsNetworkStatusChange(bool became_online); - SbTimeMonotonic GetAppStartTimestamp(); + int64_t GetAppStartTimestamp(); // microseconds void SendDateTimeConfigurationChangedEvent(); @@ -129,7 +129,7 @@ class ApplicationAndroid // --- QueueApplication overrides --- bool MayHaveSystemEvents() override { return handle_system_events_; } - Event* WaitForSystemEventWithTimeout(SbTime time) override; + Event* WaitForSystemEventWithTimeout(int64_t time) override; void WakeSystemEventWait() override; private: diff --git a/starboard/android/shared/audio_renderer_passthrough.cc b/starboard/android/shared/audio_renderer_passthrough.cc index 1a2f1b8aa1ba..0391ef7e3d18 100644 --- a/starboard/android/shared/audio_renderer_passthrough.cc +++ b/starboard/android/shared/audio_renderer_passthrough.cc @@ -21,6 +21,7 @@ #include "starboard/android/shared/jni_env_ext.h" #include "starboard/android/shared/jni_utils.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/memory.h" namespace starboard { @@ -32,7 +33,7 @@ namespace { // pushing data when there are enough decoded audio buffers. constexpr int kMaxDecodedAudios = 64; -constexpr SbTime kAudioTrackUpdateInternal = kSbTimeMillisecond * 5; +constexpr int64_t kAudioTrackUpdateInternal = 5'000; // 5ms constexpr int kPreferredBufferSizeInBytes = 16 * 1024; // TODO: Enable passthrough with tunnel mode. @@ -247,7 +248,7 @@ void AudioRendererPassthrough::SetPlaybackRate(double playback_rate) { playback_rate_ = playback_rate; } -void AudioRendererPassthrough::Seek(SbTime seek_to_time) { +void AudioRendererPassthrough::Seek(int64_t seek_to_time) { SB_DCHECK(BelongsToCurrentThread()); SB_LOG(INFO) << "Seek to " << seek_to_time; @@ -292,10 +293,10 @@ void AudioRendererPassthrough::Seek(SbTime seek_to_time) { } // This function can be called from *any* threads. -SbTime AudioRendererPassthrough::GetCurrentMediaTime(bool* is_playing, - bool* is_eos_played, - bool* is_underflow, - double* playback_rate) { +int64_t AudioRendererPassthrough::GetCurrentMediaTime(bool* is_playing, + bool* is_eos_played, + bool* is_underflow, + double* playback_rate) { SB_DCHECK(is_playing); SB_DCHECK(is_eos_played); SB_DCHECK(is_underflow); @@ -311,33 +312,33 @@ SbTime AudioRendererPassthrough::GetCurrentMediaTime(bool* is_playing, return seek_to_time_; } - SbTime audio_start_time; + int64_t audio_start_time; if (first_audio_timestamp_ > -1) { audio_start_time = first_audio_timestamp_; } else { audio_start_time = seek_to_time_; } - SbTime playback_time; + int64_t playback_time; if (stop_called_) { // When AudioTrackBridge::Stop() is called, the playback will continue until // all the frames written are played, as the AudioTrack is created in // MODE_STREAM. - auto now = SbTimeGetMonotonicNow(); + auto now = CurrentMonotonicTime(); SB_DCHECK(now >= stopped_at_); auto time_elapsed = now - stopped_at_; int64_t frames_played = - time_elapsed * audio_stream_info_.samples_per_second / kSbTimeSecond; + time_elapsed * audio_stream_info_.samples_per_second / 1'000'000LL; int64_t total_frames_played = frames_played + playback_head_position_when_stopped_; total_frames_played = std::min(total_frames_played, total_frames_written_); playback_time = - audio_start_time + total_frames_played * kSbTimeSecond / + audio_start_time + total_frames_played * 1'000'000LL / audio_stream_info_.samples_per_second; return std::max(playback_time, seek_to_time_); } - SbTime updated_at; + int64_t updated_at; auto playback_head_position = audio_track_bridge_->GetAudioTimestamp(&updated_at); if (playback_head_position <= 0) { @@ -348,7 +349,7 @@ SbTime AudioRendererPassthrough::GetCurrentMediaTime(bool* is_playing, // TODO: This may cause time regression, because the unadjusted time will be // returned on pause, after an adjusted time has been returned. - playback_time = audio_start_time + playback_head_position * kSbTimeSecond / + playback_time = audio_start_time + playback_head_position * 1'000'000LL / audio_stream_info_.samples_per_second; // When underlying AudioTrack is paused, we use returned playback time @@ -364,15 +365,15 @@ SbTime AudioRendererPassthrough::GetCurrentMediaTime(bool* is_playing, } // TODO: Cap this to the maximum frames written to the AudioTrack. - auto now = SbTimeGetMonotonicNow(); + auto now = CurrentMonotonicTime(); SB_LOG_IF(WARNING, now < updated_at) << "now (" << now << ") is not greater than updated_at (" << updated_at << ")."; - SB_LOG_IF(WARNING, now - updated_at > kSbTimeSecond) + SB_LOG_IF(WARNING, now - updated_at > 1'000'000LL) << "Elapsed time (" << now - updated_at << ") is greater than 1s. (playback_time " << playback_time << ")"; - playback_time += std::max(now - updated_at, 0); + playback_time += std::max(now - updated_at, 0); return std::max(playback_time, seek_to_time_); } @@ -419,7 +420,7 @@ void AudioRendererPassthrough::CreateAudioTrackAndStartProcessing() { } void AudioRendererPassthrough::FlushAudioTrackAndStopProcessing( - SbTime seek_to_time) { + int64_t seek_to_time) { SB_DCHECK(audio_track_thread_); SB_DCHECK(audio_track_thread_->BelongsToCurrentThread()); @@ -573,9 +574,9 @@ void AudioRendererPassthrough::UpdateStatusAndWriteData( // EOS is handled on this thread instead of in GetCurrentMediaTime(), because // GetCurrentMediaTime() is not guaranteed to be called. if (stop_called_ && !end_of_stream_played_.load()) { - auto time_elapsed = SbTimeGetMonotonicNow() - stopped_at_; + auto time_elapsed = CurrentMonotonicTime() - stopped_at_; auto frames_played = - time_elapsed * audio_stream_info_.samples_per_second / kSbTimeSecond; + time_elapsed * audio_stream_info_.samples_per_second / 1'000'000LL; if (frames_played + playback_head_position_when_stopped_ >= total_frames_written_on_audio_track_thread_) { end_of_stream_played_.store(true); diff --git a/starboard/android/shared/audio_renderer_passthrough.h b/starboard/android/shared/audio_renderer_passthrough.h index 28b8370bf462..a17c116a592a 100644 --- a/starboard/android/shared/audio_renderer_passthrough.h +++ b/starboard/android/shared/audio_renderer_passthrough.h @@ -36,7 +36,6 @@ #include "starboard/shared/starboard/player/input_buffer_internal.h" #include "starboard/shared/starboard/player/job_queue.h" #include "starboard/shared/starboard/player/job_thread.h" -#include "starboard/time.h" namespace starboard { namespace android { @@ -76,11 +75,11 @@ class AudioRendererPassthrough void Play() override; void Pause() override; void SetPlaybackRate(double playback_rate) override; - void Seek(SbTime seek_to_time) override; - SbTime GetCurrentMediaTime(bool* is_playing, - bool* is_eos_played, - bool* is_underflow, - double* playback_rate) override; + void Seek(int64_t seek_to_time) override; + int64_t GetCurrentMediaTime(bool* is_playing, + bool* is_eos_played, + bool* is_underflow, + double* playback_rate) override; private: typedef ::starboard::shared::starboard::player::DecodedAudio DecodedAudio; @@ -96,7 +95,7 @@ class AudioRendererPassthrough }; void CreateAudioTrackAndStartProcessing(); - void FlushAudioTrackAndStopProcessing(SbTime seek_to_time); + void FlushAudioTrackAndStopProcessing(int64_t seek_to_time); void UpdateStatusAndWriteData(const AudioTrackState previous_state); void OnDecoderConsumed(); void OnDecoderOutput(); @@ -126,9 +125,9 @@ class AudioRendererPassthrough bool stop_called_ = false; int64_t total_frames_written_ = 0; int64_t playback_head_position_when_stopped_ = 0; - SbTimeMonotonic stopped_at_ = 0; - SbTime seek_to_time_ = 0; - SbTime first_audio_timestamp_ = -1; + int64_t stopped_at_ = 0; // microseconds + int64_t seek_to_time_ = 0; // microseconds + int64_t first_audio_timestamp_ = -1; // microseconds double volume_ = 1.0; bool paused_ = true; double playback_rate_ = 1.0; diff --git a/starboard/android/shared/audio_sink_min_required_frames_tester.cc b/starboard/android/shared/audio_sink_min_required_frames_tester.cc index a2549090e2e9..4ad10fcc92d4 100644 --- a/starboard/android/shared/audio_sink_min_required_frames_tester.cc +++ b/starboard/android/shared/audio_sink_min_required_frames_tester.cc @@ -129,7 +129,7 @@ void MinRequiredFramesTester::TesterThreadFunc() { &MinRequiredFramesTester::ErrorFunc, 0, -1, false, this); { ScopedLock scoped_lock(mutex_); - wait_timeout = !condition_variable_.WaitTimed(kSbTimeSecond * 5); + wait_timeout = !condition_variable_.WaitTimed(5'000'000); } // Get start threshold before release the audio sink. @@ -191,7 +191,7 @@ void MinRequiredFramesTester::UpdateSourceStatusFunc(int* frames_in_buffer, // static void MinRequiredFramesTester::ConsumeFramesFunc(int frames_consumed, - SbTime frames_consumed_at, + int64_t frames_consumed_at, void* context) { MinRequiredFramesTester* tester = static_cast(context); diff --git a/starboard/android/shared/audio_sink_min_required_frames_tester.h b/starboard/android/shared/audio_sink_min_required_frames_tester.h index 934bdb977fb3..446b78da9bba 100644 --- a/starboard/android/shared/audio_sink_min_required_frames_tester.h +++ b/starboard/android/shared/audio_sink_min_required_frames_tester.h @@ -84,7 +84,7 @@ class MinRequiredFramesTester { bool* is_eos_reached, void* context); static void ConsumeFramesFunc(int frames_consumed, - SbTime frames_consumed_at, + int64_t frames_consumed_at, void* context); static void ErrorFunc(bool capability_changed, const std::string& error_message, diff --git a/starboard/android/shared/audio_track_audio_sink_type.cc b/starboard/android/shared/audio_track_audio_sink_type.cc index dfdf7433f8af..e3781184ff0e 100644 --- a/starboard/android/shared/audio_track_audio_sink_type.cc +++ b/starboard/android/shared/audio_track_audio_sink_type.cc @@ -20,6 +20,7 @@ #include "starboard/android/shared/media_capabilities_cache.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/shared/starboard/media/media_util.h" #include "starboard/shared/starboard/player/filter/common.h" @@ -47,7 +48,7 @@ const int kMaxFramesPerRequest = 65536; // improves the accuracy of audio time, especially at the beginning of a // playback, as otherwise the audio time during the initial update may be too // large (non zero) and results in dropped video frames. -const SbTime kMaxDurationPerRequestInTunnelMode = 16 * kSbTimeMillisecond; +const int64_t kMaxDurationPerRequestInTunnelMode = 16'000; // 16ms const size_t kSilenceFramesPerAppend = 1024; @@ -65,8 +66,8 @@ void* IncrementPointerByBytes(void* pointer, size_t offset) { } int GetMaxFramesPerRequestForTunnelMode(int sampling_frequency_hz) { - auto max_frames = kMaxDurationPerRequestInTunnelMode * sampling_frequency_hz / - kSbTimeSecond; + auto max_frames = + kMaxDurationPerRequestInTunnelMode * sampling_frequency_hz / 1'000'000LL; return (max_frames + 15) / 16 * 16; // align to 16 } @@ -115,7 +116,7 @@ AudioTrackAudioSink::AudioTrackAudioSink( SbAudioSinkUpdateSourceStatusFunc update_source_status_func, ConsumeFramesFunc consume_frames_func, SbAudioSinkPrivate::ErrorFunc error_func, - SbTime start_time, + int64_t start_time, int tunnel_mode_audio_session_id, bool is_web_audio, void* context) @@ -202,13 +203,13 @@ void AudioTrackAudioSink::AudioThreadFunc() { SB_LOG(INFO) << "AudioTrackAudioSink thread started."; int accumulated_written_frames = 0; - SbTime last_playback_head_event_at = -1; - SbTime playback_head_not_changed_duration = 0; - SbTime last_written_succeeded_at = -1; + int64_t last_playback_head_event_at = -1; // microseconds + int64_t playback_head_not_changed_duration = 0; // microseconds + int64_t last_written_succeeded_at = -1; // microseconds while (!quit_) { int playback_head_position = 0; - SbTime frames_consumed_at = 0; + int64_t frames_consumed_at = 0; if (bridge_.GetAndResetHasAudioDeviceChanged(env)) { SB_LOG(INFO) << "Audio device changed, raising a capability changed " "error to restart playback."; @@ -225,14 +226,14 @@ void AudioTrackAudioSink::AudioThreadFunc() { std::max(playback_head_position, last_playback_head_position_); int frames_consumed = playback_head_position - last_playback_head_position_; - SbTime now = SbTimeGetMonotonicNow(); + int64_t now = CurrentMonotonicTime(); if (last_playback_head_event_at == -1) { last_playback_head_event_at = now; } if (last_playback_head_position_ == playback_head_position) { - SbTime elapsed = now - last_playback_head_event_at; - if (elapsed > 5 * kSbTimeSecond) { + int64_t elapsed = now - last_playback_head_event_at; + if (elapsed > 5'000'000LL) { playback_head_not_changed_duration += elapsed; last_playback_head_event_at = now; SB_LOG(INFO) << "last playback head position is " @@ -280,7 +281,7 @@ void AudioTrackAudioSink::AudioThreadFunc() { } if (!is_playing || frames_in_buffer == 0) { - SbThreadSleep(10 * kSbTimeMillisecond); + SbThreadSleep(10'000); continue; } @@ -314,19 +315,18 @@ void AudioTrackAudioSink::AudioThreadFunc() { GetBytesPerSample(sample_type_) * silence_frames_per_append); auto sync_time = start_time_ + accumulated_written_frames * - kSbTimeSecond / - sampling_frequency_hz_; + 1'000'000LL / sampling_frequency_hz_; // Not necessary to handle error of WriteData(), as the audio has // reached the end of stream. WriteData(env, silence_buffer.data(), silence_frames_per_append, sync_time); } - SbThreadSleep(10 * kSbTimeMillisecond); + SbThreadSleep(10'000); continue; } SB_DCHECK(expected_written_frames > 0); - auto sync_time = start_time_ + accumulated_written_frames * kSbTimeSecond / + auto sync_time = start_time_ + accumulated_written_frames * 1'000'000LL / sampling_frequency_hz_; SB_DCHECK(start_position + expected_written_frames <= frames_per_channel_) @@ -343,7 +343,7 @@ void AudioTrackAudioSink::AudioThreadFunc() { start_position * channels_ * GetBytesPerSample(sample_type_)), expected_written_frames, sync_time); - SbTime now = SbTimeGetMonotonicNow(); + int64_t now = CurrentMonotonicTime(); if (written_frames < 0) { if (written_frames == AudioTrackBridge::kAudioTrackErrorDeadObject) { @@ -363,18 +363,17 @@ void AudioTrackAudioSink::AudioThreadFunc() { bool written_fully = (written_frames == expected_written_frames); auto unplayed_frames_in_time = - frames_in_audio_track * kSbTimeSecond / sampling_frequency_hz_ - + frames_in_audio_track * 1'000'000LL / sampling_frequency_hz_ - (now - frames_consumed_at); // As long as there is enough data in the buffer, run the loop in lower // frequency to avoid taking too much CPU. Note that the threshold should // be big enough to account for the unstable playback head reported at the // beginning of the playback and during underrun. - if (playback_head_position > 0 && - unplayed_frames_in_time > 500 * kSbTimeMillisecond) { - SbThreadSleep(40 * kSbTimeMillisecond); + if (playback_head_position > 0 && unplayed_frames_in_time > 500'000) { + SbThreadSleep(40'000); } else if (!written_fully) { // Only sleep if the buffer is nearly full and the last write is partial. - SbThreadSleep(10 * kSbTimeMillisecond); + SbThreadSleep(10'000); } } @@ -384,7 +383,7 @@ void AudioTrackAudioSink::AudioThreadFunc() { int AudioTrackAudioSink::WriteData(JniEnvExt* env, const void* buffer, int expected_written_frames, - SbTime sync_time) { + int64_t sync_time) { int samples_written = 0; if (sample_type_ == kSbMediaAudioSampleTypeFloat32) { samples_written = @@ -455,7 +454,7 @@ SbAudioSink AudioTrackAudioSinkType::Create( SbAudioSinkPrivate::ConsumeFramesFunc consume_frames_func, SbAudioSinkPrivate::ErrorFunc error_func, void* context) { - const SbTime kStartTime = 0; + const int64_t kStartTime = 0; // Disable tunnel mode. const int kTunnelModeAudioSessionId = -1; const bool kIsWebAudio = true; @@ -475,7 +474,7 @@ SbAudioSink AudioTrackAudioSinkType::Create( SbAudioSinkUpdateSourceStatusFunc update_source_status_func, SbAudioSinkPrivate::ConsumeFramesFunc consume_frames_func, SbAudioSinkPrivate::ErrorFunc error_func, - SbTime start_media_time, + int64_t start_media_time, int tunnel_mode_audio_session_id, bool is_web_audio, void* context) { diff --git a/starboard/android/shared/audio_track_audio_sink_type.h b/starboard/android/shared/audio_track_audio_sink_type.h index 6a9bc942f144..b1c47731263d 100644 --- a/starboard/android/shared/audio_track_audio_sink_type.h +++ b/starboard/android/shared/audio_track_audio_sink_type.h @@ -67,7 +67,7 @@ class AudioTrackAudioSinkType : public SbAudioSinkPrivate::Type { SbAudioSinkUpdateSourceStatusFunc update_source_status_func, SbAudioSinkPrivate::ConsumeFramesFunc consume_frames_func, SbAudioSinkPrivate::ErrorFunc error_func, - SbTime start_time, + int64_t start_time, int tunnel_mode_audio_session_id, bool is_web_audio, void* context); @@ -111,7 +111,7 @@ class AudioTrackAudioSink : public SbAudioSinkPrivate { SbAudioSinkUpdateSourceStatusFunc update_source_status_func, ConsumeFramesFunc consume_frames_func, SbAudioSinkPrivate::ErrorFunc error_func, - SbTime start_media_time, + int64_t start_media_time, int tunnel_mode_audio_session_id, bool is_web_audio, void* context); @@ -129,7 +129,10 @@ class AudioTrackAudioSink : public SbAudioSinkPrivate { static void* ThreadEntryPoint(void* context); void AudioThreadFunc(); - int WriteData(JniEnvExt* env, const void* buffer, int size, SbTime sync_time); + int WriteData(JniEnvExt* env, + const void* buffer, + int size, + int64_t sync_time); void ReportError(bool capability_changed, const std::string& error_message); @@ -142,7 +145,7 @@ class AudioTrackAudioSink : public SbAudioSinkPrivate { const SbAudioSinkUpdateSourceStatusFunc update_source_status_func_; const ConsumeFramesFunc consume_frames_func_; const SbAudioSinkPrivate::ErrorFunc error_func_; - const SbTime start_time_; + const int64_t start_time_; // microseconds const int tunnel_mode_audio_session_id_; const int max_frames_per_request_; void* const context_; diff --git a/starboard/android/shared/audio_track_bridge.cc b/starboard/android/shared/audio_track_bridge.cc index e518f745d83d..ae0e82261d8d 100644 --- a/starboard/android/shared/audio_track_bridge.cc +++ b/starboard/android/shared/audio_track_bridge.cc @@ -191,7 +191,7 @@ int AudioTrackBridge::WriteSample(const float* samples, int AudioTrackBridge::WriteSample(const uint16_t* samples, int num_of_samples, - SbTime sync_time, + int64_t sync_time, JniEnvExt* env /*= JniEnvExt::Get()*/) { SB_DCHECK(env); SB_DCHECK(is_valid()); @@ -215,7 +215,7 @@ int AudioTrackBridge::WriteSample(const uint16_t* samples, int AudioTrackBridge::WriteSample(const uint8_t* samples, int num_of_samples, - SbTime sync_time, + int64_t sync_time, JniEnvExt* env /*= JniEnvExt::Get()*/) { SB_DCHECK(env); SB_DCHECK(is_valid()); @@ -250,7 +250,7 @@ void AudioTrackBridge::SetVolume(double volume, } int64_t AudioTrackBridge::GetAudioTimestamp( - SbTime* updated_at, + int64_t* updated_at, JniEnvExt* env /*= JniEnvExt::Get()*/) { SB_DCHECK(env); SB_DCHECK(is_valid()); @@ -261,7 +261,7 @@ int64_t AudioTrackBridge::GetAudioTimestamp( if (updated_at) { *updated_at = env->GetLongFieldOrAbort(j_audio_timestamp.Get(), "nanoTime", "J") / - kSbTimeNanosecondsPerMicrosecond; + 1000; } return env->GetLongFieldOrAbort(j_audio_timestamp.Get(), "framePosition", "J"); diff --git a/starboard/android/shared/audio_track_bridge.h b/starboard/android/shared/audio_track_bridge.h index 5d7aeeb8fcd8..70f4bd5eda41 100644 --- a/starboard/android/shared/audio_track_bridge.h +++ b/starboard/android/shared/audio_track_bridge.h @@ -20,7 +20,6 @@ #include "starboard/android/shared/jni_env_ext.h" #include "starboard/common/optional.h" #include "starboard/media.h" -#include "starboard/time.h" #include "starboard/types.h" namespace starboard { @@ -66,21 +65,21 @@ class AudioTrackBridge { JniEnvExt* env = JniEnvExt::Get()); int WriteSample(const uint16_t* samples, int num_of_samples, - SbTime sync_time, + int64_t sync_time, JniEnvExt* env = JniEnvExt::Get()); // This is used by passthrough, it treats samples as if they are in bytes. // Returns zero or the positive number of samples written, or a negative error // code. int WriteSample(const uint8_t* buffer, int num_of_samples, - SbTime sync_time, + int64_t sync_time, JniEnvExt* env = JniEnvExt::Get()); void SetVolume(double volume, JniEnvExt* env = JniEnvExt::Get()); // |updated_at| contains the timestamp when the audio timstamp is updated on // return. It can be nullptr. - int64_t GetAudioTimestamp(SbTime* updated_at, + int64_t GetAudioTimestamp(int64_t* updated_at, JniEnvExt* env = JniEnvExt::Get()); bool GetAndResetHasAudioDeviceChanged(JniEnvExt* env = JniEnvExt::Get()); int GetUnderrunCount(JniEnvExt* env = JniEnvExt::Get()); diff --git a/starboard/android/shared/log_internal.cc b/starboard/android/shared/log_internal.cc index 555a23491306..fba0865b7135 100644 --- a/starboard/android/shared/log_internal.cc +++ b/starboard/android/shared/log_internal.cc @@ -21,7 +21,7 @@ namespace { const char kLogSleepTimeSwitch[] = "android_log_sleep_time"; -SbTime g_log_sleep_time = 0; +int64_t g_log_sleep_time = 0; // microseconds } // namespace namespace starboard { @@ -36,7 +36,7 @@ void LogInit(const starboard::shared::starboard::CommandLine& command_line) { } } -SbTime GetLogSleepTime() { +int64_t GetLogSleepTime() { return g_log_sleep_time; } diff --git a/starboard/android/shared/log_internal.h b/starboard/android/shared/log_internal.h index d3af63eb19f5..3da69eae8813 100644 --- a/starboard/android/shared/log_internal.h +++ b/starboard/android/shared/log_internal.h @@ -19,14 +19,13 @@ #define STARBOARD_ANDROID_SHARED_LOG_INTERNAL_H_ #include "starboard/shared/starboard/command_line.h" -#include "starboard/time.h" namespace starboard { namespace android { namespace shared { void LogInit(const starboard::shared::starboard::CommandLine& command_line); -SbTime GetLogSleepTime(); +int64_t GetLogSleepTime(); // Returns microseconds } // namespace shared } // namespace android diff --git a/starboard/android/shared/media_codec_bridge.cc b/starboard/android/shared/media_codec_bridge.cc index 705ae1f4958a..a5b92e6ba977 100644 --- a/starboard/android/shared/media_codec_bridge.cc +++ b/starboard/android/shared/media_codec_bridge.cc @@ -515,7 +515,7 @@ void MediaCodecBridge::OnMediaCodecOutputFormatChanged() { handler_->OnMediaCodecOutputFormatChanged(); } -void MediaCodecBridge::OnMediaCodecFrameRendered(SbTime frame_timestamp) { +void MediaCodecBridge::OnMediaCodecFrameRendered(int64_t frame_timestamp) { handler_->OnMediaCodecFrameRendered(frame_timestamp); } diff --git a/starboard/android/shared/media_codec_bridge.h b/starboard/android/shared/media_codec_bridge.h index cbee93a60003..5c1e4598d2a9 100644 --- a/starboard/android/shared/media_codec_bridge.h +++ b/starboard/android/shared/media_codec_bridge.h @@ -138,7 +138,7 @@ class MediaCodecBridge { int size) = 0; virtual void OnMediaCodecOutputFormatChanged() = 0; // This is only called on video decoder when tunnel mode is enabled. - virtual void OnMediaCodecFrameRendered(SbTime frame_timestamp) = 0; + virtual void OnMediaCodecFrameRendered(int64_t frame_timestamp) = 0; protected: ~Handler() {} @@ -211,7 +211,7 @@ class MediaCodecBridge { int64_t presentation_time_us, int size); void OnMediaCodecOutputFormatChanged(); - void OnMediaCodecFrameRendered(SbTime frame_timestamp); + void OnMediaCodecFrameRendered(int64_t frame_timestamp); private: // |MediaCodecBridge|s must only be created through its factory methods. diff --git a/starboard/android/shared/media_decoder.cc b/starboard/android/shared/media_decoder.cc index 280d2fdeb4a3..26608686347b 100644 --- a/starboard/android/shared/media_decoder.cc +++ b/starboard/android/shared/media_decoder.cc @@ -36,7 +36,7 @@ const jint kNoSize = 0; const jint kNoBufferFlags = 0; // Delay to use after a retryable error has been encountered. -const SbTime kErrorRetryDelay = 50 * kSbTimeMillisecond; +const int64_t kErrorRetryDelay = 50'000; // 50ms const char* GetNameForMediaCodecStatus(jint status) { switch (status) { @@ -258,7 +258,7 @@ void MediaDecoder::DecoderThreadFunc() { bool can_process_input = pending_queue_input_buffer_task_ || (has_input && has_input_buffer); if (dequeue_output_results_.empty() && !can_process_input) { - if (!condition_variable_.WaitTimed(5 * kSbTimeSecond)) { + if (!condition_variable_.WaitTimed(5'000'000LL)) { SB_LOG_IF(ERROR, !stream_ended_.load()) << GetDecoderName(media_type_) << ": Wait() hits timeout."; } @@ -355,7 +355,7 @@ void MediaDecoder::DecoderThreadFunc() { can_process_input = !pending_tasks.empty() && !input_buffer_indices.empty(); if (!can_process_input && dequeue_output_results.empty()) { - condition_variable_.WaitTimed(kSbTimeMillisecond); + condition_variable_.WaitTimed(1000); } } } @@ -639,7 +639,7 @@ void MediaDecoder::OnMediaCodecOutputFormatChanged() { condition_variable_.Signal(); } -void MediaDecoder::OnMediaCodecFrameRendered(SbTime frame_timestamp) { +void MediaDecoder::OnMediaCodecFrameRendered(int64_t frame_timestamp) { SB_DCHECK(tunnel_mode_enabled_); frame_rendered_cb_(frame_timestamp); } diff --git a/starboard/android/shared/media_decoder.h b/starboard/android/shared/media_decoder.h index bfb94f494541..3b62e1de0d86 100644 --- a/starboard/android/shared/media_decoder.h +++ b/starboard/android/shared/media_decoder.h @@ -51,7 +51,7 @@ class MediaDecoder typedef ::starboard::shared::starboard::player::filter::ErrorCB ErrorCB; typedef ::starboard::shared::starboard::player::InputBuffer InputBuffer; typedef ::starboard::shared::starboard::player::InputBuffers InputBuffers; - typedef std::function FrameRenderedCB; + typedef std::function FrameRenderedCB; // This class should be implemented by the users of MediaDecoder to receive // various notifications. Note that all such functions are called on the @@ -168,7 +168,7 @@ class MediaDecoder int64_t presentation_time_us, int size) override; void OnMediaCodecOutputFormatChanged() override; - void OnMediaCodecFrameRendered(SbTime frame_timestamp) override; + void OnMediaCodecFrameRendered(int64_t frame_timestamp) override; ::starboard::shared::starboard::ThreadChecker thread_checker_; diff --git a/starboard/android/shared/player_components_factory.h b/starboard/android/shared/player_components_factory.h index b6e3efc84b30..ce38ebadcff0 100644 --- a/starboard/android/shared/player_components_factory.h +++ b/starboard/android/shared/player_components_factory.h @@ -76,7 +76,7 @@ class AudioRendererSinkAndroid : public ::starboard::shared::starboard::player:: public: explicit AudioRendererSinkAndroid(int tunnel_mode_audio_session_id = -1) : AudioRendererSinkImpl( - [=](SbTime start_media_time, + [=](int64_t start_media_time, int channels, int sampling_frequency_hz, SbMediaAudioSampleType audio_sample_type, @@ -130,7 +130,7 @@ class AudioRendererSinkCallbackStub *is_playing = true; *is_eos_reached = false; } - void ConsumeFrames(int frames_consumed, SbTime frames_consumed_at) override { + void ConsumeFrames(int frames_consumed, int64_t frames_consumed_at) override { SB_DCHECK(frames_consumed == 0); } diff --git a/starboard/android/shared/video_decoder.cc b/starboard/android/shared/video_decoder.cc index dccc57b0f3d9..a6d9030b09fe 100644 --- a/starboard/android/shared/video_decoder.cc +++ b/starboard/android/shared/video_decoder.cc @@ -222,8 +222,8 @@ class VideoFrameImpl : public VideoFrame { const VideoFrameReleaseCallback release_callback_; }; -const SbTime kInitialPrerollTimeout = 250 * kSbTimeMillisecond; -const SbTime kNeedMoreInputCheckIntervalInTunnelMode = 50 * kSbTimeMillisecond; +const int64_t kInitialPrerollTimeout = 250'000; // 250ms +const int64_t kNeedMoreInputCheckIntervalInTunnelMode = 50'000; // 50ms const int kInitialPrerollFrameCount = 8; const int kNonInitialPrerollFrameCount = 1; @@ -301,7 +301,7 @@ class VideoRenderAlgorithmTunneled : public VideoRenderAlgorithmBase { void Render(MediaTimeProvider* media_time_provider, std::list>* frames, VideoRendererSink::DrawFrameCB draw_frame_cb) override {} - void Seek(SbTime seek_to_time) override { + void Seek(int64_t seek_to_time) override { frame_tracker_->Seek(seek_to_time); } int GetDroppedFrames() override { @@ -465,9 +465,9 @@ size_t VideoDecoder::GetPrerollFrameCount() const { return number_of_preroll_frames_; } -SbTime VideoDecoder::GetPrerollTimeout() const { +int64_t VideoDecoder::GetPrerollTimeout() const { if (input_buffer_written_ > 0 && first_buffer_timestamp_ != 0) { - return kSbTimeMax; + return kSbInt64Max; } return kInitialPrerollTimeout; } @@ -623,20 +623,20 @@ bool VideoDecoder::InitializeCodec(const VideoStreamInfo& video_stream_info, if (pending_input_buffers_.size() == 1) { video_fps_ = 30; } else { - SbTime first_timestamp = pending_input_buffers_[0]->timestamp(); - SbTime second_timestamp = pending_input_buffers_[1]->timestamp(); + int64_t first_timestamp = pending_input_buffers_[0]->timestamp(); + int64_t second_timestamp = pending_input_buffers_[1]->timestamp(); if (pending_input_buffers_.size() > 2) { second_timestamp = std::min(second_timestamp, pending_input_buffers_[2]->timestamp()); } - SbTime frame_duration = second_timestamp - first_timestamp; + int64_t frame_duration = second_timestamp - first_timestamp; if (frame_duration > 0) { // To avoid problems caused by deviation of fps calculation, we use the // nearest multiple of 5 to check codec capability. So, the fps like 61, // 62 will be capped to 60, and 24 will be increased to 25. const double kFpsMinDifference = 5; video_fps_ = - std::round(kSbTimeSecond / (second_timestamp - first_timestamp) / + std::round(1'000'000LL / (second_timestamp - first_timestamp) / kFpsMinDifference) * kFpsMinDifference; } else { @@ -814,7 +814,7 @@ void VideoDecoder::WriteInputBuffersInternal( } if (tunnel_mode_audio_session_id_ != -1) { - SbTime max_timestamp = input_buffers[0]->timestamp(); + int64_t max_timestamp = input_buffers[0]->timestamp(); for (const auto& input_buffer : input_buffers) { video_frame_tracker_->OnInputBuffer(input_buffer->timestamp()); max_timestamp = std::max(max_timestamp, input_buffer->timestamp()); @@ -1146,7 +1146,7 @@ void VideoDecoder::OnNewTextureAvailable() { has_new_texture_available_.store(true); } -void VideoDecoder::OnTunnelModeFrameRendered(SbTime frame_timestamp) { +void VideoDecoder::OnTunnelModeFrameRendered(int64_t frame_timestamp) { SB_DCHECK(tunnel_mode_audio_session_id_ != -1); tunnel_mode_frame_rendered_.store(true); @@ -1202,7 +1202,7 @@ void VideoDecoder::OnSurfaceDestroyed() { // Wait until codec is stopped. ScopedLock lock(surface_destroy_mutex_); Schedule(std::bind(&VideoDecoder::OnSurfaceDestroyed, this)); - surface_condition_variable_.WaitTimed(kSbTimeSecond); + surface_condition_variable_.WaitTimed(1'000'000); return; } // When this function is called, the decoder no longer owns the surface. diff --git a/starboard/android/shared/video_decoder.h b/starboard/android/shared/video_decoder.h index 184265649992..606a7c38294a 100644 --- a/starboard/android/shared/video_decoder.h +++ b/starboard/android/shared/video_decoder.h @@ -79,7 +79,7 @@ class VideoDecoder void Initialize(const DecoderStatusCB& decoder_status_cb, const ErrorCB& error_cb) override; size_t GetPrerollFrameCount() const override; - SbTime GetPrerollTimeout() const override; + int64_t GetPrerollTimeout() const override; // As we hold output buffers received from MediaCodec, the max number of // cached frames depends on the max number of output buffers in MediaCodec, // which is device dependent. The media decoder may stall if we hold all @@ -115,7 +115,7 @@ class VideoDecoder void OnFlushing() override; void TryToSignalPrerollForTunnelMode(); - void OnTunnelModeFrameRendered(SbTime frame_timestamp); + void OnTunnelModeFrameRendered(int64_t frame_timestamp); void OnTunnelModePrerollTimeout(); void OnTunnelModeCheckForNeedMoreInput(); @@ -188,7 +188,7 @@ class VideoDecoder int input_buffer_written_ = 0; bool first_texture_received_ = false; bool end_of_stream_written_ = false; - volatile SbTime first_buffer_timestamp_; + volatile int64_t first_buffer_timestamp_; // microseconds atomic_bool has_new_texture_available_; // Use |owns_video_surface_| only on decoder thread, to avoid unnecessary diff --git a/starboard/android/shared/video_frame_tracker.cc b/starboard/android/shared/video_frame_tracker.cc index 3e3349f538e7..e35310e9d736 100644 --- a/starboard/android/shared/video_frame_tracker.cc +++ b/starboard/android/shared/video_frame_tracker.cc @@ -21,22 +21,21 @@ #include "starboard/common/log.h" #include "starboard/common/mutex.h" -#include "starboard/time.h" namespace starboard { namespace android { namespace shared { namespace { -const SbTime kMaxAllowedSkew = 5000; +const int64_t kMaxAllowedSkew = 5'000; // 5ms } // namespace -SbTime VideoFrameTracker::seek_to_time() const { +int64_t VideoFrameTracker::seek_to_time() const { return seek_to_time_; } -void VideoFrameTracker::OnInputBuffer(SbTime timestamp) { +void VideoFrameTracker::OnInputBuffer(int64_t timestamp) { SB_DCHECK(thread_checker_.CalledOnValidThread()); if (frames_to_be_rendered_.empty()) { @@ -72,7 +71,7 @@ void VideoFrameTracker::OnFrameRendered(int64_t frame_timestamp) { rendered_frames_on_decoder_thread_.push_back(frame_timestamp); } -void VideoFrameTracker::Seek(SbTime seek_to_time) { +void VideoFrameTracker::Seek(int64_t seek_to_time) { SB_DCHECK(thread_checker_.CalledOnValidThread()); // Ensure that all dropped frames before seeking are captured. diff --git a/starboard/android/shared/video_frame_tracker.h b/starboard/android/shared/video_frame_tracker.h index 8b88f5925392..964034aaa4e8 100644 --- a/starboard/android/shared/video_frame_tracker.h +++ b/starboard/android/shared/video_frame_tracker.h @@ -20,7 +20,6 @@ #include "starboard/common/mutex.h" #include "starboard/shared/starboard/thread_checker.h" -#include "starboard/time.h" namespace starboard { namespace android { @@ -31,13 +30,13 @@ class VideoFrameTracker { explicit VideoFrameTracker(int max_pending_frames_size) : max_pending_frames_size_(max_pending_frames_size) {} - SbTime seek_to_time() const; + int64_t seek_to_time() const; - void OnInputBuffer(SbTime timestamp); + void OnInputBuffer(int64_t timestamp); void OnFrameRendered(int64_t frame_timestamp); - void Seek(SbTime seek_to_time); + void Seek(int64_t seek_to_time); int UpdateAndGetDroppedFrames(); @@ -46,15 +45,15 @@ class VideoFrameTracker { ::starboard::shared::starboard::ThreadChecker thread_checker_; - std::list frames_to_be_rendered_; + std::list frames_to_be_rendered_; const int max_pending_frames_size_; int dropped_frames_ = 0; - SbTime seek_to_time_ = 0; + int64_t seek_to_time_ = 0; // microseconds Mutex rendered_frames_mutex_; - std::vector rendered_frames_on_tracker_thread_; - std::vector rendered_frames_on_decoder_thread_; + std::vector rendered_frames_on_tracker_thread_; // microseconds + std::vector rendered_frames_on_decoder_thread_; // microseconds }; } // namespace shared diff --git a/starboard/android/shared/video_frame_tracker_test.cc b/starboard/android/shared/video_frame_tracker_test.cc index 5e61b00d25fb..7e761da169d1 100644 --- a/starboard/android/shared/video_frame_tracker_test.cc +++ b/starboard/android/shared/video_frame_tracker_test.cc @@ -15,7 +15,6 @@ #include #include "starboard/android/shared/video_frame_tracker.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" @@ -114,7 +113,7 @@ TEST(VideoFrameTrackerTest, RenderQueueIsClearedOnSeek) { video_frame_tracker.OnFrameRendered(30000); // Frames 40000, 50000, 60000 were never rendered. - const SbTime kSeekToTime = 90000; + const int64_t kSeekToTime = 90'000; // 90ms video_frame_tracker.Seek(kSeekToTime); ASSERT_EQ(kSeekToTime, video_frame_tracker.seek_to_time()); diff --git a/starboard/android/shared/video_render_algorithm.cc b/starboard/android/shared/video_render_algorithm.cc index 5edf96fdc709..dcda95ec1453 100644 --- a/starboard/android/shared/video_render_algorithm.cc +++ b/starboard/android/shared/video_render_algorithm.cc @@ -26,8 +26,8 @@ namespace shared { namespace { -const SbTimeMonotonic kBufferTooLateThreshold = -32 * kSbTimeMillisecond; -const SbTimeMonotonic kBufferReadyThreshold = 50 * kSbTimeMillisecond; +const int64_t kBufferTooLateThreshold = -32'000; // -32ms +const int64_t kBufferReadyThreshold = 50'000; // 50ms jlong GetSystemNanoTime() { timespec now; @@ -63,7 +63,7 @@ void VideoRenderAlgorithm::Render( bool is_audio_eos_played; bool is_underflow; double playback_rate; - SbTime playback_time = media_time_provider->GetCurrentMediaTime( + int64_t playback_time = media_time_provider->GetCurrentMediaTime( &is_audio_playing, &is_audio_eos_played, &is_underflow, &playback_rate); if (!is_audio_playing) { break; @@ -93,15 +93,13 @@ void VideoRenderAlgorithm::Render( jlong early_us = frames->front()->timestamp() - playback_time; auto system_time_ns = GetSystemNanoTime(); - auto unadjusted_frame_release_time_ns = - system_time_ns + (early_us * kSbTimeNanosecondsPerMicrosecond); + auto unadjusted_frame_release_time_ns = system_time_ns + (early_us * 1000); auto adjusted_release_time_ns = video_frame_release_time_helper_.AdjustReleaseTime( frames->front()->timestamp(), unadjusted_frame_release_time_ns); - early_us = (adjusted_release_time_ns - system_time_ns) / - kSbTimeNanosecondsPerMicrosecond; + early_us = (adjusted_release_time_ns - system_time_ns) / 1000; if (early_us < kBufferTooLateThreshold) { frames->pop_front(); diff --git a/starboard/android/shared/video_render_algorithm.h b/starboard/android/shared/video_render_algorithm.h index 132e8714ab06..d75a1a6a28ec 100644 --- a/starboard/android/shared/video_render_algorithm.h +++ b/starboard/android/shared/video_render_algorithm.h @@ -33,7 +33,7 @@ class VideoRenderAlgorithm : public ::starboard::shared::starboard::player:: void Render(MediaTimeProvider* media_time_provider, std::list>* frames, VideoRendererSink::DrawFrameCB draw_frame_cb) override; - void Seek(SbTime seek_to_time) override {} + void Seek(int64_t seek_to_time) override {} int GetDroppedFrames() override { return dropped_frames_; } private: diff --git a/starboard/client_porting/eztime/eztime.cc b/starboard/client_porting/eztime/eztime.cc index 7e9950cb0309..b9319bbbc392 100644 --- a/starboard/client_porting/eztime/eztime.cc +++ b/starboard/client_porting/eztime/eztime.cc @@ -18,9 +18,9 @@ #include "starboard/client_porting/icu_init/icu_init.h" #include "starboard/common/log.h" +#include "starboard/common/time.h" #include "starboard/once.h" #include "starboard/system.h" -#include "starboard/time.h" #include "third_party/icu/source/common/unicode/udata.h" #include "third_party/icu/source/common/unicode/uloc.h" @@ -78,14 +78,15 @@ void Initialize() { // Converts from an SbTime to an ICU UDate (non-fractional milliseconds since // POSIX epoch, as a double). -SbTime UDateToSbTime(UDate udate) { - return SbTimeFromPosix(static_cast(udate * kSbTimeMillisecond)); +int64_t UDateToSbTime(UDate udate) { + return starboard::PosixTimeToWindowsTime( + static_cast(udate * 1000LL)); } // Converts from an ICU UDate to an SbTime. NOTE: This is LOSSY. -UDate SbTimeToUDate(SbTime sb_time) { - return static_cast( - SbTimeNarrow(SbTimeToPosix(sb_time), kSbTimeMillisecond)); +UDate SbTimeToUDate(int64_t sb_time) { + int64_t posix_time = sb_time - 11644473600000000ULL; + return static_cast(posix_time / 1000); } // Gets the cached TimeZone ID from |g_timezones| for the given EzTimeZone @@ -132,7 +133,7 @@ bool EzTimeValueExplode(const EzTimeValue* SB_RESTRICT value, return false; } - SbTime sb_time = EzTimeValueToSbTime(value); + int64_t sb_time = EzTimeValueToSbTime(value); UDate udate = SbTimeToUDate(sb_time); ucal_setMillis(calendar, udate, &status); out_exploded->tm_year = ucal_get(calendar, UCAL_YEAR, &status) - 1900; @@ -207,12 +208,14 @@ EzTimeValue EzTimeValueImplode(EzTimeExploded* SB_RESTRICT exploded, int EzTimeValueGetNow(EzTimeValue* out_tp, void* tzp) { SB_DCHECK(tzp == NULL); SB_DCHECK(out_tp != NULL); - *out_tp = EzTimeValueFromSbTime(SbTimeGetNow()); + *out_tp = EzTimeValueFromSbTime( + starboard::PosixTimeToWindowsTime(starboard::CurrentPosixTime())); return 0; } EzTimeT EzTimeTGetNow(EzTimeT* out_now) { - EzTimeT result = EzTimeTFromSbTime(SbTimeGetNow()); + EzTimeT result = EzTimeTFromSbTime( + starboard::PosixTimeToWindowsTime(starboard::CurrentPosixTime())); if (out_now) { *out_now = result; } diff --git a/starboard/client_porting/eztime/eztime.h b/starboard/client_porting/eztime/eztime.h index faed4b148ebb..1dacbb7ef7af 100644 --- a/starboard/client_porting/eztime/eztime.h +++ b/starboard/client_porting/eztime/eztime.h @@ -18,7 +18,6 @@ #if defined(STARBOARD) #include "starboard/common/log.h" -#include "starboard/time.h" #include "starboard/types.h" #ifdef __cplusplus @@ -111,29 +110,29 @@ typedef enum EzTimeZone { // --- Simple Conversion Functions -------------------------------------------- // Converts SbTime to EzTimeT. NOTE: This is LOSSY. -static SB_C_FORCE_INLINE EzTimeT EzTimeTFromSbTime(SbTime in_time) { - return SbTimeNarrow(SbTimeToPosix(in_time), kSbTimeSecond); +static SB_C_FORCE_INLINE EzTimeT EzTimeTFromSbTime(int64_t in_time) { + int64_t posix_time = in_time - 11644473600000000ULL; + return posix_time / 1000000; } // Converts EzTimeT to SbTime. -static SB_C_FORCE_INLINE SbTime EzTimeTToSbTime(EzTimeT in_time) { - return SbTimeFromPosix(in_time * kSbTimeSecond); +static SB_C_FORCE_INLINE int64_t EzTimeTToSbTime(EzTimeT in_time) { + int64_t posix_time = in_time * 1000000; + return posix_time + 11644473600000000ULL; } // Converts SbTime to EzTimeValue. -static SB_C_FORCE_INLINE EzTimeValue EzTimeValueFromSbTime(SbTime in_time) { +static SB_C_FORCE_INLINE EzTimeValue EzTimeValueFromSbTime(int64_t in_time) { EzTimeT sec = EzTimeTFromSbTime(in_time); - SbTime diff = in_time - EzTimeTToSbTime(sec); + int64_t diff = in_time - EzTimeTToSbTime(sec); SB_DCHECK(diff >= INT_MIN); SB_DCHECK(diff <= INT_MAX); - EzTimeValue value = {sec, (int)diff}; // Some compilers do not support - // returning the initializer list - // directly. + EzTimeValue value = {sec, (int)diff}; // NOLINT(readability/casting) return value; } // Converts EzTimeValue to SbTime. -static SB_C_FORCE_INLINE SbTime EzTimeValueToSbTime(const EzTimeValue* value) { +static SB_C_FORCE_INLINE int64_t EzTimeValueToSbTime(const EzTimeValue* value) { return EzTimeTToSbTime(value->tv_sec) + value->tv_usec; } diff --git a/starboard/client_porting/eztime/eztime_test.cc b/starboard/client_porting/eztime/eztime_test.cc index 457e7ea35d00..82441695ee9b 100644 --- a/starboard/client_porting/eztime/eztime_test.cc +++ b/starboard/client_porting/eztime/eztime_test.cc @@ -14,6 +14,7 @@ #include "starboard/client_porting/eztime/eztime.h" #include "starboard/client_porting/eztime/test_constants.h" +#include "starboard/common/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -22,7 +23,7 @@ namespace eztime { namespace { TEST(EzTimeTFromSbTime, IsTransitive) { - SbTime sb_time = EzTimeTToSbTime(kTestTimePositive); + int64_t sb_time = EzTimeTToSbTime(kTestTimePositive); EzTimeT ez_time = EzTimeTFromSbTime(sb_time); EXPECT_EQ(kTestTimePositive, ez_time); @@ -49,7 +50,7 @@ TEST(EzTimeTFromSbTime, IsTransitive) { TEST(EzTimeValueFromSbTime, IsTransitive) { EzTimeValue time_value = EzTimeTToEzTimeValue(kTestTimePositive); - SbTime sb_time = EzTimeValueToSbTime(&time_value); + int64_t sb_time = EzTimeValueToSbTime(&time_value); EzTimeValue time_value2 = EzTimeValueFromSbTime(sb_time); EXPECT_EQ(time_value.tv_sec, time_value2.tv_sec); EXPECT_EQ(time_value.tv_usec, time_value2.tv_usec); @@ -63,11 +64,11 @@ TEST(EzTimeValueFromSbTime, IsTransitive) { TEST(EzTimeTGetNowTest, IsKindOfSane) { EzTimeT ez_time = EzTimeTGetNow(NULL); - SbTime sb_time = SbTimeGetNow(); + int64_t sb_time = PosixTimeToWindowsTime(CurrentPosixTime()); // They should be within a second of each other. - EXPECT_GT(kSbTimeSecond, sb_time - EzTimeTToSbTime(ez_time)); - EXPECT_GT(kSbTimeSecond, EzTimeTToSbTime(ez_time) - sb_time); + EXPECT_GT(1'000'000LL, sb_time - EzTimeTToSbTime(ez_time)); + EXPECT_GT(1'000'000LL, EzTimeTToSbTime(ez_time) - sb_time); // Now should be after the time I wrote this test. EXPECT_LE(kTestTimeWritten, ez_time); @@ -84,11 +85,11 @@ TEST(EzTimeTGetNowTest, IsKindOfSane) { TEST(EzTimeValueGetNowTest, IsKindOfSane) { EzTimeValue time_value = {0}; EXPECT_EQ(0, EzTimeValueGetNow(&time_value, NULL)); - SbTime sb_time = SbTimeGetNow(); + int64_t sb_time = PosixTimeToWindowsTime(CurrentPosixTime()); // They should be within a second of each other. - EXPECT_GT(kSbTimeSecond, sb_time - EzTimeValueToSbTime(&time_value)); - EXPECT_GT(kSbTimeSecond, EzTimeValueToSbTime(&time_value) - sb_time); + EXPECT_GT(1'000'000LL, sb_time - EzTimeValueToSbTime(&time_value)); + EXPECT_GT(1'000'000LL, EzTimeValueToSbTime(&time_value) - sb_time); // Now should be after the time I wrote this test. EzTimeT ez_time = EzTimeTFromSbTime(EzTimeValueToSbTime(&time_value)); diff --git a/starboard/common/condition_variable.cc b/starboard/common/condition_variable.cc index 4d9f8ea0bdee..892c725ed16e 100644 --- a/starboard/common/condition_variable.cc +++ b/starboard/common/condition_variable.cc @@ -31,7 +31,7 @@ void ConditionVariable::Wait() const { mutex_->debugSetAcquired(); } -bool ConditionVariable::WaitTimed(SbTime duration) const { +bool ConditionVariable::WaitTimed(int64_t duration) const { mutex_->debugSetReleased(); bool was_signaled = SbConditionVariableIsSignaled( SbConditionVariableWaitTimed(&condition_, mutex_->mutex(), duration)); diff --git a/starboard/common/condition_variable.h b/starboard/common/condition_variable.h index 9070e3625ccc..d666ef6ead6d 100644 --- a/starboard/common/condition_variable.h +++ b/starboard/common/condition_variable.h @@ -22,7 +22,6 @@ #include "starboard/common/mutex.h" #include "starboard/condition_variable.h" -#include "starboard/time.h" #include "starboard/types.h" namespace starboard { @@ -39,8 +38,9 @@ class ConditionVariable { // Returns |true| if this condition variable was signaled. Otherwise |false| // means that the condition variable timed out. In either case the - // mutex has been re-acquired once this function returns. - bool WaitTimed(SbTime duration) const; + // mutex has been re-acquired once this function returns. The |duration| is + // microseconds. + bool WaitTimed(int64_t duration) const; void Broadcast() const; void Signal() const; diff --git a/starboard/common/experimental/concurrency_debug.cc b/starboard/common/experimental/concurrency_debug.cc index d9b705a4567d..a1adcf78dca0 100644 --- a/starboard/common/experimental/concurrency_debug.cc +++ b/starboard/common/experimental/concurrency_debug.cc @@ -23,7 +23,6 @@ #include "starboard/atomic.h" #include "starboard/common/log.h" #include "starboard/common/mutex.h" -#include "starboard/shared/posix/time_internal.h" #include "starboard/system.h" namespace starboard { diff --git a/starboard/common/log.cc b/starboard/common/log.cc index 02cf3adb0d98..f105a87e4893 100644 --- a/starboard/common/log.cc +++ b/starboard/common/log.cc @@ -24,7 +24,6 @@ #include "starboard/common/string.h" #include "starboard/system.h" #include "starboard/thread.h" -#include "starboard/time.h" namespace starboard { namespace logging { diff --git a/starboard/common/queue.h b/starboard/common/queue.h index 9ee93de820d8..303183a729d6 100644 --- a/starboard/common/queue.h +++ b/starboard/common/queue.h @@ -26,8 +26,8 @@ #include "starboard/common/condition_variable.h" #include "starboard/common/mutex.h" +#include "starboard/common/time.h" #include "starboard/export.h" -#include "starboard/time.h" #include "starboard/types.h" namespace starboard { @@ -76,19 +76,19 @@ class Queue { } // Gets the item at the front of the queue, blocking until there is such an - // item, or the given timeout duration expires, or the queue is woken up. If - // there are multiple waiters, this Queue guarantees that only one waiter will - // receive any given queue item. - T GetTimed(SbTime duration) { + // item, or the given timeout duration (in microseconds) expires, or the queue + // is woken up. If there are multiple waiters, this Queue guarantees that only + // one waiter will receive any given queue item. + T GetTimed(int64_t duration) { ScopedLock lock(mutex_); - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); while (queue_.empty()) { if (wake_) { wake_ = false; return T(); } - SbTimeMonotonic elapsed = SbTimeGetMonotonicNow() - start; + int64_t elapsed = CurrentMonotonicTime() - start; if (elapsed >= duration) { return T(); } diff --git a/starboard/common/recursive_mutex.cc b/starboard/common/recursive_mutex.cc index 6c79ecf84d96..7b44bd0d42eb 100644 --- a/starboard/common/recursive_mutex.cc +++ b/starboard/common/recursive_mutex.cc @@ -14,7 +14,6 @@ #include "starboard/common/recursive_mutex.h" #include "starboard/common/log.h" -#include "starboard/time.h" namespace starboard { diff --git a/starboard/common/semaphore.cc b/starboard/common/semaphore.cc index 6f3d9f365c2d..1215f97c185b 100644 --- a/starboard/common/semaphore.cc +++ b/starboard/common/semaphore.cc @@ -13,6 +13,7 @@ // limitations under the License. #include "starboard/common/semaphore.h" +#include "starboard/common/time.h" namespace starboard { @@ -46,14 +47,14 @@ bool Semaphore::TakeTry() { return true; } -bool Semaphore::TakeWait(SbTime wait_us) { +bool Semaphore::TakeWait(int64_t wait_us) { if (wait_us <= 0) { return TakeTry(); } - SbTime expire_time = SbTimeGetMonotonicNow() + wait_us; + int64_t expire_time = CurrentMonotonicTime() + wait_us; ScopedLock lock(mutex_); while (permits_ <= 0) { - SbTime remaining_wait_time = expire_time - SbTimeGetMonotonicNow(); + int64_t remaining_wait_time = expire_time - CurrentMonotonicTime(); if (remaining_wait_time <= 0) { return false; // Timed out. } diff --git a/starboard/common/semaphore.h b/starboard/common/semaphore.h index ce0f8000b42f..a712f450f6f6 100644 --- a/starboard/common/semaphore.h +++ b/starboard/common/semaphore.h @@ -18,7 +18,6 @@ #include "starboard/common/condition_variable.h" #include "starboard/common/mutex.h" #include "starboard/configuration.h" -#include "starboard/time.h" namespace starboard { @@ -43,9 +42,9 @@ class Semaphore { // is returned then the effects are the same as if Take() had been invoked. bool TakeTry(); - // Same as Take(), but will wait at most, wait_us microseconds. + // Same as Take(), but will wait at most |wait_us| microseconds. // Returns |false| if the semaphore timed out, |true| otherwise. - bool TakeWait(SbTime wait_us); + bool TakeWait(int64_t wait_us); private: Mutex mutex_; diff --git a/starboard/common/socket.cc b/starboard/common/socket.cc index ae861168357b..0e4c056c8fab 100644 --- a/starboard/common/socket.cc +++ b/starboard/common/socket.cc @@ -144,7 +144,7 @@ bool Socket::SetSendBufferSize(int32_t size) { return SbSocketSetSendBufferSize(socket_, size); } -bool Socket::SetTcpKeepAlive(bool value, SbTime period) { +bool Socket::SetTcpKeepAlive(bool value, int64_t period) { return SbSocketSetTcpKeepAlive(socket_, value, period); } diff --git a/starboard/common/socket.h b/starboard/common/socket.h index 8efaadaf22cb..d02d62318a97 100644 --- a/starboard/common/socket.h +++ b/starboard/common/socket.h @@ -68,7 +68,7 @@ class Socket { bool SetReuseAddress(bool value); bool SetReceiveBufferSize(int32_t size); bool SetSendBufferSize(int32_t size); - bool SetTcpKeepAlive(bool value, SbTime period); + bool SetTcpKeepAlive(bool value, int64_t period); // period in microseconds. bool SetTcpNoDelay(bool value); bool SetTcpWindowScaling(bool value); bool JoinMulticastGroup(const SbSocketAddress* address); diff --git a/starboard/common/thread.cc b/starboard/common/thread.cc index 44fdcb2d50b8..9d1e24de1444 100644 --- a/starboard/common/thread.cc +++ b/starboard/common/thread.cc @@ -64,15 +64,15 @@ void Thread::Start(const Options& options) { SB_DCHECK(d_->thread_ != kSbThreadInvalid); } -void Thread::Sleep(SbTime microseconds) { +void Thread::Sleep(int64_t microseconds) { SbThreadSleep(microseconds); } void Thread::SleepMilliseconds(int value) { - return Sleep(value * kSbTimeMillisecond); + return Sleep(static_cast(value) * 1000); } -bool Thread::WaitForJoin(SbTime timeout) { +bool Thread::WaitForJoin(int64_t timeout) { bool joined = d_->join_sema_.TakeWait(timeout); if (joined) { SB_DCHECK(d_->join_called_.load()); diff --git a/starboard/common/thread.h b/starboard/common/thread.h index c01b8172fcda..15316e9b66aa 100644 --- a/starboard/common/thread.h +++ b/starboard/common/thread.h @@ -23,7 +23,6 @@ #include "starboard/common/scoped_ptr.h" #include "starboard/configuration.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "starboard/types.h" namespace starboard { @@ -65,12 +64,12 @@ class Thread { protected: static void* ThreadEntryPoint(void* context); - static void Sleep(SbTime microseconds); + static void Sleep(int64_t microseconds); static void SleepMilliseconds(int value); // Waits at most |timeout| microseconds for Join() to be called. If // Join() was called then return |true|, else |false|. - bool WaitForJoin(SbTime timeout); + bool WaitForJoin(int64_t timeout); Semaphore* join_sema(); atomic_bool* joined_bool(); diff --git a/starboard/condition_variable.h b/starboard/condition_variable.h index dea98976931a..0fc7243c68b8 100644 --- a/starboard/condition_variable.h +++ b/starboard/condition_variable.h @@ -21,7 +21,6 @@ #include "starboard/export.h" #include "starboard/mutex.h" -#include "starboard/time.h" #include "starboard/types.h" #ifdef __cplusplus @@ -96,13 +95,13 @@ SbConditionVariableWait(SbConditionVariable* condition, SbMutex* mutex); // undefined if |mutex| is not held. // // |timeout_duration|: The maximum amount of time that function should wait -// for |condition|. If the |timeout_duration| value is less than or equal to -// zero, the function returns as quickly as possible with a +// for |condition|, in microseconds. If the |timeout_duration| value is less +// than or equal to zero, the function returns as quickly as possible with a // kSbConditionVariableTimedOut result. SB_EXPORT SbConditionVariableResult SbConditionVariableWaitTimed(SbConditionVariable* condition, SbMutex* mutex, - SbTime timeout_duration); + int64_t timeout_duration); // Broadcasts to all current waiters of |condition| to stop waiting. This // function wakes all of the threads waiting on |condition| while diff --git a/starboard/doc/style.md b/starboard/doc/style.md index 90364739b8b4..4bdbe7c4f209 100644 --- a/starboard/doc/style.md +++ b/starboard/doc/style.md @@ -120,9 +120,6 @@ the guidelines follow thusly as follows. casting the handle back and forth to the pointer type. * If a word in the name of a type is redundant with the module name, it is omitted. - * A monotonic time type in the Time module is `SbTimeMonotonic`, not - ~~`SbMonotonicTime`, `SbTimeMonotonicTime`, or - `SbTimeMonotonicSbTime`~~. ### Functions @@ -188,10 +185,8 @@ namespace at the starboard repository root. * After the `k`, all constants have `Sb`, the Starboard namespace. * `kSb` * After `kSb`, all constants then have the module name. - * `kSbTime` * `kSbFile` * After `kSb` comes the rest of the name of the constant. - * `kSbTimeMillisecond` * `kSbFileInvalid` * Enum entries are prefixed with the full name of the enum. * The enum `SbSystemDeviceType` contains entries like diff --git a/starboard/elf_loader/elf_loader.cc b/starboard/elf_loader/elf_loader.cc index f8af5f63d0b0..75ed38fb22c6 100644 --- a/starboard/elf_loader/elf_loader.cc +++ b/starboard/elf_loader/elf_loader.cc @@ -19,6 +19,7 @@ #include "starboard/atomic.h" #include "starboard/common/log.h" #include "starboard/common/paths.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/elf_loader/elf_loader_impl.h" #include "starboard/elf_loader/evergreen_config.h" @@ -78,12 +79,11 @@ bool ElfLoader::Load(const std::string& library_path, EvergreenConfig::Create(library_path_.c_str(), content_path_.c_str(), custom_get_extension); SB_LOG(INFO) << "evergreen_config: content_path=" << content_path_; - SbTime start_time = SbTimeGetMonotonicNow(); + int64_t start_time = CurrentMonotonicTime(); bool res = impl_->Load(library_path_.c_str(), use_compression, use_memory_mapped_file); - SbTime end_time = SbTimeGetMonotonicNow(); - SB_LOG(INFO) << "Loading took: " - << (end_time - start_time) / kSbTimeMillisecond << " ms"; + int64_t end_time = CurrentMonotonicTime(); + SB_LOG(INFO) << "Loading took: " << (end_time - start_time) / 1000 << " ms"; return res; } diff --git a/starboard/elf_loader/exported_symbols.cc b/starboard/elf_loader/exported_symbols.cc index c4a9740d8b84..16de7c54e948 100644 --- a/starboard/elf_loader/exported_symbols.cc +++ b/starboard/elf_loader/exported_symbols.cc @@ -371,12 +371,10 @@ ExportedSymbols::ExportedSymbols() { REGISTER_SYMBOL(SbThreadSetName); REGISTER_SYMBOL(SbThreadSleep); REGISTER_SYMBOL(SbThreadYield); - REGISTER_SYMBOL(SbTimeGetMonotonicNow); #if SB_API_VERSION < 16 + REGISTER_SYMBOL(SbTimeGetMonotonicNow); REGISTER_SYMBOL(SbTimeGetMonotonicThreadNow); -#endif // SB_API_VERSION < 16 REGISTER_SYMBOL(SbTimeGetNow); -#if SB_API_VERSION < 16 REGISTER_SYMBOL(SbTimeIsTimeThreadNowSupported); #endif // SB_API_VERSION < 16 REGISTER_SYMBOL(SbTimeZoneGetCurrent); diff --git a/starboard/event.h b/starboard/event.h index e71eb8d3b948..fcdd6511b2fd 100644 --- a/starboard/event.h +++ b/starboard/event.h @@ -92,7 +92,6 @@ #include "starboard/configuration.h" #include "starboard/export.h" -#include "starboard/time.h" #include "starboard/types.h" #include "starboard/window.h" @@ -302,7 +301,7 @@ typedef enum SbEventType { // Structure representing a Starboard event and its data. typedef struct SbEvent { SbEventType type; - SbTimeMonotonic timestamp; + int64_t timestamp; // Monotonic time in microseconds. void* data; } SbEvent; @@ -377,7 +376,7 @@ SB_IMPORT void SbEventHandle(const SbEvent* event); // possible. SB_EXPORT SbEventId SbEventSchedule(SbEventCallback callback, void* context, - SbTime delay); + int64_t delay); // Cancels the specified |event_id|. Note that this function is a no-op // if the event already fired. This function can be safely called from any diff --git a/starboard/extension/demuxer.h b/starboard/extension/demuxer.h index 6107e64303ab..ff77f7059f3e 100644 --- a/starboard/extension/demuxer.h +++ b/starboard/extension/demuxer.h @@ -22,8 +22,6 @@ #include #include -#include "starboard/time.h" - #ifdef __cplusplus extern "C" { #endif @@ -284,9 +282,9 @@ typedef struct CobaltExtensionDemuxerBuffer { // Number of elements in |side_data|. int64_t side_data_elements; // Playback time in microseconds. - SbTime pts; + int64_t pts; // Duration of this buffer in microseconds. - SbTime duration; + int64_t duration; // True if this buffer contains a keyframe. bool is_keyframe; // Signifies the end of the stream. If this is true, the other fields will be @@ -310,15 +308,16 @@ typedef struct CobaltExtensionDemuxer { // fail. CobaltExtensionDemuxerStatus (*Initialize)(void* user_data); - CobaltExtensionDemuxerStatus (*Seek)(SbTime seek_time, void* user_data); + CobaltExtensionDemuxerStatus (*Seek)(int64_t seek_time, void* user_data); - // Returns the starting time for the media file; it is always positive. - SbTime (*GetStartTime)(void* user_data); + // Returns the starting time -- in microseconds since Windows epoch -- for the + // media file; it is always positive. + int64_t (*GetStartTime)(void* user_data); // Returns the time -- in microseconds since Windows epoch -- represented by // presentation timestamp 0. If the timestamps are not associated with a time, // returns 0. - SbTime (*GetTimelineOffset)(void* user_data); + int64_t (*GetTimelineOffset)(void* user_data); // Calls |read_cb| with a buffer of type |type| and the user data provided by // |read_cb_user_data|. |read_cb| is a synchronous function, so the data @@ -346,7 +345,7 @@ typedef struct CobaltExtensionDemuxer { void* user_data); // Returns the duration, in microseconds. - SbTime (*GetDuration)(void* user_data); + int64_t (*GetDuration)(void* user_data); // Will be passed to all functions. void* user_data; diff --git a/starboard/extension/enhanced_audio.h b/starboard/extension/enhanced_audio.h index f352a24dd65b..72aaec2b3052 100644 --- a/starboard/extension/enhanced_audio.h +++ b/starboard/extension/enhanced_audio.h @@ -19,7 +19,6 @@ #include "starboard/drm.h" #include "starboard/media.h" #include "starboard/player.h" -#include "starboard/time.h" #include "starboard/types.h" #ifdef __cplusplus @@ -48,8 +47,8 @@ typedef struct CobaltExtensionEnhancedAudioMediaAudioStreamInfo { // comment of `SbMediaAudioSampleInfo` in `media.h` for more details. typedef struct CobaltExtensionEnhancedAudioMediaAudioSampleInfo { CobaltExtensionEnhancedAudioMediaAudioStreamInfo stream_info; - SbTime discarded_duration_from_front; - SbTime discarded_duration_from_back; + int64_t discarded_duration_from_front; // in microseconds. + int64_t discarded_duration_from_back; // in microseconds. } CobaltExtensionEnhancedAudioMediaAudioSampleInfo; // The structure has the same binary layout as `SbMediaVideoStreamInfo` in the @@ -82,7 +81,7 @@ typedef struct CobaltExtensionEnhancedAudioPlayerSampleInfo { SbMediaType type; const void* buffer; int buffer_size; - SbTime timestamp; + int64_t timestamp; // Microseconds since Windows epoch UTC. SbPlayerSampleSideData* side_data; int side_data_count; union { diff --git a/starboard/extension/media_session.h b/starboard/extension/media_session.h index 5dd937591f92..1d8dc016a1ba 100644 --- a/starboard/extension/media_session.h +++ b/starboard/extension/media_session.h @@ -16,7 +16,6 @@ #define STARBOARD_EXTENSION_MEDIA_SESSION_H_ #include "starboard/configuration.h" -#include "starboard/time.h" #ifdef __cplusplus extern "C" { @@ -84,12 +83,12 @@ typedef void (*CobaltExtensionMediaSessionInvokeActionCallback)( // valid within the scope of that function. Any data inside must be copied if it // will be referenced later. typedef struct CobaltExtensionMediaSessionState { - SbTimeMonotonic duration; + int64_t duration; // Monotonic time in microseconds. CobaltExtensionMediaSessionPlaybackState actual_playback_state; bool available_actions[kCobaltExtensionMediaSessionActionNumActions]; CobaltExtensionMediaMetadata* metadata; double actual_playback_rate; - SbTimeMonotonic current_playback_position; + int64_t current_playback_position; // Monotonic time in microseconds. bool has_position_state; } CobaltExtensionMediaSessionState; diff --git a/starboard/file.h b/starboard/file.h index f37b1a1d744b..dcb9ff4a07e9 100644 --- a/starboard/file.h +++ b/starboard/file.h @@ -20,7 +20,6 @@ #define STARBOARD_FILE_H_ #include "starboard/export.h" -#include "starboard/time.h" #include "starboard/types.h" #ifdef __cplusplus @@ -110,14 +109,14 @@ typedef struct SbFileInfo { // Whether the file corresponds to a symbolic link. bool is_symbolic_link; - // The last modified time of a file. - SbTime last_modified; + // The last modified time of a file - microseconds since Windows epoch UTC. + int64_t last_modified; - // The last accessed time of a file. - SbTime last_accessed; + // The last accessed time of a file - microseconds since Windows epoch UTC. + int64_t last_accessed; - // The creation time of a file. - SbTime creation_time; + // The creation time of a file - microseconds since Windows epoch UTC. + int64_t creation_time; } SbFileInfo; // Well-defined value for an invalid file handle. diff --git a/starboard/input.h b/starboard/input.h index d1c7625ec1da..735cf1a8b699 100644 --- a/starboard/input.h +++ b/starboard/input.h @@ -22,7 +22,6 @@ #include "starboard/configuration.h" #include "starboard/export.h" #include "starboard/key.h" -#include "starboard/time.h" #include "starboard/types.h" #include "starboard/window.h" diff --git a/starboard/linux/shared/player_components_factory.cc b/starboard/linux/shared/player_components_factory.cc index 922156981a43..529ac4a8d6e9 100644 --- a/starboard/linux/shared/player_components_factory.cc +++ b/starboard/linux/shared/player_components_factory.cc @@ -110,7 +110,7 @@ class PlayerComponentsFactory : public PlayerComponents::Factory { typedef ::starboard::shared::openh264::VideoDecoder Openh264VideoDecoderImpl; - const SbTime kVideoSinkRenderInterval = 10 * kSbTimeMillisecond; + const int64_t kVideoSinkRenderIntervalUsec = 10'000; SB_DCHECK(video_decoder); SB_DCHECK(video_render_algorithm); @@ -170,7 +170,7 @@ class PlayerComponentsFactory : public PlayerComponents::Factory { *video_renderer_sink = NULL; } else { *video_renderer_sink = new PunchoutVideoRendererSink( - creation_parameters.player(), kVideoSinkRenderInterval); + creation_parameters.player(), kVideoSinkRenderIntervalUsec); } } diff --git a/starboard/loader_app/drain_file.cc b/starboard/loader_app/drain_file.cc index c84d7ace36bc..f7609b60099c 100644 --- a/starboard/loader_app/drain_file.cc +++ b/starboard/loader_app/drain_file.cc @@ -22,6 +22,7 @@ #include "starboard/common/file.h" #include "starboard/common/log.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/directory.h" #include "starboard/string.h" @@ -30,8 +31,8 @@ extern "C" { #endif -const SbTime kDrainFileAgeUnit = kSbTimeSecond; -const SbTime kDrainFileMaximumAge = kSbTimeHour; +const int64_t kDrainFileAgeUnitUsec = 1'000'000; // 1 second +const int64_t kDrainFileMaximumAgeUsec = 1'000'000LL * 60 * 60; // 1 hour const char kDrainFilePrefix[] = "d_"; #ifdef __cplusplus @@ -53,7 +54,7 @@ std::string ExtractAppKey(const std::string& str) { return str.substr(begin, end - begin); } -SbTime ExtractTimestamp(const std::string& str) { +int64_t ExtractTimestamp(const std::string& str) { const size_t index = str.find_last_of('_') + 1; if ((index == std::string::npos) || (index == str.size() - 1)) @@ -61,12 +62,13 @@ SbTime ExtractTimestamp(const std::string& str) { const std::string timestamp = str.substr(index, str.size() - index); - return SbTime(strtoull(timestamp.c_str(), NULL, 10)) * kDrainFileAgeUnit; + return strtoull(timestamp.c_str(), NULL, 10) * kDrainFileAgeUnitUsec; } bool IsExpired(const std::string& filename) { - const SbTime timestamp = ExtractTimestamp(filename); - return timestamp + kDrainFileMaximumAge < SbTimeGetNow(); + const int64_t timestamp = ExtractTimestamp(filename); + return timestamp + kDrainFileMaximumAgeUsec < + PosixTimeToWindowsTime(CurrentPosixTime()); } std::vector FindAllWithPrefix(const std::string& dir, @@ -109,8 +111,8 @@ void Rank(const char* dir, char* app_key, size_t len) { // are equal. auto compare_filenames = [](const std::string& left, const std::string& right) -> bool { - const SbTime left_timestamp = ExtractTimestamp(left); - const SbTime right_timestamp = ExtractTimestamp(right); + const int64_t left_timestamp = ExtractTimestamp(left); + const int64_t right_timestamp = ExtractTimestamp(right); if (left_timestamp != right_timestamp) return left_timestamp < right_timestamp; @@ -152,7 +154,8 @@ bool TryDrain(const char* dir, const char* app_key) { std::string filename(kDrainFilePrefix); filename.append(app_key); filename.append("_"); - filename.append(std::to_string(SbTimeGetNow() / kDrainFileAgeUnit)); + filename.append(std::to_string(PosixTimeToWindowsTime(CurrentPosixTime()) / + kDrainFileAgeUnitUsec)); SB_DCHECK(filename.size() <= kSbFileMaxName); diff --git a/starboard/loader_app/drain_file.h b/starboard/loader_app/drain_file.h index 5a1697f31dfe..35d5e4d27f87 100644 --- a/starboard/loader_app/drain_file.h +++ b/starboard/loader_app/drain_file.h @@ -15,18 +15,17 @@ #ifndef STARBOARD_LOADER_APP_DRAIN_FILE_H_ #define STARBOARD_LOADER_APP_DRAIN_FILE_H_ -#include "starboard/time.h" #include "starboard/types.h" #ifdef __cplusplus extern "C" { #endif -// The units of time that the drain file age is represented in. -extern const SbTime kDrainFileAgeUnit; +// The units of time that the drain file age is represented in, in microseconds. +extern const int64_t kDrainFileAgeUnitUsec; -// The amount of time of which a drain file is valid. -extern const SbTime kDrainFileMaximumAge; +// The amount of time of which a drain file is valid, in microseconds. +extern const int64_t kDrainFileMaximumAgeUsec; // The prefix that all drain file names will have. extern const char kDrainFilePrefix[]; diff --git a/starboard/loader_app/drain_file_helper.cc b/starboard/loader_app/drain_file_helper.cc index 0a61a975abb4..7ce262f45fa1 100644 --- a/starboard/loader_app/drain_file_helper.cc +++ b/starboard/loader_app/drain_file_helper.cc @@ -23,7 +23,7 @@ namespace loader_app { ScopedDrainFile::ScopedDrainFile(const std::string& dir, const std::string& app_key, - SbTime timestamp) { + int64_t timestamp) { app_key_.assign(app_key); path_.assign(dir); @@ -31,7 +31,7 @@ ScopedDrainFile::ScopedDrainFile(const std::string& dir, path_.append(kDrainFilePrefix); path_.append(app_key); path_.append("_"); - path_.append(std::to_string(timestamp / kDrainFileAgeUnit)); + path_.append(std::to_string(timestamp / kDrainFileAgeUnitUsec)); CreateFile(); } diff --git a/starboard/loader_app/drain_file_helper.h b/starboard/loader_app/drain_file_helper.h index 0948f4d5f51d..c6d66ed9c266 100644 --- a/starboard/loader_app/drain_file_helper.h +++ b/starboard/loader_app/drain_file_helper.h @@ -17,8 +17,6 @@ #include -#include "starboard/time.h" - namespace starboard { namespace loader_app { @@ -27,11 +25,12 @@ namespace loader_app { // convenient way of bundling the information and state of the file. This class // is very similar in concept to the starboard::nplb::ScopedRandomFile, except // that it allows you to choose where to create the file. +// |timestamp| is microseconds from Windows epoch UTC. class ScopedDrainFile { public: ScopedDrainFile(const std::string& dir, const std::string& app_key, - SbTime timestamp); + int64_t timestamp); ~ScopedDrainFile(); // Whether or not the created file still exists. diff --git a/starboard/loader_app/drain_file_test.cc b/starboard/loader_app/drain_file_test.cc index a1e0f07ca55b..44775de44a9d 100644 --- a/starboard/loader_app/drain_file_test.cc +++ b/starboard/loader_app/drain_file_test.cc @@ -20,6 +20,7 @@ #include "starboard/common/file.h" #include "starboard/common/log.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/directory.h" #include "starboard/loader_app/drain_file_helper.h" @@ -65,8 +66,9 @@ TEST_F(DrainFileTest, SunnyDay) { // Drain file creation should ignore expired files, even if it has a matching // app key. TEST_F(DrainFileTest, SunnyDayIgnoreExpired) { - ScopedDrainFile stale(GetTempDir(), kAppKeyOne, - SbTimeGetNow() - kDrainFileMaximumAge); + ScopedDrainFile stale( + GetTempDir(), kAppKeyOne, + PosixTimeToWindowsTime(CurrentPosixTime()) - kDrainFileMaximumAgeUsec); EXPECT_FALSE(DrainFileIsAppDraining(GetTempDir(), kAppKeyOne)); EXPECT_TRUE(DrainFileTryDrain(GetTempDir(), kAppKeyOne)); @@ -119,9 +121,11 @@ TEST_F(DrainFileTest, SunnyDayRemove) { TEST_F(DrainFileTest, SunnyDayClearExpired) { EXPECT_TRUE(DrainFileTryDrain(GetTempDir(), kAppKeyOne)); - ScopedDrainFile valid_file(GetTempDir(), kAppKeyTwo, SbTimeGetNow()); - ScopedDrainFile stale_file(GetTempDir(), kAppKeyThree, - SbTimeGetNow() - kDrainFileMaximumAge); + ScopedDrainFile valid_file(GetTempDir(), kAppKeyTwo, + PosixTimeToWindowsTime(CurrentPosixTime())); + ScopedDrainFile stale_file( + GetTempDir(), kAppKeyThree, + PosixTimeToWindowsTime(CurrentPosixTime()) - kDrainFileMaximumAgeUsec); EXPECT_TRUE(DrainFileIsAppDraining(GetTempDir(), kAppKeyOne)); EXPECT_TRUE(DrainFileIsAppDraining(GetTempDir(), kAppKeyTwo)); @@ -136,9 +140,11 @@ TEST_F(DrainFileTest, SunnyDayClearExpired) { TEST_F(DrainFileTest, SunnyDayClearForApp) { EXPECT_TRUE(DrainFileTryDrain(GetTempDir(), kAppKeyOne)); - ScopedDrainFile valid_file(GetTempDir(), kAppKeyTwo, SbTimeGetNow()); - ScopedDrainFile stale_file(GetTempDir(), kAppKeyThree, - SbTimeGetNow() - kDrainFileMaximumAge); + ScopedDrainFile valid_file(GetTempDir(), kAppKeyTwo, + PosixTimeToWindowsTime(CurrentPosixTime())); + ScopedDrainFile stale_file( + GetTempDir(), kAppKeyThree, + PosixTimeToWindowsTime(CurrentPosixTime()) - kDrainFileMaximumAgeUsec); EXPECT_TRUE(DrainFileIsAppDraining(GetTempDir(), kAppKeyOne)); EXPECT_TRUE(DrainFileIsAppDraining(GetTempDir(), kAppKeyTwo)); @@ -155,12 +161,12 @@ TEST_F(DrainFileTest, SunnyDayClearForApp) { // Ranking drain files should first be done by timestamp, with the app key being // used as a tie breaker. TEST_F(DrainFileTest, SunnyDayRankCorrectlyRanksFiles) { - const SbTime timestamp = SbTimeGetNow(); + const int64_t timestamp = PosixTimeToWindowsTime(CurrentPosixTime()); ScopedDrainFile early_and_least(GetTempDir(), "a", timestamp); ScopedDrainFile later_and_least(GetTempDir(), "c", timestamp); ScopedDrainFile later_and_greatest(GetTempDir(), "b", - timestamp + kDrainFileAgeUnit); + timestamp + kDrainFileAgeUnitUsec); std::vector result(kSbFileMaxName); diff --git a/starboard/media.h b/starboard/media.h index 0ddd5f462a38..0a7bd549be0e 100644 --- a/starboard/media.h +++ b/starboard/media.h @@ -22,7 +22,6 @@ #include "starboard/drm.h" #include "starboard/export.h" -#include "starboard/time.h" #include "starboard/types.h" #ifdef __cplusplus @@ -526,7 +525,7 @@ typedef struct SbMediaAudioConfiguration { // The expected latency of audio over this output, in microseconds, or |0| if // this device cannot provide this information. - SbTime latency; + int64_t latency; // The type of audio coding used over this connection. SbMediaAudioCodingType coding_type; @@ -572,8 +571,8 @@ typedef struct SbMediaAudioStreamInfo { typedef struct SbMediaAudioSampleInfo { // The set of information of the video stream associated with this sample. SbMediaAudioStreamInfo stream_info; - SbTime discarded_duration_from_front; - SbTime discarded_duration_from_back; + int64_t discarded_duration_from_front; // in microseconds. + int64_t discarded_duration_from_back; // in microseconds. } SbMediaAudioSampleInfo; #else // SB_API_VERSION >= 15 @@ -731,15 +730,16 @@ SB_EXPORT int SbMediaGetBufferAllocationUnit(); // difficulty if this value is too low. SB_EXPORT int SbMediaGetAudioBufferBudget(); -// Specifies the duration threshold of media source garbage collection. When -// the accumulated duration in a source buffer exceeds this value, the media -// source implementation will try to eject existing buffers from the cache. This -// is usually triggered when the video being played has a simple content and the -// encoded data is small. In such case this can limit how much is allocated for -// the book keeping data of the media buffers and avoid OOM of system heap. This -// should return 170 seconds for most of the platforms. But it can be further -// reduced on systems with extremely low memory. -SB_EXPORT SbTime SbMediaGetBufferGarbageCollectionDurationThreshold(); +// Specifies the duration threshold of media source garbage collection in +// microseconds. When the accumulated duration in a source buffer exceeds this +// value, the media source implementation will try to eject existing buffers +// from the cache. This is usually triggered when the video being played has a +// simple content and the encoded data is small. In such case this can limit +// how much is allocated for the book keeping data of the media buffers and +// avoid OOM of system heap. This should return 170 seconds for most of the +// platforms. But it can be further reduced on systems with extremely low +// memory. +SB_EXPORT int64_t SbMediaGetBufferGarbageCollectionDurationThreshold(); // The amount of memory that will be used to store media buffers allocated // during system startup. To allocate a large chunk at startup helps with @@ -834,14 +834,14 @@ SB_EXPORT int SbMediaGetVideoBufferBudget(SbMediaVideoCodec codec, // Communicate to the platform how far past |current_playback_position| the app // will write audio samples. The app will write all samples between // |current_playback_position| and |current_playback_position| + |duration|, as -// soon as they are available. The app may sometimes write more samples than -// that, but the app only guarantees to write |duration| past -// |current_playback_position| in general. The platform is responsible for +// soon as they are available (during is in microseconds). The app may sometimes +// write more samples than that, but the app only guarantees to write |duration| +// past |current_playback_position| in general. The platform is responsible for // guaranteeing that when only |duration| audio samples are written at a time, // no playback issues occur (such as transient or indefinite hanging). The // platform may assume |duration| >= 0.5 seconds. #if SB_API_VERSION < 15 -SB_EXPORT void SbMediaSetAudioWriteDuration(SbTime duration); +SB_EXPORT void SbMediaSetAudioWriteDuration(int64_t duration); #endif // SB_API_VERSION < 15 #ifdef __cplusplus diff --git a/starboard/nplb/BUILD.gn b/starboard/nplb/BUILD.gn index 6f8577fe4af8..a2d32cb2f4e5 100644 --- a/starboard/nplb/BUILD.gn +++ b/starboard/nplb/BUILD.gn @@ -218,6 +218,7 @@ target(gtest_target_type, "nplb") { "time_get_monotonic_now_test.cc", "time_get_now_test.cc", "time_narrow_test.cc", + "time_test.cc", "time_zone_get_current_test.cc", "time_zone_get_name_test.cc", "ui_navigation_test.cc", diff --git a/starboard/nplb/arpa_inet_test.cc b/starboard/nplb/arpa_inet_test.cc index 9597c9f32ea1..1609e44130c1 100644 --- a/starboard/nplb/arpa_inet_test.cc +++ b/starboard/nplb/arpa_inet_test.cc @@ -38,7 +38,7 @@ TEST(ArpaInet, BigEndian) { EXPECT_EQ(kTestU32, ntohl(kTestU32)); } #else -TEST(SbByteSwapTest, LittleEndian) { +TEST(ArpaInet, LittleEndian) { EXPECT_EQ(kExpectedU16, htons(kTestU16)); EXPECT_EQ(kExpectedU16, ntohs(kTestU16)); diff --git a/starboard/nplb/atomic_test.cc b/starboard/nplb/atomic_test.cc index ad63f9ac95d2..4ef3273cc7e6 100644 --- a/starboard/nplb/atomic_test.cc +++ b/starboard/nplb/atomic_test.cc @@ -17,7 +17,6 @@ #include "starboard/common/atomic.h" #include "starboard/memory.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" @@ -340,7 +339,7 @@ template void* TestOnceEntryPoint(void* raw_context) { // Force every thread to sleep immediately so the first thread doesn't always // just win. - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); TestOnceContext* context = reinterpret_cast*>(raw_context); SetData(context->state, context->out_data, context->data, context->size); diff --git a/starboard/nplb/audio_sink_helpers.cc b/starboard/nplb/audio_sink_helpers.cc index 712742d053aa..cc965a34d2a5 100644 --- a/starboard/nplb/audio_sink_helpers.cc +++ b/starboard/nplb/audio_sink_helpers.cc @@ -17,6 +17,7 @@ #include #include "starboard/common/log.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" namespace starboard { @@ -124,13 +125,13 @@ int AudioSinkTestEnvironment::GetFrameBufferFreeSpaceInFrames() const { bool AudioSinkTestEnvironment::WaitUntilUpdateStatusCalled() { ScopedLock lock(mutex_); int update_source_status_call_count = update_source_status_call_count_; - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); while (update_source_status_call_count == update_source_status_call_count_) { - SbTime time_elapsed = SbTimeGetMonotonicNow() - start; + int64_t time_elapsed = CurrentMonotonicTime() - start; if (time_elapsed >= kTimeToTry) { return false; } - SbTime time_to_wait = kTimeToTry - time_elapsed; + int64_t time_to_wait = kTimeToTry - time_elapsed; condition_variable_.WaitTimed(time_to_wait); } return true; @@ -139,13 +140,13 @@ bool AudioSinkTestEnvironment::WaitUntilUpdateStatusCalled() { bool AudioSinkTestEnvironment::WaitUntilSomeFramesAreConsumed() { ScopedLock lock(mutex_); int frames_consumed = frames_consumed_; - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); while (frames_consumed == frames_consumed_) { - SbTime time_elapsed = SbTimeGetMonotonicNow() - start; + int64_t time_elapsed = CurrentMonotonicTime() - start; if (time_elapsed >= kTimeToTry) { return false; } - SbTime time_to_wait = kTimeToTry - time_elapsed; + int64_t time_to_wait = kTimeToTry - time_elapsed; condition_variable_.WaitTimed(time_to_wait); } return true; @@ -157,15 +158,15 @@ bool AudioSinkTestEnvironment::WaitUntilAllFramesAreConsumed() { ScopedLock lock(mutex_); is_eos_reached_ = true; int frames_appended_before_eos = frames_appended_; - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); int silence_frames_appended = 0; while (frames_consumed_ < frames_appended_before_eos) { - SbTime time_elapsed = SbTimeGetMonotonicNow() - start; + int64_t time_elapsed = CurrentMonotonicTime() - start; if (time_elapsed >= kTimeToTry) { return false; } - SbTime time_to_wait = kTimeToTry - time_elapsed; + int64_t time_to_wait = kTimeToTry - time_elapsed; // Append silence as some audio sink implementations won't be able to finish // playback to the last frames filled. diff --git a/starboard/nplb/audio_sink_helpers.h b/starboard/nplb/audio_sink_helpers.h index 24c5da0d0c6f..36f183572a2b 100644 --- a/starboard/nplb/audio_sink_helpers.h +++ b/starboard/nplb/audio_sink_helpers.h @@ -21,7 +21,6 @@ #include "starboard/common/condition_variable.h" #include "starboard/common/mutex.h" #include "starboard/media.h" -#include "starboard/time.h" namespace starboard { namespace nplb { @@ -67,7 +66,7 @@ class AudioSinkTestFrameBuffers { class AudioSinkTestEnvironment { public: static const int kSampleRateCD = 44100; - static const SbTimeMonotonic kTimeToTry = kSbTimeSecond; + static const int64_t kTimeToTry = 1'000'000; // 1 second explicit AudioSinkTestEnvironment( const AudioSinkTestFrameBuffers& frame_buffers); diff --git a/starboard/nplb/audio_sink_test.cc b/starboard/nplb/audio_sink_test.cc index e6c059bccda4..0d3b164d62f1 100644 --- a/starboard/nplb/audio_sink_test.cc +++ b/starboard/nplb/audio_sink_test.cc @@ -18,7 +18,6 @@ #include "starboard/nplb/audio_sink_helpers.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -100,7 +99,7 @@ TEST(SbAudioSinkTest, Underflow) { environment.AppendFrame(frames_to_append); EXPECT_TRUE(environment.WaitUntilSomeFramesAreConsumed()); - SbThreadSleep(250 * kSbTimeMillisecond); + SbThreadSleep(250'000); ASSERT_GT(environment.GetFrameBufferFreeSpaceInFrames(), 0); environment.AppendFrame(environment.GetFrameBufferFreeSpaceInFrames()); EXPECT_TRUE(environment.WaitUntilAllFramesAreConsumed()); diff --git a/starboard/nplb/condition_variable_wait_timed_test.cc b/starboard/nplb/condition_variable_wait_timed_test.cc index 73a2475c2468..f27f7b52c862 100644 --- a/starboard/nplb/condition_variable_wait_timed_test.cc +++ b/starboard/nplb/condition_variable_wait_timed_test.cc @@ -14,6 +14,7 @@ #include "starboard/common/condition_variable.h" #include "starboard/common/mutex.h" +#include "starboard/common/time.h" #include "starboard/nplb/thread_helpers.h" #include "starboard/thread.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,19 +35,19 @@ void DoSunnyDay(TakeThenSignalContext* context, bool check_timeout) { SbThreadCreate(0, kSbThreadNoPriority, kSbThreadNoAffinity, true, NULL, TakeThenSignalEntryPoint, context); - const SbTime kDelay = kSbTimeMillisecond * 10; + const int64_t kDelay = 10'000; // 10ms // Allow two-millisecond-level precision. - const SbTime kPrecision = kSbTimeMillisecond * 2; + const int64_t kPrecision = 2'000; // 2ms // We know the thread hasn't signaled the condition variable yet, and won't // unless we tell it, so it should wait at least the whole delay time. if (check_timeout) { EXPECT_TRUE(SbMutexIsSuccess(SbMutexAcquire(&context->mutex))); - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); SbConditionVariableResult result = SbConditionVariableWaitTimed( &context->condition, &context->mutex, kDelay); EXPECT_EQ(kSbConditionVariableTimedOut, result); - SbTimeMonotonic elapsed = SbTimeGetMonotonicNow() - start; + int64_t elapsed = CurrentMonotonicTime() - start; EXPECT_LE(kDelay, elapsed + kPrecision); EXPECT_GT(kDelay * 2, elapsed - kPrecision); EXPECT_TRUE(SbMutexRelease(&context->mutex)); @@ -59,7 +60,7 @@ void DoSunnyDay(TakeThenSignalContext* context, bool check_timeout) { // acquire the mutex we are holding. context->do_signal.Put(); - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); // We release the mutex when we wait, allowing the thread to actually do the // signaling, and ensuring we are waiting before it signals. @@ -68,7 +69,7 @@ void DoSunnyDay(TakeThenSignalContext* context, bool check_timeout) { EXPECT_EQ(kSbConditionVariableSignaled, result); // We should have waited only a very small amount of time. - EXPECT_GT(kDelay, SbTimeGetMonotonicNow() - start); + EXPECT_GT(kDelay, CurrentMonotonicTime() - start); EXPECT_TRUE(SbMutexRelease(&context->mutex)); } @@ -110,7 +111,7 @@ TEST(SbConditionVariableWaitTimedTest, FLAKY_SunnyDayAutoInit) { // Test marked as flaky because it relies on timing sensitive execution similar // to DoSunnyDay(). TEST(SbConditionVariableWaitTimedTest, FLAKY_SunnyDayNearMaxTime) { - const SbTime kOtherDelay = kSbTimeMillisecond * 10; + const int64_t kOtherDelay = 10'000; // 10ms TakeThenSignalContext context = {TestSemaphore(0), SB_MUTEX_INITIALIZER, SB_CONDITION_VARIABLE_INITIALIZER, kOtherDelay}; @@ -121,7 +122,7 @@ TEST(SbConditionVariableWaitTimedTest, FLAKY_SunnyDayNearMaxTime) { TakeThenSignalEntryPoint, &context); // Try to wait until the end of time. - const SbTime kDelay = kSbTimeMax; + const int64_t kDelay = kSbInt64Max; EXPECT_TRUE(SbMutexIsSuccess(SbMutexAcquire(&context.mutex))); @@ -129,7 +130,7 @@ TEST(SbConditionVariableWaitTimedTest, FLAKY_SunnyDayNearMaxTime) { // acquire the mutex we are holding, after it waits for delay_after_signal. context.do_signal.Put(); - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); // We release the mutex when we wait, allowing the thread to actually do the // signaling, and ensuring we are waiting before it signals. @@ -140,9 +141,9 @@ TEST(SbConditionVariableWaitTimedTest, FLAKY_SunnyDayNearMaxTime) { // We should have waited at least the delay_after_signal amount, but not the // full delay. // Add some padding to tolerate slightly imprecise sleeps. - EXPECT_LT(context.delay_after_signal, SbTimeGetMonotonicNow() - start + - (context.delay_after_signal / 10)); - EXPECT_GT(kDelay, SbTimeGetMonotonicNow() - start); + EXPECT_LT(context.delay_after_signal, + CurrentMonotonicTime() - start + (context.delay_after_signal / 10)); + EXPECT_GT(kDelay, CurrentMonotonicTime() - start); EXPECT_TRUE(SbMutexRelease(&context.mutex)); diff --git a/starboard/nplb/drm_session_test.cc b/starboard/nplb/drm_session_test.cc index 906936705c34..adf7f5af28ee 100644 --- a/starboard/nplb/drm_session_test.cc +++ b/starboard/nplb/drm_session_test.cc @@ -20,14 +20,13 @@ #include "starboard/common/log.h" #include "starboard/common/queue.h" #include "starboard/nplb/drm_helpers.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { namespace nplb { namespace { -constexpr SbTimeMonotonic kDefaultWaitForCallbackTimeout = kSbTimeSecond; +constexpr int64_t kDefaultWaitForCallbackTimeout = 1'000'000; // 1 second constexpr char kWidevineKeySystem[] = "com.widevine.alpha"; constexpr char kCencInitDataType[] = "cenc"; constexpr int kInitialTicket = kSbDrmTicketInvalid + 1; diff --git a/starboard/nplb/extern_c_test.cc b/starboard/nplb/extern_c_test.cc index 5fafa6a08422..96cc00f7ada3 100644 --- a/starboard/nplb/extern_c_test.cc +++ b/starboard/nplb/extern_c_test.cc @@ -52,7 +52,9 @@ extern "C" { #include "starboard/string.h" #include "starboard/system.h" #include "starboard/thread.h" +#if SB_API_VERSION < 16 #include "starboard/time.h" +#endif // SB_API_VERSION < 16 #include "starboard/time_zone.h" #include "starboard/types.h" #if SB_API_VERSION < 16 diff --git a/starboard/nplb/file_get_info_test.cc b/starboard/nplb/file_get_info_test.cc index e66c78594138..11847c9022ed 100644 --- a/starboard/nplb/file_get_info_test.cc +++ b/starboard/nplb/file_get_info_test.cc @@ -16,10 +16,10 @@ #include +#include "starboard/common/time.h" #include "starboard/file.h" #include "starboard/nplb/file_helpers.h" #include "starboard/system.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -39,12 +39,16 @@ TEST(SbFileGetInfoTest, WorksOnARegularFile) { for (int i = 0; i < kTrials; ++i) { // We can't assume filesystem timestamp precision, so go back a minute // for a better chance to contain the imprecision and rounding errors. - SbTime time = SbTimeGetNow() - kSbTimeMinute; + const int64_t kOneMinuteInMicroseconds = 60'000'000; + int64_t time = + PosixTimeToWindowsTime(CurrentPosixTime()) - kOneMinuteInMicroseconds; #if !SB_HAS_QUIRK(FILESYSTEM_ZERO_FILEINFO_TIME) #if SB_HAS_QUIRK(FILESYSTEM_COARSE_ACCESS_TIME) // On platforms with coarse access time, we assume 1 day precision and go // back 2 days to avoid rounding issues. - SbTime coarse_time = SbTimeGetNow() - (2 * kSbTimeDay); + const int64_t kOneDayInMicroseconds = 1'000'000LL * 60LL * 60LL * 24LL; + int64_t coarse_time = PosixTimeToWindowsTime(CurrentPosixTime()) - + (2 * kOneDayInMicroseconds); #endif // FILESYSTEM_COARSE_ACCESS_TIME #endif // FILESYSTEM_ZERO_FILEINFO_TIME diff --git a/starboard/nplb/file_get_path_info_test.cc b/starboard/nplb/file_get_path_info_test.cc index 37ccb64c6346..687b6a1892f0 100644 --- a/starboard/nplb/file_get_path_info_test.cc +++ b/starboard/nplb/file_get_path_info_test.cc @@ -16,11 +16,11 @@ #include +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/file.h" #include "starboard/nplb/file_helpers.h" #include "starboard/system.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -52,12 +52,16 @@ TEST(SbFileGetPathInfoTest, WorksOnARegularFile) { for (int i = 0; i < kTrials; ++i) { // We can't assume filesystem timestamp precision, so go back a minute // for a better chance to contain the imprecision and rounding errors. - SbTime time = SbTimeGetNow() - kSbTimeMinute; + const int64_t kOneMinuteInMicroseconds = 60'000'000; + int64_t time = + PosixTimeToWindowsTime(CurrentPosixTime()) - kOneMinuteInMicroseconds; #if !SB_HAS_QUIRK(FILESYSTEM_ZERO_FILEINFO_TIME) #if SB_HAS_QUIRK(FILESYSTEM_COARSE_ACCESS_TIME) // On platforms with coarse access time, we assume 1 day precision and go // back 2 days to avoid rounding issues. - SbTime coarse_time = SbTimeGetNow() - (2 * kSbTimeDay); + const int64_t kOneDayInMicroseconds = 1'000'000LL * 60LL * 60LL * 24LL; + int64_t coarse_time = PosixTimeToWindowsTime(CurrentPosixTime()) - + (2 * kOneDayInMicroseconds); #endif // FILESYSTEM_COARSE_ACCESS_TIME #endif // FILESYSTEM_ZERO_FILEINFO_TIME diff --git a/starboard/nplb/include_all.c b/starboard/nplb/include_all.c index 63c71b2b2990..78ca0e89992a 100644 --- a/starboard/nplb/include_all.c +++ b/starboard/nplb/include_all.c @@ -51,7 +51,9 @@ #include "starboard/string.h" #include "starboard/system.h" #include "starboard/thread.h" +#if SB_API_VERSION < 16 #include "starboard/time.h" +#endif // SB_API_VERSION < 16 #include "starboard/time_zone.h" #include "starboard/types.h" #if SB_API_VERSION < 16 diff --git a/starboard/nplb/media_buffer_test.cc b/starboard/nplb/media_buffer_test.cc index 96928201e262..da62c253139f 100644 --- a/starboard/nplb/media_buffer_test.cc +++ b/starboard/nplb/media_buffer_test.cc @@ -236,8 +236,8 @@ TEST(SbMediaBufferTest, AudioBudget) { } TEST(SbMediaBufferTest, GarbageCollectionDurationThreshold) { - int kMinGarbageCollectionDurationThreshold = 30 * kSbTimeSecond; - int kMaxGarbageCollectionDurationThreshold = 240 * kSbTimeSecond; + int kMinGarbageCollectionDurationThreshold = 30'000'000LL; // 30 seconds + int kMaxGarbageCollectionDurationThreshold = 240'000'000LL; // 240 seconds int threshold = SbMediaGetBufferGarbageCollectionDurationThreshold(); EXPECT_GE(threshold, kMinGarbageCollectionDurationThreshold); EXPECT_LE(threshold, kMaxGarbageCollectionDurationThreshold); diff --git a/starboard/nplb/media_can_play_mime_and_key_system_test.cc b/starboard/nplb/media_can_play_mime_and_key_system_test.cc index a77a4e944716..6c2619942b4e 100644 --- a/starboard/nplb/media_can_play_mime_and_key_system_test.cc +++ b/starboard/nplb/media_can_play_mime_and_key_system_test.cc @@ -18,11 +18,11 @@ #include "starboard/common/log.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/media.h" #include "starboard/nplb/drm_helpers.h" #include "starboard/nplb/media_can_play_mime_and_key_system_test_helpers.h" #include "starboard/nplb/performance_helpers.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -915,15 +915,15 @@ TEST(SbMediaCanPlayMimeAndKeySystem, VerifyMaxBitrate) { TEST(SbMediaCanPlayMimeAndKeySystem, FLAKY_ValidatePerformance) { auto test_sequential_function_calls = [](const SbMediaCanPlayMimeAndKeySystemParam* mime_params, - int num_function_calls, SbTimeMonotonic max_time_delta_per_call, + int num_function_calls, int64_t max_time_delta_per_call, const char* query_type) { - const SbTimeMonotonic time_start = SbTimeGetMonotonicNow(); + const int64_t time_start = CurrentMonotonicTime(); for (int i = 0; i < num_function_calls; ++i) { SbMediaCanPlayMimeAndKeySystem(mime_params[i].mime, mime_params[i].key_system); } - const SbTimeMonotonic time_last = SbTimeGetMonotonicNow(); - const SbTimeMonotonic time_delta = time_last - time_start; + const int64_t time_last = CurrentMonotonicTime(); + const int64_t time_delta = time_last - time_start; const double time_per_call = static_cast(time_delta) / num_function_calls; @@ -937,8 +937,8 @@ TEST(SbMediaCanPlayMimeAndKeySystem, FLAKY_ValidatePerformance) { // Warmup the cache. test_sequential_function_calls(kWarmupQueryParams, - SB_ARRAY_SIZE_INT(kWarmupQueryParams), - 100 * kSbTimeMillisecond, "Warmup queries"); + SB_ARRAY_SIZE_INT(kWarmupQueryParams), 100'000, + "Warmup queries"); // First round of the queries. test_sequential_function_calls( diff --git a/starboard/nplb/media_configuration_test.cc b/starboard/nplb/media_configuration_test.cc index 432b12a9255e..242fdad07170 100644 --- a/starboard/nplb/media_configuration_test.cc +++ b/starboard/nplb/media_configuration_test.cc @@ -15,7 +15,6 @@ #include "starboard/media.h" #include "starboard/nplb/performance_helpers.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -28,10 +27,10 @@ TEST(SbMediaConfigurationTest, ValidatePerformance) { const int count_audio_output = SbMediaGetAudioOutputCount(); for (int i = 0; i < count_audio_output; ++i) { constexpr int kNumberOfCalls = 100; - constexpr SbTime kMaxAverageTimePerCall = 500; + constexpr int64_t kMaxAverageTimePerCallUsec = 500; SbMediaAudioConfiguration configuration; - TEST_PERF_FUNCWITHARGS_EXPLICIT(kNumberOfCalls, kMaxAverageTimePerCall, + TEST_PERF_FUNCWITHARGS_EXPLICIT(kNumberOfCalls, kMaxAverageTimePerCallUsec, SbMediaGetAudioConfiguration, i, &configuration); } diff --git a/starboard/nplb/media_set_audio_write_duration_test.cc b/starboard/nplb/media_set_audio_write_duration_test.cc index 573dd35346c7..c03077a357a0 100644 --- a/starboard/nplb/media_set_audio_write_duration_test.cc +++ b/starboard/nplb/media_set_audio_write_duration_test.cc @@ -16,6 +16,7 @@ #include "starboard/common/optional.h" #include "starboard/common/spin_lock.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/nplb/player_creation_param_helpers.h" #include "starboard/nplb/player_test_util.h" @@ -34,8 +35,8 @@ using shared::starboard::player::video_dmp::VideoDmpReader; using ::starboard::testing::FakeGraphicsContextProvider; using ::testing::ValuesIn; -const SbTime kDuration = kSbTimeSecond / 2; -const SbTime kSmallWaitInterval = 10 * kSbTimeMillisecond; +const int64_t kDuration = 500'000; // 0.5 seconds +const int64_t kSmallWaitInterval = 10'000; // 10 ms class SbMediaSetAudioWriteDurationTest : public ::testing::TestWithParam { @@ -128,10 +129,10 @@ class SbMediaSetAudioWriteDurationTest } void WaitForPlayerState(SbPlayerState desired_state) { - SbTime start_of_wait = SbTimeGetMonotonicNow(); - const SbTime kMaxWaitTime = 3 * kSbTimeSecond; + int64_t start_of_wait = CurrentMonotonicTime(); + const int64_t kMaxWaitTime = 3'000'000LL; // 3 seconds while (player_state_ != desired_state && - (SbTimeGetMonotonicNow() - start_of_wait) < kMaxWaitTime) { + (CurrentMonotonicTime() - start_of_wait) < kMaxWaitTime) { SbThreadSleep(kSmallWaitInterval); TryToWritePendingSample(); } @@ -148,10 +149,10 @@ class SbMediaSetAudioWriteDurationTest FakeGraphicsContextProvider fake_graphics_context_provider_; VideoDmpReader dmp_reader_; SbPlayerState player_state_ = kSbPlayerStateInitialized; - SbTime last_input_timestamp_ = 0; - SbTime first_input_timestamp_ = 0; + int64_t last_input_timestamp_ = 0; + int64_t first_input_timestamp_ = 0; int index_ = 0; - SbTime total_duration_ = kDuration; + int64_t total_duration_ = kDuration; // Guard access to |pending_decoder_status_|. mutable SbAtomic32 pending_decoder_status_lock_ = starboard::kSpinLockStateReleased; @@ -200,16 +201,16 @@ TEST_P(SbMediaSetAudioWriteDurationTest, WriteLimitedInput) { WaitForPlayerState(kSbPlayerStatePresenting); // Wait until the playback time is > 0. - const SbTime kMaxWaitTime = 5 * kSbTimeSecond; - SbTime start_of_wait = SbTimeGetMonotonicNow(); + const int64_t kMaxWaitTime = 5'000'000; // 5 seconds + int64_t start_of_wait = CurrentMonotonicTime(); #if SB_API_VERSION >= 15 SbPlayerInfo info = {}; #else // SB_API_VERSION >= 15 SbPlayerInfo2 info = {}; #endif // SB_API_VERSION >= 15 - while (SbTimeGetMonotonicNow() - start_of_wait < kMaxWaitTime && + while (CurrentMonotonicTime() - start_of_wait < kMaxWaitTime && info.current_media_timestamp == 0) { - SbThreadSleep(kSbTimeMillisecond * 500); + SbThreadSleep(500'000); #if SB_API_VERSION >= 15 SbPlayerGetInfo(player, &info); #else // SB_API_VERSION >= 15 @@ -231,7 +232,7 @@ TEST_P(SbMediaSetAudioWriteDurationTest, WriteContinuedLimitedInput) { #endif // SB_API_VERSION < 15 // This directly impacts the runtime of the test. - total_duration_ = 15 * kSbTimeSecond; + total_duration_ = 15'000'000LL; // 15 seconds SbPlayer player = CreatePlayer(); WaitForPlayerState(kSbPlayerStateInitialized); @@ -246,9 +247,9 @@ TEST_P(SbMediaSetAudioWriteDurationTest, WriteContinuedLimitedInput) { // Wait for the player to play far enough. It may not play all the way to // the end, but it should leave off no more than |kDuration|. - SbTime min_ending_playback_time = total_duration_ - kDuration; - SbTime start_of_wait = SbTimeGetMonotonicNow(); - const SbTime kMaxWaitTime = total_duration_ + 5 * kSbTimeSecond; + int64_t min_ending_playback_time = total_duration_ - kDuration; + int64_t start_of_wait = CurrentMonotonicTime(); + const int64_t kMaxWaitTime = total_duration_ + 5'000'000LL; #if SB_API_VERSION >= 15 SbPlayerInfo info; SbPlayerGetInfo(player, &info); @@ -257,7 +258,7 @@ TEST_P(SbMediaSetAudioWriteDurationTest, WriteContinuedLimitedInput) { SbPlayerGetInfo2(player, &info); #endif // SB_API_VERSION >= 15 while (info.current_media_timestamp < min_ending_playback_time && - (SbTimeGetMonotonicNow() - start_of_wait) < kMaxWaitTime) { + (CurrentMonotonicTime() - start_of_wait) < kMaxWaitTime) { #if SB_API_VERSION >= 15 SbPlayerGetInfo(player, &info); #else // SB_API_VERSION >= 15 diff --git a/starboard/nplb/microphone_read_test.cc b/starboard/nplb/microphone_read_test.cc index 6a6991cfe2e7..a33cc3e05e24 100644 --- a/starboard/nplb/microphone_read_test.cc +++ b/starboard/nplb/microphone_read_test.cc @@ -88,7 +88,7 @@ TEST(SbMicrophoneReadTest, SunnyDayOpenSleepCloseAndOpenRead) { EXPECT_TRUE(SbMicrophoneOpen(microphone)); - SbThreadSleep(50 * kSbTimeMillisecond); + SbThreadSleep(50'000); EXPECT_TRUE(SbMicrophoneClose(microphone)); EXPECT_TRUE(SbMicrophoneOpen(microphone)); diff --git a/starboard/nplb/multiple_player_test.cc b/starboard/nplb/multiple_player_test.cc index b2c8a04acc81..5b64149c8495 100644 --- a/starboard/nplb/multiple_player_test.cc +++ b/starboard/nplb/multiple_player_test.cc @@ -100,7 +100,7 @@ void WriteSamples(const SbPlayerTestConfig& player_config, return; } - const SbTime kDurationToPlay = kSbTimeMillisecond * 200; + const int64_t kDurationToPlay = 200'000; // 200ms GroupedSamples samples; if (player_fixture.HasAudio()) { diff --git a/starboard/nplb/performance_helpers.h b/starboard/nplb/performance_helpers.h index 7a9b538ddc50..4aa323a42e97 100644 --- a/starboard/nplb/performance_helpers.h +++ b/starboard/nplb/performance_helpers.h @@ -15,6 +15,7 @@ #ifndef STARBOARD_NPLB_PERFORMANCE_HELPERS_H_ #define STARBOARD_NPLB_PERFORMANCE_HELPERS_H_ +#include "starboard/common/time.h" #include "starboard/types.h" #include "testing/gtest/include/gtest/gtest.h" @@ -24,19 +25,18 @@ namespace nplb { // Default for parameter |count_calls| of TestPerformanceOfFunction. constexpr int kDefaultTestPerformanceCountCalls = 1000; // Default for parameter |max_time_per_call| of TestPerformanceOfFunction. -constexpr SbTimeMonotonic kDefaultTestPerformanceMaxTimePerCall = - kSbTimeMillisecond / 2; +constexpr int64_t kDefaultTestPerformanceMaxTimePerCall = 500; // 0.5ms // Helper function for testing function call time performance. template void TestPerformanceOfFunction(const char* const name_of_f, R (*const f)(Args...), Args... args) { // Measure time pre calls to |f|. - const SbTimeMonotonic time_start = SbTimeGetMonotonicNow(); + const int64_t time_start = CurrentMonotonicTime(); SbLogPriority initial_log_level = starboard::logging::GetMinLogLevel(); starboard::logging::SetMinLogLevel(kSbLogPriorityFatal); @@ -49,8 +49,8 @@ void TestPerformanceOfFunction(const char* const name_of_f, starboard::logging::SetMinLogLevel(initial_log_level); // Measure time post calls to |f|. - const SbTimeMonotonic time_last = SbTimeGetMonotonicNow(); - const SbTimeMonotonic time_delta = time_last - time_start; + const int64_t time_last = CurrentMonotonicTime(); + const int64_t time_delta = time_last - time_start; const double time_per_call = static_cast(time_delta) / count_calls; // Pretty printing. @@ -62,7 +62,7 @@ void TestPerformanceOfFunction(const char* const name_of_f, // Compare |time_delta| to |max_time_delta|. // Using the aggregate time avoids loss of precision at the us range. - const SbTimeMonotonic max_time_delta = max_time_per_call * count_calls; + const int64_t max_time_delta = max_time_per_call * count_calls; EXPECT_LT(time_delta, max_time_delta); } diff --git a/starboard/nplb/player_create_test.cc b/starboard/nplb/player_create_test.cc index 92713549e8b2..73f612bd1c55 100644 --- a/starboard/nplb/player_create_test.cc +++ b/starboard/nplb/player_create_test.cc @@ -19,13 +19,13 @@ #include "starboard/common/media.h" #include "starboard/common/mutex.h" #include "starboard/common/optional.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/decode_target.h" #include "starboard/nplb/player_creation_param_helpers.h" #include "starboard/nplb/player_test_util.h" #include "starboard/player.h" #include "starboard/testing/fake_graphics_context_provider.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -93,12 +93,12 @@ class SbPlayerTest : public ::testing::Test { } void WaitForPlayerInitializedOrError(bool* error_occurred) { - const SbTime kWaitTimeout = kSbTimeSecond * 5; + const int64_t kWaitTimeout = 5'000'000LL; // 5 seconds SB_DCHECK(error_occurred); *error_occurred = false; - const SbTimeMonotonic wait_end = SbTimeGetMonotonicNow() + kWaitTimeout; + const int64_t wait_end = CurrentMonotonicTime() + kWaitTimeout; for (;;) { ScopedLock scoped_lock(mutex_); @@ -113,7 +113,7 @@ class SbPlayerTest : public ::testing::Test { return; } - auto now = SbTimeGetMonotonicNow(); + auto now = CurrentMonotonicTime(); if (now > wait_end) { break; } diff --git a/starboard/nplb/player_get_audio_configuration_test.cc b/starboard/nplb/player_get_audio_configuration_test.cc index d89fd62022ea..7cd5a7e5a8bc 100644 --- a/starboard/nplb/player_get_audio_configuration_test.cc +++ b/starboard/nplb/player_get_audio_configuration_test.cc @@ -230,7 +230,7 @@ TEST_P(SbPlayerGetAudioConfigurationTest, MultipleSeeks) { ASSERT_EQ(initial_configs, configs_after_presenting); } - const SbTime seek_to_time = kSbTimeSecond; + const int64_t seek_to_time = 1'000'000; // 1 second ASSERT_NO_FATAL_FAILURE(player_fixture.Seek(seek_to_time)); std::vector configs_after_seek; diff --git a/starboard/nplb/player_test_fixture.cc b/starboard/nplb/player_test_fixture.cc index 7703dcda1ab7..a529a9a05f8a 100644 --- a/starboard/nplb/player_test_fixture.cc +++ b/starboard/nplb/player_test_fixture.cc @@ -18,6 +18,7 @@ #include #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/nplb/drm_helpers.h" #include "testing/gtest/include/gtest/gtest.h" @@ -126,9 +127,9 @@ GroupedSamples& GroupedSamples::AddAudioSamples(int start_index, GroupedSamples& GroupedSamples::AddAudioSamples( int start_index, int number_of_samples, - SbTime timestamp_offset, - SbTime discarded_duration_from_front, - SbTime discarded_duration_from_back) { + int64_t timestamp_offset, + int64_t discarded_duration_from_front, + int64_t discarded_duration_from_back) { SB_DCHECK(start_index >= 0); SB_DCHECK(number_of_samples >= 0); SB_DCHECK(audio_samples_.empty() || !audio_samples_.back().is_end_of_stream); @@ -234,7 +235,7 @@ SbPlayerTestFixture::~SbPlayerTestFixture() { TearDown(); } -void SbPlayerTestFixture::Seek(const SbTime time) { +void SbPlayerTestFixture::Seek(const int64_t time) { SB_DCHECK(thread_checker_.CalledOnValidThread()); SB_DCHECK(SbPlayerIsValid(player_)); @@ -273,10 +274,10 @@ void SbPlayerTestFixture::Write(const GroupedSamples& grouped_samples) { SB_DCHECK(!iterator.HasMoreAudio() || audio_dmp_reader_); SB_DCHECK(!iterator.HasMoreVideo() || video_dmp_reader_); - const SbTime kDefaultWriteTimeout = kSbTimeSecond * 5; + const int64_t kDefaultWriteTimeout = 5'000'000LL; // 5 seconds - SbTimeMonotonic start = SbTimeGetMonotonicNow(); - while (SbTimeGetMonotonicNow() - start < kDefaultWriteTimeout) { + int64_t start = CurrentMonotonicTime(); + while (CurrentMonotonicTime() - start < kDefaultWriteTimeout) { if (CanWriteMoreAudioData() && iterator.HasMoreAudio()) { auto descriptor = iterator.GetCurrentAudioSamplesToWrite(); if (descriptor.is_end_of_stream) { @@ -347,7 +348,7 @@ void SbPlayerTestFixture::WaitForPlayerEndOfStream() { ASSERT_NO_FATAL_FAILURE(WaitForPlayerState(kSbPlayerStateEndOfStream)); } -SbTime SbPlayerTestFixture::GetCurrentMediaTime() const { +int64_t SbPlayerTestFixture::GetCurrentMediaTime() const { #if SB_API_VERSION >= 15 SbPlayerInfo info = {}; SbPlayerGetInfo(player_, &info); @@ -358,13 +359,13 @@ SbTime SbPlayerTestFixture::GetCurrentMediaTime() const { return info.current_media_timestamp; } -void SbPlayerTestFixture::SetAudioWriteDuration(SbTime duration) { +void SbPlayerTestFixture::SetAudioWriteDuration(int64_t duration) { SB_DCHECK(thread_checker_.CalledOnValidThread()); SB_DCHECK(duration > 0); audio_write_duration_ = duration; } -SbTime SbPlayerTestFixture::GetAudioSampleTimestamp(int index) const { +int64_t SbPlayerTestFixture::GetAudioSampleTimestamp(int index) const { SB_DCHECK(HasAudio()); SB_DCHECK(index < audio_dmp_reader_->number_of_audio_buffers()); return audio_dmp_reader_->GetPlayerSampleInfo(kSbMediaTypeAudio, index) @@ -372,7 +373,7 @@ SbTime SbPlayerTestFixture::GetAudioSampleTimestamp(int index) const { } int SbPlayerTestFixture::ConvertDurationToAudioBufferCount( - SbTime duration) const { + int64_t duration) const { SB_DCHECK(HasAudio()); SB_DCHECK(audio_dmp_reader_->number_of_audio_buffers()); return duration * audio_dmp_reader_->number_of_audio_buffers() / @@ -380,7 +381,7 @@ int SbPlayerTestFixture::ConvertDurationToAudioBufferCount( } int SbPlayerTestFixture::ConvertDurationToVideoBufferCount( - SbTime duration) const { + int64_t duration) const { SB_DCHECK(HasVideo()); SB_DCHECK(video_dmp_reader_->number_of_video_buffers()); return duration * video_dmp_reader_->number_of_video_buffers() / @@ -520,9 +521,9 @@ bool SbPlayerTestFixture::CanWriteMoreVideoData() { void SbPlayerTestFixture::WriteAudioSamples( int start_index, int samples_to_write, - SbTime timestamp_offset, - SbTime discarded_duration_from_front, - SbTime discarded_duration_from_back) { + int64_t timestamp_offset, + int64_t discarded_duration_from_front, + int64_t discarded_duration_from_back) { SB_DCHECK(thread_checker_.CalledOnValidThread()); SB_DCHECK(SbPlayerIsValid(player_)); SB_DCHECK(audio_dmp_reader_); @@ -538,8 +539,8 @@ void SbPlayerTestFixture::WriteAudioSamples( CallSbPlayerWriteSamples( player_, kSbMediaTypeAudio, audio_dmp_reader_.get(), start_index, samples_to_write, timestamp_offset, - std::vector(samples_to_write, discarded_duration_from_front), - std::vector(samples_to_write, discarded_duration_from_back)); + std::vector(samples_to_write, discarded_duration_from_front), + std::vector(samples_to_write, discarded_duration_from_back)); last_written_audio_timestamp_ = audio_dmp_reader_ @@ -587,7 +588,7 @@ void SbPlayerTestFixture::WriteEndOfStream(SbMediaType media_type) { } } -void SbPlayerTestFixture::WaitAndProcessNextEvent(SbTime timeout) { +void SbPlayerTestFixture::WaitAndProcessNextEvent(int64_t timeout) { SB_DCHECK(thread_checker_.CalledOnValidThread()); auto event = callback_event_queue_.GetTimed(timeout); @@ -630,13 +631,13 @@ void SbPlayerTestFixture::WaitAndProcessNextEvent(SbTime timeout) { ASSERT_FALSE(error_occurred_); } -void SbPlayerTestFixture::WaitForDecoderStateNeedsData(const SbTime timeout) { +void SbPlayerTestFixture::WaitForDecoderStateNeedsData(const int64_t timeout) { SB_DCHECK(thread_checker_.CalledOnValidThread()); bool old_can_accept_more_audio_data = can_accept_more_audio_data_; bool old_can_accept_more_video_data = can_accept_more_video_data_; - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); do { ASSERT_FALSE(error_occurred_); GetDecodeTargetWhenSupported(); @@ -645,17 +646,17 @@ void SbPlayerTestFixture::WaitForDecoderStateNeedsData(const SbTime timeout) { old_can_accept_more_video_data != can_accept_more_video_data_) { return; } - } while (SbTimeGetMonotonicNow() - start < timeout); + } while (CurrentMonotonicTime() - start < timeout); } void SbPlayerTestFixture::WaitForPlayerState(const SbPlayerState desired_state, - const SbTime timeout) { + const int64_t timeout) { SB_DCHECK(thread_checker_.CalledOnValidThread()); if (HasReceivedPlayerState(desired_state)) { return; } - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); do { ASSERT_FALSE(error_occurred_); ASSERT_NO_FATAL_FAILURE(GetDecodeTargetWhenSupported()); @@ -663,7 +664,7 @@ void SbPlayerTestFixture::WaitForPlayerState(const SbPlayerState desired_state, if (HasReceivedPlayerState(desired_state)) { return; } - } while (SbTimeGetMonotonicNow() - start < timeout); + } while (CurrentMonotonicTime() - start < timeout); FAIL() << "WaitForPlayerState() did not receive expected state."; } diff --git a/starboard/nplb/player_test_fixture.h b/starboard/nplb/player_test_fixture.h index 72b069b939eb..0027ebf89478 100644 --- a/starboard/nplb/player_test_fixture.h +++ b/starboard/nplb/player_test_fixture.h @@ -42,9 +42,9 @@ class SbPlayerTestFixture { struct AudioSamplesDescriptor { int start_index = 0; int samples_count = 0; - SbTime timestamp_offset = 0; - SbTime discarded_duration_from_front = 0; - SbTime discarded_duration_from_back = 0; + int64_t timestamp_offset = 0; + int64_t discarded_duration_from_front = 0; + int64_t discarded_duration_from_back = 0; bool is_end_of_stream = false; }; @@ -57,9 +57,9 @@ class SbPlayerTestFixture { GroupedSamples& AddAudioSamples(int start_index, int number_of_samples); GroupedSamples& AddAudioSamples(int start_index, int number_of_samples, - SbTime timestamp_offset, - SbTime discarded_duration_from_front, - SbTime discarded_duration_from_back); + int64_t timestamp_offset, + int64_t discarded_duration_from_front, + int64_t discarded_duration_from_back); GroupedSamples& AddAudioEOS(); GroupedSamples& AddVideoSamples(int start_index, int number_of_samples); GroupedSamples& AddVideoEOS(); @@ -76,7 +76,7 @@ class SbPlayerTestFixture { testing::FakeGraphicsContextProvider* fake_graphics_context_provider); ~SbPlayerTestFixture(); - void Seek(const SbTime time); + void Seek(const int64_t time); // Write audio and video samples. It waits for // |kSbPlayerDecoderStateNeedsData| internally. When writing EOS are // requested, the function will write EOS after all samples of the same type @@ -86,22 +86,21 @@ class SbPlayerTestFixture { void WaitForPlayerPresenting(); // Wait until kSbPlayerStateEndOfStream received. void WaitForPlayerEndOfStream(); - SbTime GetCurrentMediaTime() const; + int64_t GetCurrentMediaTime() const; - void SetAudioWriteDuration(SbTime duration); + void SetAudioWriteDuration(int64_t duration); SbPlayer GetPlayer() const { return player_; } bool HasAudio() const { return audio_dmp_reader_; } bool HasVideo() const { return video_dmp_reader_; } - SbTime GetAudioSampleTimestamp(int index) const; - int ConvertDurationToAudioBufferCount(SbTime duration) const; - int ConvertDurationToVideoBufferCount(SbTime duration) const; + int64_t GetAudioSampleTimestamp(int index) const; + int ConvertDurationToAudioBufferCount(int64_t duration) const; + int ConvertDurationToVideoBufferCount(int64_t duration) const; private: - static constexpr SbTime kDefaultWaitForPlayerStateTimeout = 5 * kSbTimeSecond; - static constexpr SbTime kDefaultWaitForCallbackEventTimeout = - 15 * kSbTimeMillisecond; + static constexpr int64_t kDefaultWaitForPlayerStateTimeout = 5'000'000LL; + static constexpr int64_t kDefaultWaitForCallbackEventTimeout = 15'000; typedef shared::starboard::player::video_dmp::VideoDmpReader VideoDmpReader; @@ -160,9 +159,9 @@ class SbPlayerTestFixture { void WriteAudioSamples(int start_index, int samples_to_write, - SbTime timestamp_offset, - SbTime discarded_duration_from_front, - SbTime discarded_duration_from_back); + int64_t timestamp_offset, + int64_t discarded_duration_from_front, + int64_t discarded_duration_from_back); void WriteVideoSamples(int start_index, int samples_to_write); void WriteEndOfStream(SbMediaType media_type); @@ -172,16 +171,16 @@ class SbPlayerTestFixture { // * |player_state_set_| for SbPlayerState updates. // Executes a blocking wait for any new CallbackEvents to be enqueued. void WaitAndProcessNextEvent( - SbTime timeout = kDefaultWaitForCallbackEventTimeout); + int64_t timeout = kDefaultWaitForCallbackEventTimeout); // Waits for |kSbPlayerDecoderStateNeedsData| to be sent. void WaitForDecoderStateNeedsData( - const SbTime timeout = kDefaultWaitForCallbackEventTimeout); + const int64_t timeout = kDefaultWaitForCallbackEventTimeout); // Waits for desired player state update to be sent. void WaitForPlayerState( const SbPlayerState desired_state, - const SbTime timeout = kDefaultWaitForPlayerStateTimeout); + const int64_t timeout = kDefaultWaitForPlayerStateTimeout); // When the |output_mode| is decoding to texture, then this method is used to // advance the decoded frames. @@ -214,9 +213,9 @@ class SbPlayerTestFixture { bool can_accept_more_video_data_ = false; // The duration of how far past the current playback position we will write - // audio samples. - SbTime audio_write_duration_ = 0; - SbTime last_written_audio_timestamp_ = 0; + // audio samples, in microseconds. + int64_t audio_write_duration_ = 0; + int64_t last_written_audio_timestamp_ = 0; // Set of received player state updates from the underlying player. This is // used to check that the state updates occur in a valid order during normal diff --git a/starboard/nplb/player_test_util.cc b/starboard/nplb/player_test_util.cc index 34639e1afb88..57ca92a10d3e 100644 --- a/starboard/nplb/player_test_util.cc +++ b/starboard/nplb/player_test_util.cc @@ -254,9 +254,9 @@ void CallSbPlayerWriteSamples( shared::starboard::player::video_dmp::VideoDmpReader* dmp_reader, int start_index, int number_of_samples_to_write, - SbTime timestamp_offset, - const std::vector& discarded_durations_from_front, - const std::vector& discarded_durations_from_back) { + int64_t timestamp_offset, + const std::vector& discarded_durations_from_front, + const std::vector& discarded_durations_from_back) { SB_DCHECK(start_index >= 0); SB_DCHECK(number_of_samples_to_write > 0); diff --git a/starboard/nplb/player_test_util.h b/starboard/nplb/player_test_util.h index 100bf6ca30cd..518d43d18709 100644 --- a/starboard/nplb/player_test_util.h +++ b/starboard/nplb/player_test_util.h @@ -107,9 +107,9 @@ void CallSbPlayerWriteSamples( shared::starboard::player::video_dmp::VideoDmpReader* dmp_reader, int start_index, int number_of_samples_to_write, - SbTime timestamp_offset = 0, - const std::vector& discarded_durations_from_front = {}, - const std::vector& discarded_durations_from_back = {}); + int64_t timestamp_offset = 0, + const std::vector& discarded_durations_from_front = {}, + const std::vector& discarded_durations_from_back = {}); bool IsOutputModeSupported(SbPlayerOutputMode output_mode, SbMediaAudioCodec audio_codec, diff --git a/starboard/nplb/player_write_sample_test.cc b/starboard/nplb/player_write_sample_test.cc index f17e14f7897f..8df2dd0a5dc0 100644 --- a/starboard/nplb/player_write_sample_test.cc +++ b/starboard/nplb/player_write_sample_test.cc @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "starboard/common/time.h" #include "starboard/nplb/drm_helpers.h" #include "starboard/nplb/player_creation_param_helpers.h" #include "starboard/nplb/player_test_fixture.h" @@ -42,7 +43,7 @@ TEST_P(SbPlayerWriteSampleTest, SeekAndDestroy) { if (HasFatalFailure()) { return; } - ASSERT_NO_FATAL_FAILURE(player_fixture.Seek(kSbTimeSecond)); + ASSERT_NO_FATAL_FAILURE(player_fixture.Seek(1'000'000)); } TEST_P(SbPlayerWriteSampleTest, NoInput) { @@ -135,17 +136,17 @@ TEST_P(SbPlayerWriteSampleTest, LimitedAudioInput) { // TODO: we simply set audio write duration to 0.5 second. Ideally, we should // set the audio write duration to 10 seconds if audio connectors are remote. - player_fixture.SetAudioWriteDuration(kSbTimeSecond / 2); + player_fixture.SetAudioWriteDuration(500'000); GroupedSamples samples; if (player_fixture.HasAudio()) { samples.AddAudioSamples( - 0, player_fixture.ConvertDurationToAudioBufferCount(kSbTimeSecond)); + 0, player_fixture.ConvertDurationToAudioBufferCount(1'000'000)); samples.AddAudioEOS(); } if (player_fixture.HasVideo()) { samples.AddVideoSamples( - 0, player_fixture.ConvertDurationToVideoBufferCount(kSbTimeSecond)); + 0, player_fixture.ConvertDurationToVideoBufferCount(1'000'000)); samples.AddVideoEOS(); } @@ -172,7 +173,7 @@ TEST_P(SbPlayerWriteSampleTest, PartialAudio) { return; } - const SbTime kDurationToPlay = kSbTimeSecond; + const int64_t kDurationToPlay = 1'000'000; // 1 second const float kSegmentSize = 0.3f; GroupedSamples samples; @@ -185,11 +186,11 @@ TEST_P(SbPlayerWriteSampleTest, PartialAudio) { int total_buffers_to_write = player_fixture.ConvertDurationToAudioBufferCount(kDurationToPlay); for (int i = 0; i < total_buffers_to_write; i++) { - SbTime current_timestamp = player_fixture.GetAudioSampleTimestamp(i); - SbTime next_timestamp = player_fixture.GetAudioSampleTimestamp(i + 1); - SbTime buffer_duration = next_timestamp - current_timestamp; - SbTime segment_duration = buffer_duration * kSegmentSize; - SbTime written_duration = 0; + int64_t current_timestamp = player_fixture.GetAudioSampleTimestamp(i); + int64_t next_timestamp = player_fixture.GetAudioSampleTimestamp(i + 1); + int64_t buffer_duration = next_timestamp - current_timestamp; + int64_t segment_duration = buffer_duration * kSegmentSize; + int64_t written_duration = 0; while (written_duration < buffer_duration) { samples.AddAudioSamples( i, 1, written_duration, written_duration, @@ -203,15 +204,15 @@ TEST_P(SbPlayerWriteSampleTest, PartialAudio) { ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples)); ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerPresenting()); - SbTime start_system_time = SbTimeGetMonotonicNow(); - SbTime start_media_time = player_fixture.GetCurrentMediaTime(); + int64_t start_system_time = CurrentMonotonicTime(); + int64_t start_media_time = player_fixture.GetCurrentMediaTime(); ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream()); - SbTime end_system_time = SbTimeGetMonotonicNow(); - SbTime end_media_time = player_fixture.GetCurrentMediaTime(); + int64_t end_system_time = CurrentMonotonicTime(); + int64_t end_media_time = player_fixture.GetCurrentMediaTime(); - const SbTime kDurationDifferenceAllowance = 500 * kSbTimeMillisecond; + const int64_t kDurationDifferenceAllowance = 500'000; // 500ms; EXPECT_NEAR(end_media_time, kDurationToPlay, kDurationDifferenceAllowance); EXPECT_NEAR(end_system_time - start_system_time + start_media_time, kDurationToPlay, kDurationDifferenceAllowance); @@ -248,9 +249,9 @@ TEST_P(SbPlayerWriteSampleTest, PartialAudioDiscardAll) { return; } - const SbTime kDurationToPlay = kSbTimeSecond; - const SbTime kDurationPerWrite = 100 * kSbTimeMillisecond; - const SbTime kNumberOfBuffersToDiscard = 20; + const int64_t kDurationToPlay = 1'000'000; // 1 second + const int64_t kDurationPerWrite = 100'000; // 100ms + const int64_t kNumberOfBuffersToDiscard = 20; GroupedSamples samples; if (player_fixture.HasVideo()) { @@ -260,13 +261,13 @@ TEST_P(SbPlayerWriteSampleTest, PartialAudioDiscardAll) { } int written_buffer_index = 0; - SbTime current_time_offset = 0; + int64_t current_time_offset = 0; int num_of_buffers_per_write = player_fixture.ConvertDurationToAudioBufferCount(kDurationPerWrite); int count = 0; while (current_time_offset < kDurationToPlay) { - const SbTime kDurationToDiscard = - count % 2 == 0 ? kSbTimeSecond : kSbTimeMax; + const int64_t kDurationToDiscard = + count % 2 == 0 ? 1'000'000LL : kSbInt64Max; count++; // Discard from front. for (int i = 0; i < kNumberOfBuffersToDiscard; i++) { @@ -289,16 +290,16 @@ TEST_P(SbPlayerWriteSampleTest, PartialAudioDiscardAll) { ASSERT_NO_FATAL_FAILURE(player_fixture.Write(samples)); ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerPresenting()); - SbTime start_system_time = SbTimeGetMonotonicNow(); - SbTime start_media_time = player_fixture.GetCurrentMediaTime(); + int64_t start_system_time = CurrentMonotonicTime(); + int64_t start_media_time = player_fixture.GetCurrentMediaTime(); ASSERT_NO_FATAL_FAILURE(player_fixture.WaitForPlayerEndOfStream()); - SbTime end_system_time = SbTimeGetMonotonicNow(); - SbTime end_media_time = player_fixture.GetCurrentMediaTime(); + int64_t end_system_time = CurrentMonotonicTime(); + int64_t end_media_time = player_fixture.GetCurrentMediaTime(); - const SbTime kDurationDifferenceAllowance = 500 * kSbTimeMillisecond; - SbTime total_written_duration = + const int64_t kDurationDifferenceAllowance = 500'000; // 500ms + int64_t total_written_duration = player_fixture.GetAudioSampleTimestamp(written_buffer_index); EXPECT_NEAR(end_media_time, total_written_duration, kDurationDifferenceAllowance); @@ -333,7 +334,7 @@ class SecondaryPlayerTestThread : public AbstractTestThread { return; } - const SbTime kDurationToPlay = kSbTimeMillisecond * 200; + const int64_t kDurationToPlay = 200'000; // 200ms GroupedSamples samples; if (player_fixture.HasAudio()) { diff --git a/starboard/nplb/rwlock_test.cc b/starboard/nplb/rwlock_test.cc index baea46d6f7de..9ec49902fde4 100644 --- a/starboard/nplb/rwlock_test.cc +++ b/starboard/nplb/rwlock_test.cc @@ -13,6 +13,7 @@ // limitations under the License. #include "starboard/common/rwlock.h" +#include "starboard/common/time.h" #include "starboard/configuration.h" #include "starboard/nplb/thread_helpers.h" #include "starboard/thread.h" @@ -100,8 +101,8 @@ TEST(RWLock, ReadAcquisitionTwoThreads) { class ThreadHoldsWriteLockForTime : public AbstractTestThread { public: struct SharedData { - explicit SharedData(SbTime time_hold) : time_to_hold(time_hold) {} - SbTime time_to_hold; + explicit SharedData(int64_t time_hold) : time_to_hold(time_hold) {} + int64_t time_to_hold; Semaphore signal_write_lock; RWLock rw_lock; }; @@ -118,21 +119,21 @@ class ThreadHoldsWriteLockForTime : public AbstractTestThread { SharedData* shared_data_; }; TEST(RWLock, FLAKY_HoldsLockForTime) { - const SbTime kTimeToHold = kSbTimeMillisecond * 5; - const SbTime kAllowedError = kSbTimeMillisecond * 10; + const int64_t kTimeToHold = 5'000; // 5ms + const int64_t kAllowedError = 10'000; // 10ms ThreadHoldsWriteLockForTime::SharedData shared_data(kTimeToHold); ThreadHoldsWriteLockForTime thread(&shared_data); thread.Start(); shared_data.signal_write_lock.Take(); // write lock was taken, start timer. - const SbTime start_time = SbTimeGetMonotonicNow(); + const int64_t start_time = CurrentMonotonicTime(); shared_data.rw_lock.AcquireReadLock(); // Blocked by thread for kTimeToHold. shared_data.rw_lock.ReleaseReadLock(); - const SbTime delta_time = SbTimeGetMonotonicNow() - start_time; + const int64_t delta_time = CurrentMonotonicTime() - start_time; thread.Join(); - SbTime time_diff = delta_time - kTimeToHold; + int64_t time_diff = delta_time - kTimeToHold; if (time_diff < 0) { time_diff = -time_diff; } diff --git a/starboard/nplb/semaphore_test.cc b/starboard/nplb/semaphore_test.cc index 76742d8e2835..16a618e9bf37 100644 --- a/starboard/nplb/semaphore_test.cc +++ b/starboard/nplb/semaphore_test.cc @@ -13,6 +13,7 @@ // limitations under the License. #include "starboard/common/semaphore.h" +#include "starboard/common/time.h" #include "starboard/nplb/thread_helpers.h" #include "testing/gtest/include/gtest/gtest.h" @@ -64,16 +65,16 @@ TEST(Semaphore, ThreadTakes) { class ThreadTakesWaitSemaphore : public AbstractTestThread { public: - explicit ThreadTakesWaitSemaphore(SbTime wait_us) + explicit ThreadTakesWaitSemaphore(int64_t wait_us) : thread_started_(false), wait_us_(wait_us), result_signaled_(false), result_wait_time_(0) {} void Run() override { thread_started_ = true; - SbTime start_time = SbTimeGetMonotonicNow(); + int64_t start_time = CurrentMonotonicTime(); result_signaled_ = semaphore_.TakeWait(wait_us_); - result_wait_time_ = SbTimeGetMonotonicNow() - start_time; + result_wait_time_ = CurrentMonotonicTime() - start_time; } // Use a volatile bool to signal when the thread has started executing @@ -81,21 +82,21 @@ class ThreadTakesWaitSemaphore : public AbstractTestThread { // time after signalling the semaphore to return from the Put. volatile bool thread_started_; - SbTime wait_us_; + int64_t wait_us_; Semaphore semaphore_; bool result_signaled_; - SbTime result_wait_time_; + int64_t result_wait_time_; }; TEST(Semaphore, FLAKY_ThreadTakesWait_PutBeforeTimeExpires) { - SbTime timeout_time = kSbTimeMillisecond * 250; - SbTime wait_time = kSbTimeMillisecond; + int64_t timeout_time = 250'000; // 250ms + int64_t wait_time = 1000; // 1ms ThreadTakesWaitSemaphore thread(timeout_time); // Create thread and wait for it to start executing. thread.Start(); while (!thread.thread_started_) { - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); } SbThreadSleep(wait_time); @@ -119,16 +120,16 @@ TEST(Semaphore, ThreadTakesWait_TimeExpires) { const int attempts = 20; // Retest up to 20 times. bool passed = false; - const SbTime kTimeThreshold = kSbTimeMillisecond * 5; + const int64_t kTimeThreshold = 5'000; // 5ms for (int i = 0; i < attempts; ++i) { - SbTime wait_time = kSbTimeMillisecond * 20; + int64_t wait_time = 20'000; // 20ms ThreadTakesWaitSemaphore thread(wait_time); // Create thread and wait for it to start executing. thread.Start(); while (!thread.thread_started_) { - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); } // It is possible for the thread to be preempted just before processing diff --git a/starboard/nplb/socket_accept_test.cc b/starboard/nplb/socket_accept_test.cc index be933db44e4f..fcb34dee9387 100644 --- a/starboard/nplb/socket_accept_test.cc +++ b/starboard/nplb/socket_accept_test.cc @@ -17,7 +17,6 @@ #include "starboard/common/socket.h" #include "starboard/nplb/socket_helpers.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { diff --git a/starboard/nplb/socket_helpers.cc b/starboard/nplb/socket_helpers.cc index 6efecd239fa7..7e75bd4af291 100644 --- a/starboard/nplb/socket_helpers.cc +++ b/starboard/nplb/socket_helpers.cc @@ -19,10 +19,10 @@ #include "starboard/common/scoped_ptr.h" #include "starboard/common/socket.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/once.h" #include "starboard/socket_waiter.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -246,8 +246,8 @@ scoped_ptr CreateConnectingTcpSocketWrapped( } } // namespace -SbSocket AcceptBySpinning(SbSocket server_socket, SbTime timeout) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); +SbSocket AcceptBySpinning(SbSocket server_socket, int64_t timeout) { + int64_t start = CurrentMonotonicTime(); while (true) { SbSocket accepted_socket = SbSocketAccept(server_socket); if (SbSocketIsValid(accepted_socket)) { @@ -258,7 +258,7 @@ SbSocket AcceptBySpinning(SbSocket server_socket, SbTime timeout) { EXPECT_EQ(kSbSocketPending, SbSocketGetLastError(server_socket)); // Check if we have passed our timeout. - if (SbTimeGetMonotonicNow() - start >= timeout) { + if (CurrentMonotonicTime() - start >= timeout) { break; } @@ -269,8 +269,8 @@ SbSocket AcceptBySpinning(SbSocket server_socket, SbTime timeout) { return kSbSocketInvalid; } -scoped_ptr AcceptBySpinning(Socket* server_socket, SbTime timeout) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); +scoped_ptr AcceptBySpinning(Socket* server_socket, int64_t timeout) { + int64_t start = CurrentMonotonicTime(); while (true) { Socket* accepted_socket = server_socket->Accept(); if (accepted_socket && accepted_socket->IsValid()) { @@ -281,7 +281,7 @@ scoped_ptr AcceptBySpinning(Socket* server_socket, SbTime timeout) { EXPECT_TRUE(server_socket->IsPending()); // Check if we have passed our timeout. - if (SbTimeGetMonotonicNow() - start >= timeout) { + if (CurrentMonotonicTime() - start >= timeout) { break; } @@ -295,8 +295,8 @@ scoped_ptr AcceptBySpinning(Socket* server_socket, SbTime timeout) { bool WriteBySpinning(SbSocket socket, const char* data, int data_size, - SbTime timeout) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t timeout) { + int64_t start = CurrentMonotonicTime(); int total = 0; while (total < data_size) { int sent = SbSocketSendTo(socket, data + total, data_size - total, NULL); @@ -309,7 +309,7 @@ bool WriteBySpinning(SbSocket socket, return false; } - if (SbTimeGetMonotonicNow() - start >= timeout) { + if (CurrentMonotonicTime() - start >= timeout) { return false; } @@ -322,8 +322,8 @@ bool WriteBySpinning(SbSocket socket, bool WriteBySpinning(Socket* socket, const char* data, int data_size, - SbTime timeout) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t timeout) { + int64_t start = CurrentMonotonicTime(); int total = 0; while (total < data_size) { int sent = socket->SendTo(data + total, data_size - total, NULL); @@ -336,7 +336,7 @@ bool WriteBySpinning(Socket* socket, return false; } - if (SbTimeGetMonotonicNow() - start >= timeout) { + if (CurrentMonotonicTime() - start >= timeout) { return false; } @@ -349,8 +349,8 @@ bool WriteBySpinning(Socket* socket, bool ReadBySpinning(SbSocket socket, char* out_data, int data_size, - SbTime timeout) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t timeout) { + int64_t start = CurrentMonotonicTime(); int total = 0; while (total < data_size) { int received = @@ -364,7 +364,7 @@ bool ReadBySpinning(SbSocket socket, return false; } - if (SbTimeGetMonotonicNow() - start >= timeout) { + if (CurrentMonotonicTime() - start >= timeout) { return false; } @@ -377,8 +377,8 @@ bool ReadBySpinning(SbSocket socket, bool ReadBySpinning(Socket* socket, char* out_data, int data_size, - SbTime timeout) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t timeout) { + int64_t start = CurrentMonotonicTime(); int total = 0; while (total < data_size) { int received = @@ -392,7 +392,7 @@ bool ReadBySpinning(Socket* socket, return false; } - if (SbTimeGetMonotonicNow() - start >= timeout) { + if (CurrentMonotonicTime() - start >= timeout) { return false; } @@ -477,7 +477,7 @@ int Transfer(Socket* receive_socket, ConnectedTrio CreateAndConnect(SbSocketAddressType server_address_type, SbSocketAddressType client_address_type, int port, - SbTime timeout) { + int64_t timeout) { // Verify the listening socket. SbSocket listen_socket = CreateListeningTcpSocket(server_address_type, port); if (!SbSocketIsValid(listen_socket)) { @@ -494,7 +494,7 @@ ConnectedTrio CreateAndConnect(SbSocketAddressType server_address_type, } // Spin until the accept happens (or we get impatient). - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); SbSocket server_socket = AcceptBySpinning(listen_socket, timeout); if (!SbSocketIsValid(server_socket)) { ADD_FAILURE() << "Failed to accept within " << timeout; @@ -510,7 +510,7 @@ scoped_ptr CreateAndConnectWrapped( SbSocketAddressType server_address_type, SbSocketAddressType client_address_type, int port, - SbTime timeout) { + int64_t timeout) { // Verify the listening socket. scoped_ptr listen_socket = CreateListeningTcpSocketWrapped(server_address_type, port); @@ -528,7 +528,7 @@ scoped_ptr CreateAndConnectWrapped( } // Spin until the accept happens (or we get impatient). - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); scoped_ptr server_socket = AcceptBySpinning(listen_socket.get(), timeout); if (!server_socket || !server_socket->IsValid()) { @@ -540,17 +540,17 @@ scoped_ptr CreateAndConnectWrapped( listen_socket.Pass(), client_socket.Pass(), server_socket.Pass())); } -SbTimeMonotonic TimedWait(SbSocketWaiter waiter) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); +int64_t TimedWait(SbSocketWaiter waiter) { + int64_t start = CurrentMonotonicTime(); SbSocketWaiterWait(waiter); - return SbTimeGetMonotonicNow() - start; + return CurrentMonotonicTime() - start; } // Waits on the given waiter, and returns the elapsed time. -SbTimeMonotonic TimedWaitTimed(SbSocketWaiter waiter, SbTime timeout) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); +int64_t TimedWaitTimed(SbSocketWaiter waiter, int64_t timeout) { + int64_t start = CurrentMonotonicTime(); SbSocketWaiterWaitTimed(waiter, timeout); - return SbTimeGetMonotonicNow() - start; + return CurrentMonotonicTime() - start; } #if !defined(COBALT_BUILD_TYPE_GOLD) diff --git a/starboard/nplb/socket_helpers.h b/starboard/nplb/socket_helpers.h index 4d28134d99cd..53ffcc336f76 100644 --- a/starboard/nplb/socket_helpers.h +++ b/starboard/nplb/socket_helpers.h @@ -22,13 +22,12 @@ #include "starboard/common/scoped_ptr.h" #include "starboard/common/socket.h" #include "starboard/socket_waiter.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { namespace nplb { -const SbTime kSocketTimeout = kSbTimeSecond / 5; +const int64_t kSocketTimeout = 200'000; // 200ms // Returns true if the given address is the unspecified address (all zeros), // supporting both address types. @@ -61,28 +60,28 @@ scoped_ptr CreateListeningTcpSocketWrapped( // Tries to accept a new connection from the given listening socket by checking, // yielding, and retrying for up to timeout. Returns kSbSocketInvalid if no // socket has been accepted in the given time. -SbSocket AcceptBySpinning(SbSocket listen_socket, SbTime timeout); -scoped_ptr AcceptBySpinning(Socket* listen_socket, SbTime timeout); +SbSocket AcceptBySpinning(SbSocket listen_socket, int64_t timeout); +scoped_ptr AcceptBySpinning(Socket* listen_socket, int64_t timeout); // Writes the given data to socket, spinning until success or error. bool WriteBySpinning(SbSocket socket, const char* data, int data_size, - SbTime timeout); + int64_t timeout); bool WriteBySpinning(Socket* socket, const char* data, int data_size, - SbTime timeout); + int64_t timeout); // Reads the given amount of data from socket, spinning until success or error. bool ReadBySpinning(SbSocket socket, char* out_data, int data_size, - SbTime timeout); + int64_t timeout); bool ReadBySpinning(Socket* socket, char* out_data, int data_size, - SbTime timeout); + int64_t timeout); // Transfers data between the two connected local sockets, spinning until |size| // has been transferred, or an error occurs. @@ -132,26 +131,27 @@ struct ConnectedTrioWrapped { ConnectedTrio CreateAndConnect(SbSocketAddressType server_address_type, SbSocketAddressType client_address_type, int port, - SbTime timeout); + int64_t timeout); scoped_ptr CreateAndConnectWrapped( SbSocketAddressType server_address_type, SbSocketAddressType client_address_type, int port, - SbTime timeout); + int64_t timeout); -// Waits on the given waiter, and returns the elapsed time. -SbTimeMonotonic TimedWait(SbSocketWaiter waiter); +// Waits on the given waiter, and returns the elapsed time in microseconds. +int64_t TimedWait(SbSocketWaiter waiter); -// Waits on the given waiter, and returns the elapsed time. -SbTimeMonotonic TimedWaitTimed(SbSocketWaiter waiter, SbTime timeout); +// Waits on the given waiter, and returns the elapsed time in microseconds. +int64_t TimedWaitTimed(SbSocketWaiter waiter, int64_t timeout); -// Waits on the given waiter, and checks that it blocked between [lower, upper). +// Waits on the given waiter, and checks that it blocked between +// [lower_usec, upper_usec). static inline void WaitShouldBlockBetween(SbSocketWaiter waiter, - SbTime lower, - SbTime upper) { - SbTime time = TimedWait(waiter); - EXPECT_GT(upper, time); - EXPECT_LE(lower, time); + int64_t lower_usec, + int64_t upper_usec) { + int64_t time = TimedWait(waiter); + EXPECT_GT(upper_usec, time); + EXPECT_LE(lower_usec, time); } // Waits on the given waiter, and checks that it did not block for very long. @@ -162,13 +162,14 @@ static inline void WaitShouldNotBlock(SbSocketWaiter waiter) { // Waits on the given waiter, and checks that it did not block for the given // timeout. static inline void TimedWaitShouldNotBlock(SbSocketWaiter waiter, - SbTime timeout) { + int64_t timeout) { EXPECT_GT(timeout, TimedWaitTimed(waiter, timeout)); } // Waits on the given waiter, and checks that it did block for at least the // given timeout. -static inline void TimedWaitShouldBlock(SbSocketWaiter waiter, SbTime timeout) { +static inline void TimedWaitShouldBlock(SbSocketWaiter waiter, + int64_t timeout) { EXPECT_LE(timeout, TimedWaitTimed(waiter, timeout)); } diff --git a/starboard/nplb/socket_is_connected_and_idle_test.cc b/starboard/nplb/socket_is_connected_and_idle_test.cc index 3a16795b8393..32c75760569e 100644 --- a/starboard/nplb/socket_is_connected_and_idle_test.cc +++ b/starboard/nplb/socket_is_connected_and_idle_test.cc @@ -16,6 +16,7 @@ #include "starboard/common/log.h" #include "starboard/common/socket.h" +#include "starboard/common/time.h" #include "starboard/nplb/socket_helpers.h" #include "starboard/thread.h" #include "testing/gtest/include/gtest/gtest.h" @@ -38,9 +39,9 @@ class PairSbSocketIsConnectedAndIdleTest SbSocketAddressType GetClientAddressType() { return GetParam().second; } }; -bool IsNonIdleWithin(SbSocket socket, SbTimeMonotonic timeout) { - SbTimeMonotonic deadline = SbTimeGetMonotonicNow() + timeout; - while (SbTimeGetMonotonicNow() < deadline) { +bool IsNonIdleWithin(SbSocket socket, int64_t timeout) { + int64_t deadline = CurrentMonotonicTime() + timeout; + while (CurrentMonotonicTime() < deadline) { if (!SbSocketIsConnectedAndIdle(socket)) { return true; } diff --git a/starboard/nplb/socket_join_multicast_group_test.cc b/starboard/nplb/socket_join_multicast_group_test.cc index f31fd0fcfc54..7a2a64653f87 100644 --- a/starboard/nplb/socket_join_multicast_group_test.cc +++ b/starboard/nplb/socket_join_multicast_group_test.cc @@ -13,9 +13,9 @@ // limitations under the License. #include "starboard/common/socket.h" +#include "starboard/common/time.h" #include "starboard/nplb/socket_helpers.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -83,16 +83,16 @@ TEST(SbSocketJoinMulticastGroupTest, SunnyDay) { } SbSocketAddress receive_address; - SbTimeMonotonic stop_time = SbTimeGetMonotonicNow() + kSbTimeSecond; + int64_t stop_time = CurrentMonotonicTime() + 1'000'000LL; while (true) { // Breaks the case where the test will hang in a loop when // SbSocketReceiveFrom() always returns kSbSocketPending. - ASSERT_LE(SbTimeGetMonotonicNow(), stop_time) << "Multicast timed out."; + ASSERT_LE(CurrentMonotonicTime(), stop_time) << "Multicast timed out."; int received = SbSocketReceiveFrom( receive_socket, buf, SB_ARRAY_SIZE_INT(buf), &receive_address); if (received < 0 && SbSocketGetLastError(receive_socket) == kSbSocketPending) { - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); continue; } EXPECT_EQ(SB_ARRAY_SIZE_INT(kBuf), received); diff --git a/starboard/nplb/socket_receive_from_test.cc b/starboard/nplb/socket_receive_from_test.cc index b9deb062ac22..1fc8a54ea7c3 100644 --- a/starboard/nplb/socket_receive_from_test.cc +++ b/starboard/nplb/socket_receive_from_test.cc @@ -16,7 +16,6 @@ #include "starboard/common/socket.h" #include "starboard/nplb/socket_helpers.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { diff --git a/starboard/nplb/socket_send_to_test.cc b/starboard/nplb/socket_send_to_test.cc index f0be4d56d065..7d9ac32d081c 100644 --- a/starboard/nplb/socket_send_to_test.cc +++ b/starboard/nplb/socket_send_to_test.cc @@ -18,10 +18,10 @@ #include #include "starboard/common/socket.h" +#include "starboard/common/time.h" #include "starboard/memory.h" #include "starboard/nplb/socket_helpers.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -48,13 +48,13 @@ void* SendToServerSocketEntryPoint(void* trio_as_void_ptr) { // Continue sending to the socket until it fails to send. It's expected that // SbSocketSendTo will fail when the server socket closes, but the application // should not terminate. - SbTime start = SbTimeGetMonotonicNow(); - SbTime now = start; - SbTime kTimeout = kSbTimeSecond; + int64_t start = CurrentMonotonicTime(); + int64_t now = start; + int64_t kTimeout = 1'000'000; // 1 second int result = 0; while (result >= 0 && (now - start < kTimeout)) { result = SbSocketSendTo(trio->server_socket, send_buf, kBufSize, NULL); - now = SbTimeGetMonotonicNow(); + now = CurrentMonotonicTime(); } delete[] send_buf; @@ -169,7 +169,7 @@ TEST_P(PairSbSocketSendToTest, RainyDaySendToSocketConnectionReset) { int kNumRetries = 1000; for (int i = 0; i < kNumRetries; ++i) { char buff[kChunkSize] = {}; - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); int result = trio->client_socket->SendTo(buff, sizeof(buff), NULL); if (result < 0) { diff --git a/starboard/nplb/socket_set_options_test.cc b/starboard/nplb/socket_set_options_test.cc index b871de692e2a..603be92c5983 100644 --- a/starboard/nplb/socket_set_options_test.cc +++ b/starboard/nplb/socket_set_options_test.cc @@ -14,7 +14,6 @@ #include "starboard/common/socket.h" #include "starboard/nplb/socket_helpers.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -33,7 +32,7 @@ TEST_P(SbSocketSetOptionsTest, TryThemAllTCP) { EXPECT_TRUE(SbSocketSetReuseAddress(socket, true)); EXPECT_TRUE(SbSocketSetReceiveBufferSize(socket, 16 * 1024)); EXPECT_TRUE(SbSocketSetSendBufferSize(socket, 16 * 1024)); - EXPECT_TRUE(SbSocketSetTcpKeepAlive(socket, true, 30 * kSbTimeSecond)); + EXPECT_TRUE(SbSocketSetTcpKeepAlive(socket, true, 30'000'000)); EXPECT_TRUE(SbSocketSetTcpNoDelay(socket, true)); // Returns false on unsupported platforms, so we can't check the return value @@ -58,8 +57,7 @@ TEST_P(SbSocketSetOptionsTest, RainyDayInvalidSocket) { EXPECT_FALSE(SbSocketSetReuseAddress(kSbSocketInvalid, true)); EXPECT_FALSE(SbSocketSetReceiveBufferSize(kSbSocketInvalid, 16 * 1024)); EXPECT_FALSE(SbSocketSetSendBufferSize(kSbSocketInvalid, 16 * 1024)); - EXPECT_FALSE( - SbSocketSetTcpKeepAlive(kSbSocketInvalid, true, 30 * kSbTimeSecond)); + EXPECT_FALSE(SbSocketSetTcpKeepAlive(kSbSocketInvalid, true, 30'000'000)); EXPECT_FALSE(SbSocketSetTcpNoDelay(kSbSocketInvalid, true)); EXPECT_FALSE(SbSocketSetTcpWindowScaling(kSbSocketInvalid, true)); } diff --git a/starboard/nplb/socket_waiter_wait_test.cc b/starboard/nplb/socket_waiter_wait_test.cc index 5e94c549d70c..373880879305 100644 --- a/starboard/nplb/socket_waiter_wait_test.cc +++ b/starboard/nplb/socket_waiter_wait_test.cc @@ -20,7 +20,6 @@ #include "starboard/nplb/thread_helpers.h" #include "starboard/socket_waiter.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { diff --git a/starboard/nplb/socket_waiter_wait_timed_test.cc b/starboard/nplb/socket_waiter_wait_timed_test.cc index 692454d72b2e..1d7926ca4506 100644 --- a/starboard/nplb/socket_waiter_wait_timed_test.cc +++ b/starboard/nplb/socket_waiter_wait_timed_test.cc @@ -18,7 +18,6 @@ #include "starboard/common/socket.h" #include "starboard/nplb/socket_helpers.h" #include "starboard/socket_waiter.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { diff --git a/starboard/nplb/socket_waiter_wake_up_test.cc b/starboard/nplb/socket_waiter_wake_up_test.cc index 9d43a269fe54..4295ff645d25 100644 --- a/starboard/nplb/socket_waiter_wake_up_test.cc +++ b/starboard/nplb/socket_waiter_wake_up_test.cc @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "starboard/common/time.h" #include "starboard/nplb/socket_helpers.h" #include "starboard/nplb/thread_helpers.h" #include "starboard/socket_waiter.h" @@ -125,10 +126,10 @@ TEST(SbSocketWaiterWakeUpTest, CallFromOtherThreadWakesUp) { context.waiter = waiter; SbThread thread = Spawn(&context, &WakeUpSleepEntryPoint); - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); context.semaphore.Put(); TimedWait(waiter); - SbTimeMonotonic duration = SbTimeGetMonotonicNow() - start; + int64_t duration = CurrentMonotonicTime() - start; EXPECT_GT(kSocketTimeout * 2, duration); EXPECT_LE(kSocketTimeout, duration); Join(thread); diff --git a/starboard/nplb/socket_wrapper_test.cc b/starboard/nplb/socket_wrapper_test.cc index 9d2c442eda98..759c704f48f1 100644 --- a/starboard/nplb/socket_wrapper_test.cc +++ b/starboard/nplb/socket_wrapper_test.cc @@ -16,7 +16,6 @@ #include "starboard/common/socket.h" #include "starboard/nplb/socket_helpers.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { diff --git a/starboard/nplb/system_get_path_test.cc b/starboard/nplb/system_get_path_test.cc index e3207371606d..3f2b2cdaa8d9 100644 --- a/starboard/nplb/system_get_path_test.cc +++ b/starboard/nplb/system_get_path_test.cc @@ -18,11 +18,11 @@ #include "starboard/common/file.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/memory.h" #include "starboard/nplb/file_helpers.h" #include "starboard/system.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -206,7 +206,7 @@ TEST(SbSystemGetPath, ExecutableFileCreationTimeIsSound) { result = SbFileGetPathInfo(path.data(), &executable_file_info); ASSERT_TRUE(result); - SbTime now = SbTimeGetNow(); + int64_t now = PosixTimeToWindowsTime(CurrentPosixTime()); EXPECT_GT(now, executable_file_info.creation_time); } diff --git a/starboard/nplb/thread_helpers.h b/starboard/nplb/thread_helpers.h index c3851f90e949..709613062799 100644 --- a/starboard/nplb/thread_helpers.h +++ b/starboard/nplb/thread_helpers.h @@ -20,7 +20,6 @@ #include "starboard/common/semaphore.h" #include "starboard/configuration.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "starboard/types.h" #include "testing/gtest/include/gtest/gtest.h" @@ -143,7 +142,7 @@ struct TakeThenSignalContext { TestSemaphore do_signal; SbMutex mutex; SbConditionVariable condition; - SbTime delay_after_signal; + int64_t delay_after_signal; }; // AbstractTestThread that is a bare bones class wrapper around Starboard diff --git a/starboard/nplb/thread_join_test.cc b/starboard/nplb/thread_join_test.cc index d15007994d54..eeb63a0c24c9 100644 --- a/starboard/nplb/thread_join_test.cc +++ b/starboard/nplb/thread_join_test.cc @@ -38,7 +38,7 @@ TEST(SbThreadLocalValueTest, ThreadJoinWaitsForFunctionRun) { struct LocalStatic { static void* ThreadEntryPoint(void* input) { int* value = static_cast(input); - static const SbTime kSleepTime = 10 * kSbTimeMillisecond; // 10 ms. + static const int64_t kSleepTime = 10'000; // 10 ms. // Wait to write the value to increase likelihood of catching // a race condition. SbThreadSleep(kSleepTime); diff --git a/starboard/nplb/thread_sampler_test.cc b/starboard/nplb/thread_sampler_test.cc index 2a4aa7aa2cff..204bbde0702d 100644 --- a/starboard/nplb/thread_sampler_test.cc +++ b/starboard/nplb/thread_sampler_test.cc @@ -13,9 +13,9 @@ // limitations under the License. #include "starboard/common/atomic.h" +#include "starboard/common/time.h" #include "starboard/nplb/thread_helpers.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -29,7 +29,7 @@ class CountingThread : public AbstractTestThread { void Run() override { while (!stop_.load()) { counter_.increment(); - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); } } @@ -40,10 +40,10 @@ class CountingThread : public AbstractTestThread { int32_t GetCount() { return counter_.load(); } - bool IsCounting(SbTime timeout) { + bool IsCounting(int64_t timeout) { int32_t end_count = GetCount() + 2; - SbTime end_time = SbTimeGetNow() + timeout; - while (SbTimeGetNow() < end_time) { + int64_t end_time = CurrentPosixTime() + timeout; + while (CurrentPosixTime() < end_time) { if (GetCount() >= end_count) return true; SbThreadYield(); @@ -117,15 +117,15 @@ TEST(ThreadSamplerTest, SunnyDayThreadFreeze) { EXPECT_TRUE(SbThreadSamplerIsValid(sampler)); // Check that the thread is counting, with a long timeout to avoid flakiness. - EXPECT_TRUE(counting_thread.IsCounting(4 * kSbTimeSecond)); + EXPECT_TRUE(counting_thread.IsCounting(4'000'000)); // Check that the thread stops counting when frozen. EXPECT_NE(kSbThreadContextInvalid, SbThreadSamplerFreeze(sampler)); - EXPECT_FALSE(counting_thread.IsCounting(100 * kSbTimeMillisecond)); + EXPECT_FALSE(counting_thread.IsCounting(100'000)); // Check that the thread is counting again when thawed. EXPECT_TRUE(SbThreadSamplerThaw(sampler)); - EXPECT_TRUE(counting_thread.IsCounting(4 * kSbTimeSecond)); + EXPECT_TRUE(counting_thread.IsCounting(4'000'000)); SbThreadSamplerDestroy(sampler); } @@ -144,7 +144,7 @@ TEST(ThreadSamplerTest, SunnyDayThreadContextPointers) { // Wait until the thread is counting before freezing it so that we know it's // in a valid stack frame. - EXPECT_TRUE(counting_thread.IsCounting(4 * kSbTimeSecond)); + EXPECT_TRUE(counting_thread.IsCounting(4'000'000)); SbThreadContext ctx = SbThreadSamplerFreeze(sampler); EXPECT_TRUE(SbThreadContextIsValid(ctx)); diff --git a/starboard/nplb/thread_sleep_test.cc b/starboard/nplb/thread_sleep_test.cc index fd04c9b056a5..cdbd906a0bd9 100644 --- a/starboard/nplb/thread_sleep_test.cc +++ b/starboard/nplb/thread_sleep_test.cc @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "starboard/common/time.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -21,7 +21,7 @@ namespace nplb { namespace { // Allow millisecond-level precision. -const SbTime kPrecision = kSbTimeMillisecond; +const int64_t kPrecision = 1000; // 1ms TEST(SbThreadSleepTest, SunnyDay) { SbThreadSleep(0); @@ -36,10 +36,10 @@ TEST(SbThreadSleepTest, SunnyDayAtLeastDelay) { const int64_t one = 1; for (int trial = 0; trial < kTrials; ++trial) { // This tests several delays, between about 15 to about 4 milliseconds. - const SbTime kDelay = kSbTimeSecond / (one << ((trial % 3) + 6)); - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + const int64_t kDelay = 1'000'000LL / (one << ((trial % 3) + 6)); + int64_t start = CurrentMonotonicTime(); SbThreadSleep(kDelay); - SbTimeMonotonic end = SbTimeGetMonotonicNow(); + int64_t end = CurrentMonotonicTime(); EXPECT_LE(start + kDelay, end + kPrecision) << "Trial " << trial << ", kDelay=" << kDelay; } @@ -48,10 +48,9 @@ TEST(SbThreadSleepTest, SunnyDayAtLeastDelay) { TEST(SbThreadSleepTest, RainyDayNegativeDuration) { const int kTrials = 128; for (int trial = 0; trial < kTrials; ++trial) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); - SbThreadSleep(-kSbTimeSecond); - EXPECT_GT(kSbTimeSecond / 5, SbTimeGetMonotonicNow() - start) - << "Trial " << trial; + int64_t start = CurrentMonotonicTime(); + SbThreadSleep(-1'000'000); + EXPECT_GT(200'000, CurrentMonotonicTime() - start) << "Trial " << trial; } } diff --git a/starboard/nplb/thread_test.cc b/starboard/nplb/thread_test.cc index dc4f8de8499f..7a45baa1c0f4 100644 --- a/starboard/nplb/thread_test.cc +++ b/starboard/nplb/thread_test.cc @@ -28,7 +28,7 @@ class TestRunThread : public Thread { TestRunThread() : Thread("TestThread"), finished_(false) {} void Run() override { - while (!WaitForJoin(kSbTimeMillisecond)) { + while (!WaitForJoin(1000)) { } finished_.store(true); } diff --git a/starboard/nplb/thread_yield_test.cc b/starboard/nplb/thread_yield_test.cc index b93c8aa487b6..b81b2ddbe4dd 100644 --- a/starboard/nplb/thread_yield_test.cc +++ b/starboard/nplb/thread_yield_test.cc @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "starboard/common/time.h" #include "starboard/nplb/thread_helpers.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -35,8 +35,8 @@ void* YieldingEntryPoint(void* context) { SbThreadYield(); } - SbTimeMonotonic* end_time = static_cast(context); - *end_time = SbTimeGetMonotonicNow(); + int64_t* end_time = static_cast(context); + *end_time = CurrentMonotonicTime(); return NULL; } @@ -45,8 +45,8 @@ void* UnyieldingEntryPoint(void* context) { DoNotYield(); } - SbTimeMonotonic* end_time = static_cast(context); - *end_time = SbTimeGetMonotonicNow(); + int64_t* end_time = static_cast(context); + *end_time = CurrentMonotonicTime(); return NULL; } @@ -76,7 +76,7 @@ TEST(SbThreadYieldTest, SunnyDayRace) { // and enough data for the averages to be consistently divergent. const int64_t kRacers = 32; SbThread threads[kRacers]; - SbTimeMonotonic end_times[kRacers] = {0}; + int64_t end_times[kRacers] = {0}; for (int i = 0; i < kRacers; ++i) { threads[i] = SbThreadCreate( 0, kSbThreadNoPriority, affinity, true, NULL, @@ -93,8 +93,8 @@ TEST(SbThreadYieldTest, SunnyDayRace) { } // On average, Unyielders should finish sooner than Yielders. - SbTimeMonotonic average_yielder = 0; - SbTimeMonotonic average_unyielder = 0; + int64_t average_yielder = 0; + int64_t average_unyielder = 0; const int64_t kRacersPerGroup = kRacers / 2; for (int i = 0; i < kRacers; ++i) { if (IsYielder(trial, i)) { diff --git a/starboard/nplb/time_constants.h b/starboard/nplb/time_constants.h index 5802331c1948..348424741e14 100644 --- a/starboard/nplb/time_constants.h +++ b/starboard/nplb/time_constants.h @@ -15,6 +15,8 @@ #ifndef STARBOARD_NPLB_TIME_CONSTANTS_H_ #define STARBOARD_NPLB_TIME_CONSTANTS_H_ +#if SB_API_VERSION < 16 + #include "starboard/time.h" namespace starboard { @@ -60,4 +62,6 @@ static const SbTime kTestTimePastWritten = } // namespace nplb } // namespace starboard +#endif // SB_API_VERSION < 16 + #endif // STARBOARD_NPLB_TIME_CONSTANTS_H_ diff --git a/starboard/nplb/time_get_monotonic_now_test.cc b/starboard/nplb/time_get_monotonic_now_test.cc index 2b5f16c08fa9..d984ecd77b1d 100644 --- a/starboard/nplb/time_get_monotonic_now_test.cc +++ b/starboard/nplb/time_get_monotonic_now_test.cc @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if SB_API_VERSION < 16 + #include "starboard/nplb/time_constants.h" #include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" @@ -50,3 +52,5 @@ TEST(SbTimeGetMonotonicNowTest, IsMonotonic) { } // namespace } // namespace nplb } // namespace starboard + +#endif // SB_API_VERSION < 16 diff --git a/starboard/nplb/time_get_now_test.cc b/starboard/nplb/time_get_now_test.cc index 093383fd49c6..32d9f4265e11 100644 --- a/starboard/nplb/time_get_now_test.cc +++ b/starboard/nplb/time_get_now_test.cc @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if SB_API_VERSION < 16 + #include "starboard/nplb/time_constants.h" #include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" @@ -58,3 +60,5 @@ TEST(SbTimeGetNowTest, HasDecentResolution) { } // namespace } // namespace nplb } // namespace starboard + +#endif // SB_API_VERSION < 16 diff --git a/starboard/nplb/time_narrow_test.cc b/starboard/nplb/time_narrow_test.cc index 4d5feb266bc0..ee6f3233bd12 100644 --- a/starboard/nplb/time_narrow_test.cc +++ b/starboard/nplb/time_narrow_test.cc @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if SB_API_VERSION < 16 + #include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" @@ -37,3 +39,5 @@ TEST(SbTimeNarrowTest, SunnyDay) { } // namespace } // namespace nplb } // namespace starboard + +#endif // SB_API_VERSION < 16 diff --git a/starboard/nplb/time_test.cc b/starboard/nplb/time_test.cc new file mode 100644 index 000000000000..2acd233a7b8f --- /dev/null +++ b/starboard/nplb/time_test.cc @@ -0,0 +1,80 @@ +// Copyright 2024 The Cobalt Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "starboard/common/time.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace starboard { +namespace nplb { +namespace { + +TEST(TimeTest, PosixTimeIsKindOfSane) { + int64_t now_usec = CurrentPosixTime(); + + // Now should be after 2024-01-01 UTC (the past). + int64_t past_usec = 1704067200000000LL; + EXPECT_GT(time, past_usec); + + // Now should be before 2044-01-01 UTC (the future). + int64_t future_usec = 2335219200000000LL; + EXPECT_LT(time, future_usec); +} + +TEST(TimeTest, HasDecentResolution) { + const int kNumIterations = 100; + for (int i = 0; i < kNumIterations; ++i) { + int64_t timerStart = CurrentMonotonicTime(); + int64_t initialTime = CurrentPosixTime(); + + // Spin tightly until time increments. + while (CurrentPosixTime() == initialTime) { + // If time hasn't changed within a second, that's beyond low resolution. + if ((CurrentMonotonicTime() - timerStart) >= 1'000'000) { + GTEST_FAIL() << "CurrentPosixTime() hasn't changed within a second."; + break; + } + } + } +} + +TEST(TimeTest, MonotonickIsMonotonic) { + const int kTrials = 100; + for (int trial = 0; trial < kTrials; ++trial) { + int64_t timerStart = CurrentPosixTime(); + int64_t initialMonotonic = CurrentMonotonicTime(); + + // Spin tightly until time changes. + int64_t newMonotonic = 0; + while (true) { + newMonotonic = CurrentMonotonicTime(); + if (initialMonotonic != newMonotonic) { + EXPECT_GT(newMonotonic, initialMonotonic); + EXPECT_LT(newMonotonic - initialMonotonic, 1'000'000); // Less than 1s + return; + } + + // If time hasn't increased within a second, our "high-resolution" + // monotonic timer is broken. + if (CurrentPosixTime() - timerStart >= 1'000'000) { + GTEST_FAIL() << "CurrentMonotonicTime() hasn't changed within a " + << "second."; + return; + } + } + } +} + +} // namespace +} // namespace nplb +} // namespace starboard diff --git a/starboard/nplb/time_zone_get_current_test.cc b/starboard/nplb/time_zone_get_current_test.cc index 0c2b3b86d646..b18d5de27641 100644 --- a/starboard/nplb/time_zone_get_current_test.cc +++ b/starboard/nplb/time_zone_get_current_test.cc @@ -13,7 +13,6 @@ // limitations under the License. #include "starboard/extension/time_zone.h" -#include "starboard/nplb/time_constants.h" #include "starboard/system.h" #include "starboard/time_zone.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/starboard/nplb/time_zone_get_name_test.cc b/starboard/nplb/time_zone_get_name_test.cc index 318cbfc60b61..5e3cbb699709 100644 --- a/starboard/nplb/time_zone_get_name_test.cc +++ b/starboard/nplb/time_zone_get_name_test.cc @@ -16,7 +16,6 @@ #include "starboard/common/log.h" #include "starboard/extension/time_zone.h" -#include "starboard/nplb/time_constants.h" #include "starboard/system.h" #include "starboard/time_zone.h" #include "testing/gmock/include/gmock/gmock.h" diff --git a/starboard/nplb/vertical_video_test.cc b/starboard/nplb/vertical_video_test.cc index 5427aeb2bfeb..f02b87fcf610 100644 --- a/starboard/nplb/vertical_video_test.cc +++ b/starboard/nplb/vertical_video_test.cc @@ -23,7 +23,6 @@ #include "starboard/player.h" #include "starboard/shared/starboard/player/video_dmp_reader.h" #include "starboard/testing/fake_graphics_context_provider.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -130,10 +129,10 @@ TEST_P(VerticalVideoTest, WriteSamples) { SB_DCHECK(player_fixture.HasVideo()); SB_DCHECK(player_fixture.HasAudio()); - int audio_samples_to_write = player_fixture.ConvertDurationToAudioBufferCount( - 200 * kSbTimeMillisecond); - int video_samples_to_write = player_fixture.ConvertDurationToVideoBufferCount( - 200 * kSbTimeMillisecond); + int audio_samples_to_write = + player_fixture.ConvertDurationToAudioBufferCount(200'000); + int video_samples_to_write = + player_fixture.ConvertDurationToVideoBufferCount(200'000); GroupedSamples samples; samples.AddVideoSamples(0, audio_samples_to_write); diff --git a/starboard/player.h b/starboard/player.h index 0d3c85a4a41c..32347f67a1e0 100644 --- a/starboard/player.h +++ b/starboard/player.h @@ -25,7 +25,6 @@ #include "starboard/drm.h" #include "starboard/export.h" #include "starboard/media.h" -#include "starboard/time.h" #include "starboard/types.h" #include "starboard/window.h" @@ -171,8 +170,8 @@ typedef struct SbPlayerSampleInfo { const void* buffer; // Size of the data pointed to by |buffer|. int buffer_size; - // The timestamp of the sample in SbTime. - SbTime timestamp; + // The timestamp of the sample in microseconds since Windows epoch UTC. + int64_t timestamp; // Points to an array of side data for the input, when available. SbPlayerSampleSideData* side_data; @@ -202,14 +201,14 @@ typedef struct SbPlayerInfo2 { #endif // SB_API_VERSION >= 15 // The position of the playback head, as precisely as possible, in // microseconds. - SbTime current_media_timestamp; + int64_t current_media_timestamp; // The known duration of the currently playing media stream, in microseconds. - SbTime duration; + int64_t duration; // The result of getStartDate for the currently playing media stream, in // microseconds since the epoch of January 1, 1601 UTC. - SbTime start_date; + int64_t start_date; // The width of the currently displayed frame, in pixels, or 0 if not provided // by this player. @@ -314,11 +313,11 @@ typedef void (*SbPlayerDeallocateSampleFunc)(SbPlayer player, #if SB_API_VERSION >= 15 // The audio write duration when all the audio connectors are local. -#define kSbPlayerWriteDurationLocal (kSbTimeSecond / 2) +#define kSbPlayerWriteDurationLocal (1000000 / 2) // 0.5 seconds // The audio write duration when at least one of the audio connectors are // remote. -#define kSbPlayerWriteDurationRemote (kSbTimeSecond * 10) +#define kSbPlayerWriteDurationRemote (1000000 * 10) // 10 seconds #endif // SB_API_VERSION >= 15 @@ -498,11 +497,11 @@ SB_EXPORT void SbPlayerDestroy(SbPlayer player); #if SB_API_VERSION >= 15 SB_EXPORT void SbPlayerSeek(SbPlayer player, - SbTime seek_to_timestamp, + int64_t seek_to_timestamp, int ticket); #else // SB_API_VERSION >= 15 SB_EXPORT void SbPlayerSeek2(SbPlayer player, - SbTime seek_to_timestamp, + int64_t seek_to_timestamp, int ticket); #endif // SB_API_VERSION >= 15 diff --git a/starboard/raspi/shared/application_dispmanx.cc b/starboard/raspi/shared/application_dispmanx.cc index 5424fd1ec8a7..ffa067109d5d 100644 --- a/starboard/raspi/shared/application_dispmanx.cc +++ b/starboard/raspi/shared/application_dispmanx.cc @@ -26,9 +26,7 @@ #include "starboard/memory.h" #include "starboard/raspi/shared/window_internal.h" #include "starboard/shared/linux/dev_input/dev_input.h" -#include "starboard/shared/posix/time_internal.h" #include "starboard/shared/starboard/audio_sink/audio_sink_internal.h" -#include "starboard/time.h" namespace starboard { namespace raspi { @@ -119,7 +117,7 @@ ApplicationDispmanx::PollNextSystemEvent() { } ::starboard::shared::starboard::Application::Event* -ApplicationDispmanx::WaitForSystemEventWithTimeout(SbTime duration) { +ApplicationDispmanx::WaitForSystemEventWithTimeout(int64_t duration) { SB_DCHECK(input_); Event* event = input_->WaitForSystemEventWithTimeout(duration); return event; diff --git a/starboard/raspi/shared/application_dispmanx.h b/starboard/raspi/shared/application_dispmanx.h index 4ef9a48af2cf..653ddbf76d78 100644 --- a/starboard/raspi/shared/application_dispmanx.h +++ b/starboard/raspi/shared/application_dispmanx.h @@ -68,7 +68,7 @@ class ApplicationDispmanx // --- QueueApplication overrides --- bool MayHaveSystemEvents() override; Event* PollNextSystemEvent() override; - Event* WaitForSystemEventWithTimeout(SbTime duration) override; + Event* WaitForSystemEventWithTimeout(int64_t duration) override; void WakeSystemEventWait() override; bool IsStartImmediate() override { return !HasPreloadSwitch(); } diff --git a/starboard/raspi/shared/dispmanx_util.h b/starboard/raspi/shared/dispmanx_util.h index 5646d24bc8fc..c7c4b8752df8 100644 --- a/starboard/raspi/shared/dispmanx_util.h +++ b/starboard/raspi/shared/dispmanx_util.h @@ -149,7 +149,7 @@ class DispmanxElement { class DispmanxVideoFrame : public starboard::shared::starboard::player::filter::VideoFrame { public: - DispmanxVideoFrame(SbTime time, + DispmanxVideoFrame(int64_t time, DispmanxYUV420Resource* resource, std::function release_cb) : VideoFrame(time), resource_(resource), release_cb_(release_cb) { diff --git a/starboard/raspi/shared/open_max/open_max_component.cc b/starboard/raspi/shared/open_max/open_max_component.cc index 6a19725eae4a..3bd26619ae23 100644 --- a/starboard/raspi/shared/open_max/open_max_component.cc +++ b/starboard/raspi/shared/open_max/open_max_component.cc @@ -83,7 +83,7 @@ void OpenMaxComponent::Flush() { int OpenMaxComponent::WriteData(const void* data, int size, DataType type, - SbTime timestamp) { + int64_t timestamp) { int offset = 0; while (offset < size) { diff --git a/starboard/raspi/shared/open_max/open_max_component.h b/starboard/raspi/shared/open_max/open_max_component.h index 6ca5c49fef8f..8dc797b2534a 100644 --- a/starboard/raspi/shared/open_max/open_max_component.h +++ b/starboard/raspi/shared/open_max/open_max_component.h @@ -22,7 +22,6 @@ #include "starboard/common/mutex.h" #include "starboard/raspi/shared/open_max/open_max_component_base.h" #include "starboard/shared/internal_only.h" -#include "starboard/time.h" namespace starboard { namespace raspi { @@ -53,7 +52,7 @@ class OpenMaxComponent : protected OpenMaxComponentBase { // Write data to the input buffer. Returns the number of bytes written or // -1 if an error occurred. // This will return immediately once no more buffers are available. - int WriteData(const void* data, int size, DataType type, SbTime timestamp); + int WriteData(const void* data, int size, DataType type, int64_t timestamp); // Write an empty buffer that is flagged as the end of the input stream. // This will block until a buffer is available. diff --git a/starboard/raspi/shared/open_max/open_max_image_decode_component.cc b/starboard/raspi/shared/open_max/open_max_image_decode_component.cc index 8556b32659aa..a2c1fe0cca96 100644 --- a/starboard/raspi/shared/open_max/open_max_image_decode_component.cc +++ b/starboard/raspi/shared/open_max/open_max_image_decode_component.cc @@ -16,6 +16,7 @@ #include +#include "starboard/common/time.h" #include "starboard/configuration.h" #include "starboard/memory.h" #include "starboard/raspi/shared/open_max/decode_target_create.h" @@ -85,7 +86,7 @@ SbDecodeTarget OpenMaxImageDecodeComponent::Decode( if (write_size > 0) { write_size = WriteData(reinterpret_cast(data) + data_size_written, - write_size, kDataEOS, SbTimeGetMonotonicNow()); + write_size, kDataEOS, CurrentMonotonicTime()); SB_DCHECK(write_size >= 0); data_size_written += write_size; } @@ -94,7 +95,7 @@ SbDecodeTarget OpenMaxImageDecodeComponent::Decode( break; } else if (write_size == 0 && output_size == 0) { // Wait for buffers to become available. - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); } } diff --git a/starboard/raspi/shared/open_max/video_decoder.cc b/starboard/raspi/shared/open_max/video_decoder.cc index e2afc3858adb..32e411cc02ac 100644 --- a/starboard/raspi/shared/open_max/video_decoder.cc +++ b/starboard/raspi/shared/open_max/video_decoder.cc @@ -14,8 +14,6 @@ #include "starboard/raspi/shared/open_max/video_decoder.h" -#include "starboard/time.h" - namespace starboard { namespace raspi { namespace shared { @@ -27,7 +25,7 @@ using std::placeholders::_1; const size_t kResourcePoolSize = 26; // TODO: Make this configurable inside SbPlayerCreate(). -const SbTimeMonotonic kUpdateInterval = 5 * kSbTimeMillisecond; +const int64_t kUpdateIntervalUsec = 5'000; } // namespace @@ -38,7 +36,7 @@ VideoDecoder::VideoDecoder(SbMediaVideoCodec video_codec) request_thread_termination_(false) { SB_DCHECK(video_codec == kSbMediaVideoCodecH264); update_job_ = std::bind(&VideoDecoder::Update, this); - update_job_token_ = Schedule(update_job_, kUpdateInterval); + update_job_token_ = Schedule(update_job_, kUpdateIntervalUsec); } VideoDecoder::~VideoDecoder() { @@ -79,7 +77,7 @@ void VideoDecoder::WriteInputBuffers(const InputBuffers& input_buffers) { const auto& input_buffer = input_buffers[0]; queue_.Put(new Event(input_buffer)); if (!TryToDeliverOneFrame()) { - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); // Call the callback with NULL frame to ensure that the host knows that // more data is expected. decoder_status_cb_(kNeedMoreInput, NULL); @@ -108,7 +106,7 @@ void VideoDecoder::Update() { if (eos_written_) { TryToDeliverOneFrame(); } - update_job_token_ = Schedule(update_job_, kUpdateInterval); + update_job_token_ = Schedule(update_job_, kUpdateIntervalUsec); } bool VideoDecoder::TryToDeliverOneFrame() { @@ -187,7 +185,7 @@ void VideoDecoder::RunLoop() { current_buffer = NULL; offset = 0; } else { - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); continue; } } @@ -196,7 +194,7 @@ void VideoDecoder::RunLoop() { eos_written = component.WriteEOS(); } - Event* event = queue_.GetTimed(kSbTimeMillisecond); + Event* event = queue_.GetTimed(1000); if (event == NULL) { continue; } @@ -268,8 +266,8 @@ scoped_refptr VideoDecoder::CreateFrame( resource->WriteData(buffer->pBuffer); - SbTime timestamp = ((buffer->nTimeStamp.nHighPart * 0x100000000ull) + - buffer->nTimeStamp.nLowPart); + int64_t timestamp = ((buffer->nTimeStamp.nHighPart * 0x100000000ull) + + buffer->nTimeStamp.nLowPart); resource_pool_->AddRef(); frame = new DispmanxVideoFrame( diff --git a/starboard/raspi/shared/open_max/video_decoder.h b/starboard/raspi/shared/open_max/video_decoder.h index 9965a59324a7..52b9a68b320c 100644 --- a/starboard/raspi/shared/open_max/video_decoder.h +++ b/starboard/raspi/shared/open_max/video_decoder.h @@ -48,7 +48,7 @@ class VideoDecoder void Initialize(const DecoderStatusCB& decoder_status_cb, const ErrorCB& error_cb) override; size_t GetPrerollFrameCount() const override { return 1; } - SbTime GetPrerollTimeout() const override { return kSbTimeMax; } + int64_t GetPrerollTimeout() const override { return kSbInt64Max; } size_t GetMaxNumberOfCachedFrames() const override { return 12; } void WriteInputBuffers(const InputBuffers& input_buffers) override; void WriteEndOfStream() override; diff --git a/starboard/raspi/shared/video_renderer_sink_impl.cc b/starboard/raspi/shared/video_renderer_sink_impl.cc index 7f1003402d65..41e598400b4e 100644 --- a/starboard/raspi/shared/video_renderer_sink_impl.cc +++ b/starboard/raspi/shared/video_renderer_sink_impl.cc @@ -17,7 +17,6 @@ #include "starboard/common/log.h" #include "starboard/configuration.h" #include "starboard/shared/starboard/application.h" -#include "starboard/time.h" namespace starboard { namespace raspi { @@ -62,9 +61,10 @@ void VideoRendererSinkImpl::SetBounds(int z_index, } void VideoRendererSinkImpl::Update() { - const SbTime kUpdateInterval = 5 * kSbTimeMillisecond; + const int64_t kUpdateIntervalUsec = 5'000; render_cb_(std::bind(&VideoRendererSinkImpl::DrawFrame, this, _1, _2)); - Schedule(std::bind(&VideoRendererSinkImpl::Update, this), kUpdateInterval); + Schedule(std::bind(&VideoRendererSinkImpl::Update, this), + kUpdateIntervalUsec); } VideoRendererSinkImpl::DrawFrameStatus VideoRendererSinkImpl::DrawFrame( diff --git a/starboard/shared/alsa/alsa_audio_sink_type.cc b/starboard/shared/alsa/alsa_audio_sink_type.cc index fdd0bfb7056d..d0fe33af204c 100644 --- a/starboard/shared/alsa/alsa_audio_sink_type.cc +++ b/starboard/shared/alsa/alsa_audio_sink_type.cc @@ -23,11 +23,11 @@ #include "starboard/common/condition_variable.h" #include "starboard/common/log.h" #include "starboard/common/mutex.h" +#include "starboard/common/time.h" #include "starboard/configuration.h" #include "starboard/memory.h" #include "starboard/shared/alsa/alsa_util.h" #include "starboard/thread.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -143,7 +143,7 @@ class AlsaAudioSink : public SbAudioSinkPrivate { starboard::Mutex mutex_; starboard::ConditionVariable creation_signal_; - SbTime time_to_wait_; + int64_t time_to_wait_; bool destroying_; @@ -177,7 +177,7 @@ AlsaAudioSink::AlsaAudioSink( context_(context), audio_out_thread_(kSbThreadInvalid), creation_signal_(mutex_), - time_to_wait_(kFramesPerRequest * kSbTimeSecond / sampling_frequency_hz / + time_to_wait_(kFramesPerRequest * 1'000'000LL / sampling_frequency_hz / 2), destroying_(false), frame_buffer_(frame_buffers[0]), @@ -346,7 +346,7 @@ void AlsaAudioSink::WriteFrames(double playback_rate, IncrementPointerByBytes(frame_buffer_, offset_in_frames * bytes_per_frame), frames_to_buffer_end); - consume_frames_func_(consumed, SbTimeGetMonotonicNow(), context_); + consume_frames_func_(consumed, CurrentMonotonicTime(), context_); if (consumed != frames_to_buffer_end) { SB_DLOG(INFO) << "alsa::AlsaAudioSink exits write frames : consumed " << consumed << " frames, with " << frames_to_buffer_end @@ -363,7 +363,7 @@ void AlsaAudioSink::WriteFrames(double playback_rate, IncrementPointerByBytes( frame_buffer_, offset_in_frames * bytes_per_frame), frames_to_write); - consume_frames_func_(consumed, SbTimeGetMonotonicNow(), context_); + consume_frames_func_(consumed, CurrentMonotonicTime(), context_); } else { // A very low quality resampler that simply shift the audio frames to play // at the right time. @@ -392,7 +392,7 @@ void AlsaAudioSink::WriteFrames(double playback_rate, int consumed = AlsaWriteFrames(playback_handle_, &resample_buffer_[0], target_frames); - consume_frames_func_(consumed * playback_rate_, SbTimeGetMonotonicNow(), + consume_frames_func_(consumed * playback_rate_, CurrentMonotonicTime(), context_); } } diff --git a/starboard/shared/ffmpeg/ffmpeg_demuxer.cc b/starboard/shared/ffmpeg/ffmpeg_demuxer.cc index d359e3231049..fb3c8178fdec 100644 --- a/starboard/shared/ffmpeg/ffmpeg_demuxer.cc +++ b/starboard/shared/ffmpeg/ffmpeg_demuxer.cc @@ -17,7 +17,6 @@ #include #include "starboard/shared/ffmpeg/ffmpeg_dispatch.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -34,11 +33,11 @@ CobaltExtensionDemuxerStatus FFmpegDemuxer_Seek(int64_t seek_time_us, return static_cast(user_data)->Seek(seek_time_us); } -SbTime FFmpegDemuxer_GetStartTime(void* user_data) { +int64_t FFmpegDemuxer_GetStartTime(void* user_data) { return static_cast(user_data)->GetStartTime(); } -SbTime FFmpegDemuxer_GetTimelineOffset(void* user_data) { +int64_t FFmpegDemuxer_GetTimelineOffset(void* user_data) { return static_cast(user_data)->GetTimelineOffset(); } @@ -72,7 +71,7 @@ bool FFmpegDemuxer_GetVideoConfig( return true; } -SbTime FFmpegDemuxer_GetDuration(void* user_data) { +int64_t FFmpegDemuxer_GetDuration(void* user_data) { return static_cast(user_data)->GetDuration(); } diff --git a/starboard/shared/ffmpeg/ffmpeg_demuxer.h b/starboard/shared/ffmpeg/ffmpeg_demuxer.h index eeed996f951e..7194429aa571 100644 --- a/starboard/shared/ffmpeg/ffmpeg_demuxer.h +++ b/starboard/shared/ffmpeg/ffmpeg_demuxer.h @@ -47,9 +47,9 @@ class FFmpegDemuxer { const = 0; virtual const CobaltExtensionDemuxerVideoDecoderConfig& GetVideoConfig() const = 0; - virtual SbTime GetDuration() const = 0; - virtual SbTime GetStartTime() const = 0; - virtual SbTime GetTimelineOffset() const = 0; + virtual int64_t GetDuration() const = 0; // microseconds + virtual int64_t GetStartTime() const = 0; // microseconds + virtual int64_t GetTimelineOffset() const = 0; // microseconds virtual void Read(CobaltExtensionDemuxerStreamType type, CobaltExtensionDemuxerReadCB read_cb, void* read_cb_user_data) = 0; diff --git a/starboard/shared/ffmpeg/ffmpeg_demuxer_impl.cc b/starboard/shared/ffmpeg/ffmpeg_demuxer_impl.cc index 0c78c4c708d1..d0fe5ac8e117 100644 --- a/starboard/shared/ffmpeg/ffmpeg_demuxer_impl.cc +++ b/starboard/shared/ffmpeg/ffmpeg_demuxer_impl.cc @@ -353,13 +353,13 @@ int64_t AVIOSeekOperation(void* opaque, int64_t offset, int whence) { int64_t ConvertFromTimeBaseToMicros(AVRational time_base, int64_t timestamp) { return FFmpegDemuxer::GetDispatch()->av_rescale_rnd( - timestamp, time_base.num * kSbTimeSecond, time_base.den, + timestamp, time_base.num * 1'000'000LL, time_base.den, static_cast(AV_ROUND_NEAR_INF)); } int64_t ConvertMicrosToTimeBase(AVRational time_base, int64_t timestamp_us) { return FFmpegDemuxer::GetDispatch()->av_rescale_rnd( - timestamp_us, time_base.den, time_base.num * kSbTimeSecond, + timestamp_us, time_base.den, time_base.num * 1'000'000LL, static_cast(AV_ROUND_NEAR_INF)); } @@ -618,15 +618,15 @@ FFmpegDemuxerImpl::GetVideoConfig() const { return video_config_; } -SbTime FFmpegDemuxerImpl::GetDuration() const { +int64_t FFmpegDemuxerImpl::GetDuration() const { return duration_us_; } -SbTime FFmpegDemuxerImpl::GetStartTime() const { +int64_t FFmpegDemuxerImpl::GetStartTime() const { return start_time_; } -SbTime FFmpegDemuxerImpl::GetTimelineOffset() const { +int64_t FFmpegDemuxerImpl::GetTimelineOffset() const { return timeline_offset_us_; } diff --git a/starboard/shared/ffmpeg/ffmpeg_demuxer_impl.h b/starboard/shared/ffmpeg/ffmpeg_demuxer_impl.h index c8113c96de84..64f4ed5a32b8 100644 --- a/starboard/shared/ffmpeg/ffmpeg_demuxer_impl.h +++ b/starboard/shared/ffmpeg/ffmpeg_demuxer_impl.h @@ -23,7 +23,6 @@ #include "starboard/shared/ffmpeg/ffmpeg_common.h" #include "starboard/shared/ffmpeg/ffmpeg_demuxer.h" #include "starboard/shared/ffmpeg/ffmpeg_demuxer_impl_interface.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -54,9 +53,9 @@ class FFmpegDemuxerImpl : public FFmpegDemuxer { const override; const CobaltExtensionDemuxerVideoDecoderConfig& GetVideoConfig() const override; - SbTime GetDuration() const override; - SbTime GetStartTime() const override; - SbTime GetTimelineOffset() const override; + int64_t GetDuration() const override; + int64_t GetStartTime() const override; + int64_t GetTimelineOffset() const override; void Read(CobaltExtensionDemuxerStreamType type, CobaltExtensionDemuxerReadCB read_cb, void* read_cb_user_data) override; diff --git a/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.h b/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.h index 5f680e263247..673cf7ee5b35 100644 --- a/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.h +++ b/starboard/shared/ffmpeg/ffmpeg_video_decoder_impl.h @@ -60,7 +60,7 @@ class VideoDecoderImpl : public VideoDecoder { void Initialize(const DecoderStatusCB& decoder_status_cb, const ErrorCB& error_cb) override; size_t GetPrerollFrameCount() const override { return 8; } - SbTime GetPrerollTimeout() const override { return kSbTimeMax; } + int64_t GetPrerollTimeout() const override { return kSbInt64Max; } size_t GetMaxNumberOfCachedFrames() const override { return 12; } void WriteInputBuffers(const InputBuffers& input_buffers) override; diff --git a/starboard/shared/libaom/aom_video_decoder.cc b/starboard/shared/libaom/aom_video_decoder.cc index 2f5111513bbf..306f52e0e5ce 100644 --- a/starboard/shared/libaom/aom_video_decoder.cc +++ b/starboard/shared/libaom/aom_video_decoder.cc @@ -195,7 +195,7 @@ void VideoDecoder::DecodeOneBuffer( SB_DCHECK(context_); - SbTime timestamp = input_buffer->timestamp(); + int64_t timestamp = input_buffer->timestamp(); aom_codec_err_t status = aom_codec_decode( context_.get(), input_buffer->data(), input_buffer->size(), ×tamp); if (status != AOM_CODEC_OK) { diff --git a/starboard/shared/libaom/aom_video_decoder.h b/starboard/shared/libaom/aom_video_decoder.h index d551872f513e..e5e344725735 100644 --- a/starboard/shared/libaom/aom_video_decoder.h +++ b/starboard/shared/libaom/aom_video_decoder.h @@ -45,7 +45,7 @@ class VideoDecoder : public starboard::player::filter::VideoDecoder, void Initialize(const DecoderStatusCB& decoder_status_cb, const ErrorCB& error_cb) override; size_t GetPrerollFrameCount() const override { return 8; } - SbTime GetPrerollTimeout() const override { return kSbTimeMax; } + int64_t GetPrerollTimeout() const override { return kSbInt64Max; } size_t GetMaxNumberOfCachedFrames() const override { return 12; } void WriteInputBuffers(const InputBuffers& input_buffers) override; diff --git a/starboard/shared/libdav1d/dav1d_video_decoder.cc b/starboard/shared/libdav1d/dav1d_video_decoder.cc index d584643c71b1..25086aabd659 100644 --- a/starboard/shared/libdav1d/dav1d_video_decoder.cc +++ b/starboard/shared/libdav1d/dav1d_video_decoder.cc @@ -118,8 +118,8 @@ void VideoDecoder::WriteEndOfStream() { return; } - decoder_thread_->job_queue()->Schedule(std::bind( - &VideoDecoder::DecodeEndOfStream, this, 100 * kSbTimeMillisecond)); + decoder_thread_->job_queue()->Schedule( + std::bind(&VideoDecoder::DecodeEndOfStream, this, 100'000)); } void VideoDecoder::Reset() { @@ -267,18 +267,18 @@ void VideoDecoder::DecodeOneBuffer( ReportError(FormatString("|dav1d_send_data| failed with code %d.", result)); } -void VideoDecoder::DecodeEndOfStream(SbTime timeout) { +void VideoDecoder::DecodeEndOfStream(int64_t timeout) { SB_DCHECK(decoder_thread_->job_queue()->BelongsToCurrentThread()); if (!TryToOutputFrames()) { return; } if (frames_being_decoded_ > 0 && timeout > 0) { - const SbTime delay_period = 5 * kSbTimeMillisecond; + const int64_t delay_period_usec = 5'000; // 5ms decoder_thread_->job_queue()->Schedule( std::bind(&VideoDecoder::DecodeEndOfStream, this, - timeout - delay_period), - delay_period); + timeout - delay_period_usec), + delay_period_usec); return; } else { SB_LOG_IF(WARNING, frames_being_decoded_ > 0) diff --git a/starboard/shared/libdav1d/dav1d_video_decoder.h b/starboard/shared/libdav1d/dav1d_video_decoder.h index fb39ba1024a8..b5f3511f59a6 100644 --- a/starboard/shared/libdav1d/dav1d_video_decoder.h +++ b/starboard/shared/libdav1d/dav1d_video_decoder.h @@ -46,7 +46,7 @@ class VideoDecoder : public starboard::player::filter::VideoDecoder, // TODO: Verify if these values are correct. size_t GetPrerollFrameCount() const override { return 8; } - SbTime GetPrerollTimeout() const override { return kSbTimeMax; } + int64_t GetPrerollTimeout() const override { return kSbInt64Max; } size_t GetMaxNumberOfCachedFrames() const override { return 12; } void WriteInputBuffers(const InputBuffers& input_buffers) override; @@ -68,7 +68,7 @@ class VideoDecoder : public starboard::player::filter::VideoDecoder, void InitializeCodec(); void TeardownCodec(); void DecodeOneBuffer(const scoped_refptr& input_buffer); - void DecodeEndOfStream(SbTime timeout); + void DecodeEndOfStream(int64_t timeout); // Sends all available decoded frames from dav1d for outputting. Returns the // number of frames decoded. The output argument tracks whether an diff --git a/starboard/shared/libde265/de265_video_decoder.cc b/starboard/shared/libde265/de265_video_decoder.cc index ee8e149ba48c..f887f1314e97 100644 --- a/starboard/shared/libde265/de265_video_decoder.cc +++ b/starboard/shared/libde265/de265_video_decoder.cc @@ -180,7 +180,7 @@ void VideoDecoder::DecodeOneBuffer( SB_DCHECK(context_); - SbTime timestamp = input_buffer->timestamp(); + int64_t timestamp = input_buffer->timestamp(); de265_error status = de265_push_data(context_, input_buffer->data(), input_buffer->size(), timestamp, 0); if (status != DE265_OK) { diff --git a/starboard/shared/libde265/de265_video_decoder.h b/starboard/shared/libde265/de265_video_decoder.h index 878b49d90ea9..7f8a8dc86a73 100644 --- a/starboard/shared/libde265/de265_video_decoder.h +++ b/starboard/shared/libde265/de265_video_decoder.h @@ -47,7 +47,7 @@ class VideoDecoder : public starboard::player::filter::VideoDecoder, void Initialize(const DecoderStatusCB& decoder_status_cb, const ErrorCB& error_cb) override; size_t GetPrerollFrameCount() const override { return 8; } - SbTime GetPrerollTimeout() const override { return kSbTimeMax; } + int64_t GetPrerollTimeout() const override { return kSbInt64Max; } size_t GetMaxNumberOfCachedFrames() const override { return 12; } void WriteInputBuffers(const InputBuffers& input_buffers) override; diff --git a/starboard/shared/libevent/socket_waiter_internal.cc b/starboard/shared/libevent/socket_waiter_internal.cc index 7ab3a4b3ad3c..2246e2638cf1 100644 --- a/starboard/shared/libevent/socket_waiter_internal.cc +++ b/starboard/shared/libevent/socket_waiter_internal.cc @@ -23,10 +23,10 @@ #include #include "starboard/common/log.h" +#include "starboard/common/time.h" #include "starboard/shared/posix/handle_eintr.h" #include "starboard/shared/posix/set_non_blocking_internal.h" #include "starboard/shared/posix/socket_internal.h" -#include "starboard/shared/posix/time_internal.h" #include "starboard/thread.h" #include "third_party/libevent/event.h" @@ -47,8 +47,8 @@ SbSocketAddress GetIpv4Localhost() { return address; } -SbSocket AcceptBySpinning(SbSocket server_socket, SbTime timeout) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); +SbSocket AcceptBySpinning(SbSocket server_socket, int64_t timeout) { + int64_t start = starboard::CurrentMonotonicTime(); while (true) { SbSocket accepted_socket = SbSocketAccept(server_socket); if (SbSocketIsValid(accepted_socket)) { @@ -59,7 +59,7 @@ SbSocket AcceptBySpinning(SbSocket server_socket, SbTime timeout) { SB_DCHECK(SbSocketGetLastError(server_socket) == kSbSocketPending); // Check if we have passed our timeout. - if (SbTimeGetMonotonicNow() - start >= timeout) { + if (starboard::CurrentMonotonicTime() - start >= timeout) { break; } @@ -74,7 +74,7 @@ SbSocket AcceptBySpinning(SbSocket server_socket, SbTime timeout) { void GetSocketPipe(SbSocket* client_socket, SbSocket* server_socket) { int result; SbSocketError sb_socket_result; - const SbTimeMonotonic kTimeout = kSbTimeSecond / 15; + const int64_t kTimeoutUsec = 1'000'000 / 15; SbSocketAddress address = GetIpv4Localhost(); // Setup a listening socket. @@ -101,7 +101,7 @@ void GetSocketPipe(SbSocket* client_socket, SbSocket* server_socket) { sb_socket_result == kSbSocketPending); // Spin until the accept happens (or we get impatient). - *server_socket = AcceptBySpinning(listen_socket, kTimeout); + *server_socket = AcceptBySpinning(listen_socket, kTimeoutUsec); SB_DCHECK(SbSocketIsValid(*server_socket)); result = SbSocketDestroy(listen_socket); @@ -257,10 +257,10 @@ void SbSocketWaiterPrivate::Wait() { // We basically wait for the largest amount of time to achieve an indefinite // block. - WaitTimed(kSbTimeMax); + WaitTimed(kSbInt64Max); } -SbSocketWaiterResult SbSocketWaiterPrivate::WaitTimed(SbTime duration) { +SbSocketWaiterResult SbSocketWaiterPrivate::WaitTimed(int64_t duration_usec) { SB_DCHECK(SbThreadIsCurrent(thread_)); // The way to do this is apparently to create a timeout event, call WakeUp @@ -269,9 +269,10 @@ SbSocketWaiterResult SbSocketWaiterPrivate::WaitTimed(SbTime duration) { timeout_set(&event, &SbSocketWaiterPrivate::LibeventTimeoutCallback, this); event_base_set(base_, &event); - if (duration < kSbTimeMax) { + if (duration_usec < kSbInt64Max) { struct timeval tv; - ToTimevalDuration(duration, &tv); + tv.tv_sec = duration_usec / 1'000'000; + tv.tv_usec = duration_usec % 1'000'000; timeout_add(&event, &tv); } @@ -283,7 +284,7 @@ SbSocketWaiterResult SbSocketWaiterPrivate::WaitTimed(SbTime duration) { woken_up_ ? kSbSocketWaiterResultWokenUp : kSbSocketWaiterResultTimedOut; woken_up_ = false; - if (duration < kSbTimeMax) { + if (duration_usec < kSbInt64Max) { // We clean this up, in case we were awakened early, to prevent a spurious // wake-up later. timeout_del(&event); diff --git a/starboard/shared/libevent/socket_waiter_internal.h b/starboard/shared/libevent/socket_waiter_internal.h index 55127af4a6be..e43bca8a603d 100644 --- a/starboard/shared/libevent/socket_waiter_internal.h +++ b/starboard/shared/libevent/socket_waiter_internal.h @@ -38,7 +38,7 @@ struct SbSocketWaiterPrivate { bool persistent); bool Remove(SbSocket socket); void Wait(); - SbSocketWaiterResult WaitTimed(SbTime duration); + SbSocketWaiterResult WaitTimed(int64_t duration_usec); void WakeUp(bool timeout); private: diff --git a/starboard/shared/libevent/socket_waiter_wait_timed.cc b/starboard/shared/libevent/socket_waiter_wait_timed.cc index a0aeee4fa15b..dc7231a7e8ed 100644 --- a/starboard/shared/libevent/socket_waiter_wait_timed.cc +++ b/starboard/shared/libevent/socket_waiter_wait_timed.cc @@ -17,7 +17,7 @@ #include "starboard/shared/libevent/socket_waiter_internal.h" SbSocketWaiterResult SbSocketWaiterWaitTimed(SbSocketWaiter waiter, - SbTime duration) { + int64_t duration) { if (!SbSocketWaiterIsValid(waiter)) { return kSbSocketWaiterResultInvalid; } diff --git a/starboard/shared/libvpx/vpx_video_decoder.cc b/starboard/shared/libvpx/vpx_video_decoder.cc index 76d2d71807a5..4a3662ce2730 100644 --- a/starboard/shared/libvpx/vpx_video_decoder.cc +++ b/starboard/shared/libvpx/vpx_video_decoder.cc @@ -194,7 +194,7 @@ void VideoDecoder::DecodeOneBuffer( SB_DCHECK(context_); - SbTime timestamp = input_buffer->timestamp(); + int64_t timestamp = input_buffer->timestamp(); vpx_codec_err_t status = vpx_codec_decode(context_.get(), input_buffer->data(), input_buffer->size(), ×tamp, 0); diff --git a/starboard/shared/libvpx/vpx_video_decoder.h b/starboard/shared/libvpx/vpx_video_decoder.h index a99bab6aba73..433f91c4aabd 100644 --- a/starboard/shared/libvpx/vpx_video_decoder.h +++ b/starboard/shared/libvpx/vpx_video_decoder.h @@ -47,7 +47,7 @@ class VideoDecoder : public starboard::player::filter::VideoDecoder, void Initialize(const DecoderStatusCB& decoder_status_cb, const ErrorCB& error_cb) override; size_t GetPrerollFrameCount() const override { return 8; } - SbTime GetPrerollTimeout() const override { return kSbTimeMax; } + int64_t GetPrerollTimeout() const override { return kSbInt64Max; } size_t GetMaxNumberOfCachedFrames() const override { return 12; } void WriteInputBuffers(const InputBuffers& input_buffers) override; diff --git a/starboard/shared/linux/dev_input/dev_input.cc b/starboard/shared/linux/dev_input/dev_input.cc index f211ddf9929e..56e421c2c541 100644 --- a/starboard/shared/linux/dev_input/dev_input.cc +++ b/starboard/shared/linux/dev_input/dev_input.cc @@ -41,7 +41,6 @@ #include "starboard/memory.h" #include "starboard/once.h" #include "starboard/shared/posix/handle_eintr.h" -#include "starboard/shared/posix/time_internal.h" namespace starboard { namespace shared { @@ -224,7 +223,7 @@ class DevInputImpl : public DevInput { void InitDevInputImpl(SbWindow window); Event* PollNextSystemEvent() override; - Event* WaitForSystemEventWithTimeout(SbTime time) override; + Event* WaitForSystemEventWithTimeout(int64_t time) override; void WakeSystemEventWait() override; private: @@ -964,7 +963,7 @@ DevInput::Event* DevInputImpl::PollNextSystemEvent() { return NULL; } -DevInput::Event* DevInputImpl::WaitForSystemEventWithTimeout(SbTime duration) { +DevInput::Event* DevInputImpl::WaitForSystemEventWithTimeout(int64_t duration) { Event* event = PollNextSystemEvent(); if (event) { return event; @@ -981,9 +980,10 @@ DevInput::Event* DevInputImpl::WaitForSystemEventWithTimeout(SbTime duration) { } read_set.Set(wakeup_read_fd_); + int64_t clamped_duration_usec = std::max(duration, 0LL); struct timeval tv; - SbTime clamped_duration = std::max(duration, (SbTime)0); - ToTimevalDuration(clamped_duration, &tv); + tv.tv_sec = clamped_duration_usec / 1'000'000; + tv.tv_usec = clamped_duration_usec % 1'000'000; if (select(read_set.max_fd() + 1, read_set.set(), NULL, NULL, &tv) == 0) { // This is the timeout case. return NULL; diff --git a/starboard/shared/linux/dev_input/dev_input.h b/starboard/shared/linux/dev_input/dev_input.h index a20c07c10e47..3f13369f941c 100644 --- a/starboard/shared/linux/dev_input/dev_input.h +++ b/starboard/shared/linux/dev_input/dev_input.h @@ -17,7 +17,6 @@ #include "starboard/shared/internal_only.h" #include "starboard/shared/starboard/application.h" -#include "starboard/time.h" #include "starboard/window.h" namespace starboard { @@ -36,10 +35,10 @@ class DevInput { // responsible for deleting the returned event. virtual Event* PollNextSystemEvent() = 0; - // Waits for an event until the timeout |time| runs out. If an event occurs in - // this time, it is returned, otherwise NULL is returned. The caller is - // responsible for deleting the returned event. - virtual Event* WaitForSystemEventWithTimeout(SbTime duration) = 0; + // Waits for an event until the timeout |duration| (in microseconds) runs out. + // If an event occurs in this time, it is returned, otherwise NULL is + // returned. The caller is responsible for deleting the returned event. + virtual Event* WaitForSystemEventWithTimeout(int64_t duration) = 0; // Wakes up any thread waiting within a call to // WaitForSystemEventWithTimeout(). diff --git a/starboard/shared/openh264/openh264_video_decoder.h b/starboard/shared/openh264/openh264_video_decoder.h index b547b1f4864d..420574c7f5cc 100644 --- a/starboard/shared/openh264/openh264_video_decoder.h +++ b/starboard/shared/openh264/openh264_video_decoder.h @@ -50,7 +50,7 @@ class VideoDecoder : public starboard::player::filter::VideoDecoder, // TODO: Verify if these values are correct. size_t GetPrerollFrameCount() const override { return 8; } - SbTime GetPrerollTimeout() const override { return kSbTimeMax; } + int64_t GetPrerollTimeout() const override { return kSbInt64Max; } size_t GetMaxNumberOfCachedFrames() const override { return 12; } void WriteInputBuffers(const InputBuffers& input_buffers) override; diff --git a/starboard/shared/posix/impl/file_get_info.h b/starboard/shared/posix/impl/file_get_info.h index d94663735fcc..e086b41efdc3 100644 --- a/starboard/shared/posix/impl/file_get_info.h +++ b/starboard/shared/posix/impl/file_get_info.h @@ -20,8 +20,7 @@ #include "starboard/file.h" #include - -#include "starboard/shared/posix/time_internal.h" +#include #include "starboard/shared/internal_only.h" #include "starboard/shared/posix/impl/file_impl.h" @@ -42,11 +41,11 @@ bool FileGetInfo(SbFile file, SbFileInfo* out_info) { return false; } - out_info->creation_time = FromTimeT(stat.st_ctime); + out_info->creation_time = TimeTToWindowsUsec(stat.st_ctime); out_info->is_directory = S_ISDIR(stat.st_mode); out_info->is_symbolic_link = S_ISLNK(stat.st_mode); - out_info->last_accessed = FromTimeT(stat.st_atime); - out_info->last_modified = FromTimeT(stat.st_mtime); + out_info->last_accessed = TimeTToWindowsUsec(stat.st_atime); + out_info->last_modified = TimeTToWindowsUsec(stat.st_mtime); out_info->size = stat.st_size; return true; } diff --git a/starboard/shared/posix/impl/file_get_path_info.h b/starboard/shared/posix/impl/file_get_path_info.h index ab0282c1f22e..588552c8c1c7 100644 --- a/starboard/shared/posix/impl/file_get_path_info.h +++ b/starboard/shared/posix/impl/file_get_path_info.h @@ -20,8 +20,7 @@ #include "starboard/file.h" #include - -#include "starboard/shared/posix/time_internal.h" +#include #include "starboard/shared/internal_only.h" #include "starboard/shared/posix/impl/file_impl.h" @@ -42,11 +41,11 @@ bool FileGetPathInfo(const char* path, SbFileInfo* out_info) { return false; } - out_info->creation_time = FromTimeT(file_info.st_ctime); + out_info->creation_time = TimeTToWindowsUsec(file_info.st_ctime); out_info->is_directory = S_ISDIR(file_info.st_mode); out_info->is_symbolic_link = S_ISLNK(file_info.st_mode); - out_info->last_accessed = FromTimeT(file_info.st_atime); - out_info->last_modified = FromTimeT(file_info.st_mtime); + out_info->last_accessed = TimeTToWindowsUsec(file_info.st_atime); + out_info->last_modified = TimeTToWindowsUsec(file_info.st_mtime); out_info->size = file_info.st_size; return true; } diff --git a/starboard/shared/posix/impl/file_impl.h b/starboard/shared/posix/impl/file_impl.h index 43fb61c0baa8..27fa9cc0785f 100644 --- a/starboard/shared/posix/impl/file_impl.h +++ b/starboard/shared/posix/impl/file_impl.h @@ -17,6 +17,7 @@ #ifndef STARBOARD_SHARED_POSIX_IMPL_FILE_IMPL_H_ #define STARBOARD_SHARED_POSIX_IMPL_FILE_IMPL_H_ +#include "starboard/common/time.h" #include "starboard/configuration.h" #include "starboard/file.h" @@ -26,4 +27,19 @@ SB_COMPILE_ASSERT(sizeof(((SbFile)0)->descriptor), SbFilePrivate_must_have_descriptor); +namespace starboard { +namespace shared { +namespace posix { +namespace impl { + +inline int64_t TimeTToWindowsUsec(time_t time) { + int64_t posix_usec = static_cast(time) * 1000000; + return PosixTimeToWindowsTime(posix_usec); +} + +} // namespace impl +} // namespace posix +} // namespace shared +} // namespace starboard + #endif // STARBOARD_SHARED_POSIX_IMPL_FILE_IMPL_H_ diff --git a/starboard/shared/posix/socket_set_tcp_keep_alive.cc b/starboard/shared/posix/socket_set_tcp_keep_alive.cc index 6b2d3b5c82af..871cc12517eb 100644 --- a/starboard/shared/posix/socket_set_tcp_keep_alive.cc +++ b/starboard/shared/posix/socket_set_tcp_keep_alive.cc @@ -21,14 +21,14 @@ namespace sbposix = starboard::shared::posix; -bool SbSocketSetTcpKeepAlive(SbSocket socket, bool value, SbTime period) { +bool SbSocketSetTcpKeepAlive(SbSocket socket, bool value, int64_t period) { bool result = sbposix::SetBooleanSocketOption( socket, SOL_SOCKET, SO_KEEPALIVE, "SO_KEEPALIVE", value); if (!result) { return false; } - int period_seconds = static_cast(period / kSbTimeSecond); + int period_seconds = static_cast(period / 1'000'000); result = sbposix::SetIntegerSocketOption(socket, SOL_TCP, TCP_KEEPIDLE, "TCP_KEEPIDLE", period_seconds); if (!result) { diff --git a/starboard/shared/posix/thread_sleep.cc b/starboard/shared/posix/thread_sleep.cc index 4df76f541633..73b812b2ecde 100644 --- a/starboard/shared/posix/thread_sleep.cc +++ b/starboard/shared/posix/thread_sleep.cc @@ -16,13 +16,11 @@ #include -#include "starboard/time.h" - -void SbThreadSleep(SbTime duration) { +void SbThreadSleep(int64_t duration) { if (duration <= 0) { return; } - // SbTime is microseconds, so this is easy. + // duration is microseconds, so this is easy. usleep(duration); } diff --git a/starboard/shared/posix/time_get_monotonic_now.cc b/starboard/shared/posix/time_get_monotonic_now.cc index 07fe8466fc55..b5bdf4aa66f0 100644 --- a/starboard/shared/posix/time_get_monotonic_now.cc +++ b/starboard/shared/posix/time_get_monotonic_now.cc @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if SB_API_VERSION < 16 + #include "starboard/time.h" #include @@ -28,3 +30,5 @@ SbTimeMonotonic SbTimeGetMonotonicNow() { return FromTimespecDelta(&time); } + +#endif // SB_API_VERSION < 16 diff --git a/starboard/shared/posix/time_get_now.cc b/starboard/shared/posix/time_get_now.cc index c38190583bb7..0323fc43fbc3 100644 --- a/starboard/shared/posix/time_get_now.cc +++ b/starboard/shared/posix/time_get_now.cc @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if SB_API_VERSION < 16 + #include "starboard/time.h" #include @@ -28,3 +30,5 @@ SbTime SbTimeGetNow() { return FromTimeval(&time); } + +#endif // SB_API_VERSION < 16 diff --git a/starboard/shared/posix/time_internal.h b/starboard/shared/posix/time_internal.h index 89f175ebb715..6d75f49fae90 100644 --- a/starboard/shared/posix/time_internal.h +++ b/starboard/shared/posix/time_internal.h @@ -15,20 +15,18 @@ #ifndef STARBOARD_SHARED_POSIX_TIME_INTERNAL_H_ #define STARBOARD_SHARED_POSIX_TIME_INTERNAL_H_ +#if SB_API_VERSION < 16 + #include #include #include "starboard/shared/internal_only.h" #include "starboard/time.h" -namespace { +namespace { // NOLINT(build/namespaces_headers) const int64_t kMillisecondsPerSecond = kSbTimeSecond / kSbTimeMillisecond; const int64_t kNanosecondsPerMicrosecond = 1000; -inline SbTime FromMilliseconds(int64_t ms) { - return ms * kSbTimeMillisecond; -} - inline SbTime FromSeconds(int64_t secs) { return secs * kSbTimeSecond; } @@ -43,14 +41,6 @@ inline int64_t FromTimespecDelta(struct timespec* time) { FromNanoseconds(static_cast(time->tv_nsec)); } -// Converts the number of microseconds in |time_us| into a POSIX timespec, -// placing the result in |out_time|. -inline void ToTimespec(struct timespec* out_time, int64_t time_us) { - out_time->tv_sec = time_us / kSbTimeSecond; - int64_t remainder_us = time_us - (out_time->tv_sec * kSbTimeSecond); - out_time->tv_nsec = remainder_us * kNanosecondsPerMicrosecond; -} - // Converts a timeval (relative to POSIX epoch) into microseconds since the // Windows epoch (1601). inline int64_t FromTimeval(const struct timeval* time) { @@ -58,12 +48,6 @@ inline int64_t FromTimeval(const struct timeval* time) { time->tv_usec); } -// Converts a number of microseconds into a timeval. -inline void ToTimevalDuration(int64_t microseconds, struct timeval* out_time) { - out_time->tv_sec = microseconds / kSbTimeSecond; - out_time->tv_usec = microseconds % kSbTimeSecond; -} - // Converts a time_t (relative to POSIX epoch) into microseconds since the // Windows epoch (1601). inline int64_t FromTimeT(time_t time) { @@ -71,4 +55,6 @@ inline int64_t FromTimeT(time_t time) { } } // namespace +#endif // SB_API_VERSION < 16 + #endif // STARBOARD_SHARED_POSIX_TIME_INTERNAL_H_ diff --git a/starboard/shared/pthread/condition_variable_wait_timed.cc b/starboard/shared/pthread/condition_variable_wait_timed.cc index 3144b862c559..6965b5901667 100644 --- a/starboard/shared/pthread/condition_variable_wait_timed.cc +++ b/starboard/shared/pthread/condition_variable_wait_timed.cc @@ -19,7 +19,6 @@ #include #include "starboard/common/time.h" -#include "starboard/shared/posix/time_internal.h" #include "starboard/shared/pthread/is_success.h" #include "starboard/shared/pthread/types_internal.h" #include "starboard/shared/starboard/lazy_initialization_internal.h" @@ -39,21 +38,22 @@ SbConditionVariableResult SbConditionVariableWaitTimed( } #if !SB_HAS_QUIRK(NO_CONDATTR_SETCLOCK_SUPPORT) - int64_t timeout_time = starboard::CurrentMonotonicTime() + timeout; + int64_t timeout_time_usec = starboard::CurrentMonotonicTime() + timeout; #else // !SB_HAS_QUIRK(NO_CONDATTR_SETCLOCK_SUPPORT) - int64_t timeout_time = starboard::CurrentPosixTime() + timeout; + int64_t timeout_time_usec = starboard::CurrentPosixTime() + timeout; #endif // !SB_HAS_QUIRK(NO_CONDATTR_SETCLOCK_SUPPORT) // Detect overflow if timeout is near kSbInt64Max. Since timeout can't be // negative at this point, if it goes negative after adding now, we know we've // gone over. Especially posix now, which has a 400 year advantage over // Chromium (Windows) now. - if (timeout_time < 0) { - timeout_time = kSbInt64Max; + if (timeout_time_usec < 0) { + timeout_time_usec = kSbInt64Max; } struct timespec timeout_ts; - ToTimespec(&timeout_ts, timeout_time); + timeout_ts.tv_sec = timeout_time_usec / 1'000'000; + timeout_ts.tv_nsec = (timeout_time_usec % 1'000'000) * 1000; if (!EnsureInitialized( &(SB_PTHREAD_INTERNAL_CONDITION(condition)->initialized_state))) { diff --git a/starboard/shared/pulse/pulse_audio_sink_type.cc b/starboard/shared/pulse/pulse_audio_sink_type.cc index ab75c858d4e9..7e200cefa210 100644 --- a/starboard/shared/pulse/pulse_audio_sink_type.cc +++ b/starboard/shared/pulse/pulse_audio_sink_type.cc @@ -24,11 +24,11 @@ #include "starboard/common/atomic.h" #include "starboard/common/log.h" #include "starboard/common/mutex.h" +#include "starboard/common/time.h" #include "starboard/shared/pulse/pulse_dynamic_load_dispatcher.h" #include "starboard/shared/starboard/audio_sink/audio_sink_internal.h" #include "starboard/shared/starboard/media/media_util.h" #include "starboard/thread.h" -#include "starboard/time.h" #if defined(ADDRESS_SANITIZER) // By default, Leak Sanitizer and Address Sanitizer is expected to exist @@ -50,8 +50,8 @@ namespace { using starboard::media::GetBytesPerSample; -const SbTime kAudioIdleSleepInterval = 15 * kSbTimeMillisecond; -const SbTime kAudioRunningSleepInterval = 5 * kSbTimeMillisecond; +const int64_t kAudioIdleSleepIntervalUsec = 15'000; // 15ms +const int64_t kAudioRunningSleepIntervalUsec = 5'000; // 5ms // The minimum number of frames that can be written to Pulse once. A small // number will lead to more CPU being used as the callbacks will be called more // frequently. @@ -276,7 +276,7 @@ bool PulseAudioSink::WriteFrameIfNecessary(pa_context* context) { SB_DCHECK(total_frames_played_ <= new_total_frames_played); int64_t consume = new_total_frames_played - total_frames_played_; if (consume > 0) { - consume_frames_func_(consume, SbTimeGetMonotonicNow(), context_); + consume_frames_func_(consume, CurrentMonotonicTime(), context_); total_frames_played_ = new_total_frames_played; } } @@ -571,9 +571,9 @@ void PulseAudioSinkType::AudioThreadFunc() { pa_mainloop_iterate(mainloop_, 0, NULL); } if (has_running_sink) { - SbThreadSleep(kAudioRunningSleepInterval); + SbThreadSleep(kAudioRunningSleepIntervalUsec); } else { - SbThreadSleep(kAudioIdleSleepInterval); + SbThreadSleep(kAudioIdleSleepIntervalUsec); } } } diff --git a/starboard/shared/signal/suspend_signals.cc b/starboard/shared/signal/suspend_signals.cc index f0ea9b1f1d84..87784a6f3206 100644 --- a/starboard/shared/signal/suspend_signals.cc +++ b/starboard/shared/signal/suspend_signals.cc @@ -117,7 +117,7 @@ class SignalHandlerThread : public ::starboard::Thread { void Run() override { SignalMask(kAllSignals, SIG_UNBLOCK); - while (!WaitForJoin(kSbTimeMax)) { + while (!WaitForJoin(kSbInt64Max)) { } } }; diff --git a/starboard/shared/starboard/application.cc b/starboard/shared/starboard/application.cc index f751f9419ccd..b85194b0de28 100644 --- a/starboard/shared/starboard/application.cc +++ b/starboard/shared/starboard/application.cc @@ -196,7 +196,7 @@ void Application::WindowSizeChanged(void* context, SbEventId Application::Schedule(SbEventCallback callback, void* context, - SbTimeMonotonic delay) { + int64_t delay) { SbEventId id = SbAtomicNoBarrier_Increment(&g_next_event_id, 1); InjectTimedEvent(new TimedEvent(id, callback, context, delay)); return id; @@ -226,13 +226,13 @@ void Application::SetStartLink(const char* start_link) { } } -void Application::DispatchStart(SbTimeMonotonic timestamp) { +void Application::DispatchStart(int64_t timestamp) { SB_DCHECK(IsCurrentThread()); SB_DCHECK(state_ == kStateUnstarted); DispatchAndDelete(CreateInitialEvent(kSbEventTypeStart, timestamp)); } -void Application::DispatchPreload(SbTimeMonotonic timestamp) { +void Application::DispatchPreload(int64_t timestamp) { SB_DCHECK(IsCurrentThread()); SB_DCHECK(state_ == kStateUnstarted); DispatchAndDelete(CreateInitialEvent(kSbEventTypePreload, timestamp)); @@ -256,7 +256,7 @@ bool Application::DispatchAndDelete(Application::Event* event) { // HandleEventAndUpdateState() rather than Inject() for the intermediate // events because there may already be other lifecycle events in the queue. - SbTimeMonotonic timestamp = scoped_event->event->timestamp; + int64_t timestamp = scoped_event->event->timestamp; switch (scoped_event->event->type) { case kSbEventTypePreload: if (state() != kStateUnstarted) { @@ -479,7 +479,7 @@ void Application::CallTeardownCallbacks() { } Application::Event* Application::CreateInitialEvent(SbEventType type, - SbTimeMonotonic timestamp) { + int64_t timestamp) { SB_DCHECK(type == kSbEventTypePreload || type == kSbEventTypeStart); SbEventStartData* start_data = new SbEventStartData(); memset(start_data, 0, sizeof(SbEventStartData)); @@ -499,9 +499,9 @@ Application::Event* Application::CreateInitialEvent(SbEventType type, int Application::RunLoop() { SB_DCHECK(command_line_); if (IsPreloadImmediate()) { - DispatchPreload(SbTimeGetMonotonicNow()); + DispatchPreload(CurrentMonotonicTime()); } else if (IsStartImmediate()) { - DispatchStart(SbTimeGetMonotonicNow()); + DispatchStart(CurrentMonotonicTime()); } for (;;) { diff --git a/starboard/shared/starboard/application.h b/starboard/shared/starboard/application.h index 9a0f804beb4b..3f4f219fcd25 100644 --- a/starboard/shared/starboard/application.h +++ b/starboard/shared/starboard/application.h @@ -25,13 +25,13 @@ #include "starboard/common/log.h" #include "starboard/common/ref_counted.h" #include "starboard/common/scoped_ptr.h" +#include "starboard/common/time.h" #include "starboard/event.h" #include "starboard/player.h" #include "starboard/shared/internal_only.h" #include "starboard/shared/starboard/command_line.h" #include "starboard/shared/starboard/player/filter/video_frame_internal.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "starboard/types.h" #include "starboard/window.h" @@ -86,20 +86,17 @@ class Application { // Structure to keep track of scheduled events, also used as the data argument // for kSbEventTypeScheduled Events. struct TimedEvent { - TimedEvent(SbEventId eid, - SbEventCallback func, - void* data, - SbTimeMonotonic delay) + TimedEvent(SbEventId eid, SbEventCallback func, void* data, int64_t delay) : id(eid), callback(func), context(data), - target_time(delay + SbTimeGetMonotonicNow()), + target_time(delay + CurrentMonotonicTime()), canceled(false) {} SbEventId id; SbEventCallback callback; void* context; - SbTimeMonotonic target_time; + int64_t target_time; bool canceled; }; @@ -121,7 +118,7 @@ class Application { // deleted. struct Event { Event(SbEventType type, - SbTimeMonotonic timestamp, + int64_t timestamp, void* data, SbEventDataDestructor destructor) : event(new SbEvent()), destructor(destructor), error_level(0) { @@ -133,7 +130,7 @@ class Application { Event(SbEventType type, void* data, SbEventDataDestructor destructor) : event(new SbEvent()), destructor(destructor), error_level(0) { event->type = type; - event->timestamp = SbTimeGetMonotonicNow(); + event->timestamp = CurrentMonotonicTime(); event->data = data; } @@ -142,7 +139,7 @@ class Application { destructor(&DeleteDestructor), error_level(0) { event->type = kSbEventTypeScheduled; - event->timestamp = SbTimeGetMonotonicNow(); + event->timestamp = CurrentMonotonicTime(); event->data = data; } ~Event() { @@ -279,9 +276,7 @@ class Application { // Schedules an event into the event queue. May be called from an external // thread. - SbEventId Schedule(SbEventCallback callback, - void* context, - SbTimeMonotonic delay); + SbEventId Schedule(SbEventCallback callback, void* context, int64_t delay); // Cancels an event that was previously scheduled. May be called from an // external thread. @@ -363,10 +358,10 @@ class Application { // NULL if there are no due TimedEvents queued. Passes ownership to caller. virtual TimedEvent* GetNextDueTimedEvent() = 0; - // Gets the next time that a TimedEvent is due. Returns - // SbTimeGetMonotonicNow() if the next TimedEvent is past due. Returns - // kSbTimeMax if there are no queued TimedEvents. - virtual SbTimeMonotonic GetNextTimedEventTargetTime() = 0; + // Gets the next time in microseconds that a TimedEvent is due. Returns + // CurrentMonotonicTime() if the next TimedEvent is past due. Returns + // kSbInt64Max if there are no queued TimedEvents. + virtual int64_t GetNextTimedEventTargetTime() = 0; // Sets the command-line parameters for the application. Used to support // system message pump-based implementations, which don't call |Run()|. @@ -397,7 +392,7 @@ class Application { // Synchronously dispatches a Start event to the system event handler. Must be // called on the main dispatch thread. - void DispatchStart(SbTimeMonotonic timestamp); + void DispatchStart(int64_t timestamp); // Returns whether the Preload event should be sent in |Run| before entering // the event loop. Derived classes that return true must call |Unpause| or @@ -408,7 +403,7 @@ class Application { // Synchronously dispatches a Preload event to the system event handler. Must // be called on the main dispatch thread. - void DispatchPreload(SbTimeMonotonic timestamp); + void DispatchPreload(int64_t timestamp); // Returns whether the '--preload' command-line argument is specified. bool HasPreloadSwitch(); @@ -426,7 +421,7 @@ class Application { private: // Creates an initial event type of either Start or Preload with the original // command line and deep link. - Event* CreateInitialEvent(SbEventType type, SbTimeMonotonic timestamp); + Event* CreateInitialEvent(SbEventType type, int64_t timestamp); // Internal workhorse of the main run loop. int RunLoop(); diff --git a/starboard/shared/starboard/audio_sink/audio_sink_internal.cc b/starboard/shared/starboard/audio_sink/audio_sink_internal.cc index 61bcdb419a33..450c4186928a 100644 --- a/starboard/shared/starboard/audio_sink/audio_sink_internal.cc +++ b/starboard/shared/starboard/audio_sink/audio_sink_internal.cc @@ -37,7 +37,7 @@ const char kUseStubAudioSink[] = "use_stub_audio_sink"; void WrapConsumeFramesFunc(SbAudioSinkConsumeFramesFunc sb_consume_frames_func, int frames_consumed, - SbTime frames_consumed_at, + int64_t frames_consumed_at, void* context) { SB_UNREFERENCED_PARAMETER(frames_consumed_at); sb_consume_frames_func(frames_consumed, context); diff --git a/starboard/shared/starboard/audio_sink/audio_sink_internal.h b/starboard/shared/starboard/audio_sink/audio_sink_internal.h index 57e282a1eea0..fa0cc550d1f6 100644 --- a/starboard/shared/starboard/audio_sink/audio_sink_internal.h +++ b/starboard/shared/starboard/audio_sink/audio_sink_internal.h @@ -32,7 +32,7 @@ struct SbAudioSinkPrivate { void* context); typedef std::function< - void(int frames_consumed, SbTime frames_consumed_at, void* context)> + void(int frames_consumed, int64_t frames_consumed_at, void* context)> ConsumeFramesFunc; class Type { diff --git a/starboard/shared/starboard/audio_sink/stub_audio_sink_type.cc b/starboard/shared/starboard/audio_sink/stub_audio_sink_type.cc index 0510c982cb27..1bf89cfcee24 100644 --- a/starboard/shared/starboard/audio_sink/stub_audio_sink_type.cc +++ b/starboard/shared/starboard/audio_sink/stub_audio_sink_type.cc @@ -17,10 +17,10 @@ #include #include "starboard/common/mutex.h" +#include "starboard/common/time.h" #include "starboard/configuration.h" #include "starboard/configuration_constants.h" #include "starboard/thread.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -113,12 +113,11 @@ void StubAudioSink::AudioThreadFunc() { int frames_to_consume = std::min(kMaxFramesToConsumePerRequest, frames_in_buffer); - SbThreadSleep(frames_to_consume * kSbTimeSecond / sampling_frequency_hz_); - consume_frames_func_(frames_to_consume, SbTimeGetMonotonicNow(), - context_); + SbThreadSleep(frames_to_consume * 1'000'000LL / sampling_frequency_hz_); + consume_frames_func_(frames_to_consume, CurrentMonotonicTime(), context_); } else { // Wait for five millisecond if we are paused. - SbThreadSleep(kSbTimeMillisecond * 5); + SbThreadSleep(5'000); } } } diff --git a/starboard/shared/starboard/event_schedule.cc b/starboard/shared/starboard/event_schedule.cc index 1f318673e4d2..d33dea0d1349 100644 --- a/starboard/shared/starboard/event_schedule.cc +++ b/starboard/shared/starboard/event_schedule.cc @@ -18,7 +18,7 @@ SbEventId SbEventSchedule(SbEventCallback callback, void* context, - SbTime delay) { + int64_t delay) { return starboard::shared::starboard::Application::Get()->Schedule( callback, context, delay); } diff --git a/starboard/shared/starboard/media/media_get_buffer_garbage_collection_duration_threshold.cc b/starboard/shared/starboard/media/media_get_buffer_garbage_collection_duration_threshold.cc index a89285c525ef..2cbf9216ab61 100644 --- a/starboard/shared/starboard/media/media_get_buffer_garbage_collection_duration_threshold.cc +++ b/starboard/shared/starboard/media/media_get_buffer_garbage_collection_duration_threshold.cc @@ -14,6 +14,6 @@ #include "starboard/media.h" -SbTime SbMediaGetBufferGarbageCollectionDurationThreshold() { - return 170 * kSbTimeSecond; +int64_t SbMediaGetBufferGarbageCollectionDurationThreshold() { + return 170'000'000; // 170 seconds } diff --git a/starboard/shared/starboard/media/media_util.cc b/starboard/shared/starboard/media/media_util.cc index ce7e533afc7e..e0541d47dc08 100644 --- a/starboard/shared/starboard/media/media_util.cc +++ b/starboard/shared/starboard/media/media_util.cc @@ -452,18 +452,18 @@ bool IsAudioSampleInfoSubstantiallyDifferent(const AudioStreamInfo& left, left.audio_specific_config != right.audio_specific_config; } -int AudioDurationToFrames(SbTime duration, int samples_per_second) { +int AudioDurationToFrames(int64_t duration, int samples_per_second) { SB_DCHECK(samples_per_second > 0) << "samples_per_second has to be greater than 0"; - // The same as `frames = (duration / kSbTimeSecond) * samples_per_second`, + // The same as `frames = (duration / 1'000'000) * samples_per_second`, // switch order to avoid precision loss due to integer division. - return duration * samples_per_second / kSbTimeSecond; + return duration * samples_per_second / 1'000'000LL; } -SbTime AudioFramesToDuration(int frames, int samples_per_second) { +int64_t AudioFramesToDuration(int frames, int samples_per_second) { SB_DCHECK(samples_per_second > 0) << "samples_per_second has to be greater than 0"; - return frames * kSbTimeSecond / std::max(samples_per_second, 1); + return frames * 1'000'000LL / std::max(samples_per_second, 1); } } // namespace media diff --git a/starboard/shared/starboard/media/media_util.h b/starboard/shared/starboard/media/media_util.h index e4f3ddb19e95..030a53fd084c 100644 --- a/starboard/shared/starboard/media/media_util.h +++ b/starboard/shared/starboard/media/media_util.h @@ -83,8 +83,8 @@ struct AudioSampleInfo { // `SbMediaAudioSampleInfo` defined in `media.h`. Please refer to the comment // of `SbMediaAudioSampleInfo` for more details. AudioStreamInfo stream_info; - SbTime discarded_duration_from_front = 0; - SbTime discarded_duration_from_back = 0; + int64_t discarded_duration_from_front = 0; // in microseconds. + int64_t discarded_duration_from_back = 0; // in microseconds. }; // Encapsulates all information contained in `SbMediaVideoStreamInfo`. It @@ -164,8 +164,9 @@ std::string GetMixedRepresentation(const uint8_t* data, bool IsAudioSampleInfoSubstantiallyDifferent(const AudioStreamInfo& left, const AudioStreamInfo& right); -int AudioDurationToFrames(SbTime duration, int samples_per_second); -SbTime AudioFramesToDuration(int frames, int samples_per_second); +// Durations are in microseconds. +int AudioDurationToFrames(int64_t duration, int samples_per_second); +int64_t AudioFramesToDuration(int frames, int samples_per_second); } // namespace media } // namespace starboard diff --git a/starboard/shared/starboard/media/media_util_test.cc b/starboard/shared/starboard/media/media_util_test.cc index cdf3161de820..a76f5c4059e1 100644 --- a/starboard/shared/starboard/media/media_util_test.cc +++ b/starboard/shared/starboard/media/media_util_test.cc @@ -299,16 +299,16 @@ TEST(VideoSampleInfoTest, CobaltExtensionEnhancedAudioMediaVideoSampleInfo) { TEST(MediaUtilTest, AudioDurationToFrames) { EXPECT_EQ(AudioDurationToFrames(0, 48000), 0); - EXPECT_EQ(AudioDurationToFrames(kSbTimeSecond / 2, 48000), 48000 / 2); - EXPECT_EQ(AudioDurationToFrames(kSbTimeSecond, 48000), 48000); - EXPECT_EQ(AudioDurationToFrames(kSbTimeSecond * 2, 48000), 48000 * 2); + EXPECT_EQ(AudioDurationToFrames(1'000'000LL / 2, 48000), 48000 / 2); + EXPECT_EQ(AudioDurationToFrames(1'000'000LL, 48000), 48000); + EXPECT_EQ(AudioDurationToFrames(1'000'000LL * 2, 48000), 48000 * 2); } TEST(MediaUtilTest, AudioFramesToDuration) { EXPECT_EQ(AudioFramesToDuration(0, 48000), 0); - EXPECT_EQ(AudioFramesToDuration(48000 / 2, 48000), kSbTimeSecond / 2); - EXPECT_EQ(AudioFramesToDuration(48000, 48000), kSbTimeSecond); - EXPECT_EQ(AudioFramesToDuration(48000 * 2, 48000), kSbTimeSecond * 2); + EXPECT_EQ(AudioFramesToDuration(48000 / 2, 48000), 1'000'000LL / 2); + EXPECT_EQ(AudioFramesToDuration(48000, 48000), 1'000'000LL); + EXPECT_EQ(AudioFramesToDuration(48000 * 2, 48000), 1'000'000LL * 2); } } // namespace diff --git a/starboard/shared/starboard/net_args.cc b/starboard/shared/starboard/net_args.cc index ea4ce74f7d47..860b1b7b0575 100644 --- a/starboard/shared/starboard/net_args.cc +++ b/starboard/shared/starboard/net_args.cc @@ -19,9 +19,9 @@ #include "starboard/common/scoped_ptr.h" #include "starboard/common/socket.h" +#include "starboard/common/time.h" #include "starboard/socket_waiter.h" #include "starboard/thread.h" -#include "starboard/time.h" #ifndef NET_ARGS_PORT #define NET_ARGS_PORT 49355 @@ -77,19 +77,19 @@ void WaitUntilReadableOrConnectionReset(SbSocket sock) { } scoped_ptr WaitForClientConnection(Socket* listen_sock, - SbTime timeout) { - SbTimeMonotonic expire_time = (timeout >= 0) && (timeout < kSbTimeMax) - ? SbTimeGetMonotonicNow() + timeout - : kSbTimeMax; + int64_t timeout) { + int64_t expire_time = (timeout >= 0) && (timeout < kSbInt64Max) + ? CurrentMonotonicTime() + timeout + : kSbInt64Max; while (true) { scoped_ptr client_connection(listen_sock->Accept()); if (client_connection) { return client_connection.Pass(); } - if (SbTimeGetMonotonicNow() > expire_time) { + if (CurrentMonotonicTime() > expire_time) { return scoped_ptr(); } - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); } } @@ -111,7 +111,7 @@ std::vector SplitStringByLines(const std::string& string_buff) { // should be called. const char kNetArgsCommandSwitchWait[] = "net_args_wait_for_connection"; -std::vector NetArgsWaitForPayload(SbTime timeout) { +std::vector NetArgsWaitForPayload(int64_t timeout) { scoped_ptr listen = CreateListenSocket(); scoped_ptr client_connection = WaitForClientConnection(listen.get(), timeout); diff --git a/starboard/shared/starboard/net_args.h b/starboard/shared/starboard/net_args.h index 81d99b44b92a..fcee5cd24170 100644 --- a/starboard/shared/starboard/net_args.h +++ b/starboard/shared/starboard/net_args.h @@ -37,8 +37,6 @@ #include #include -#include "starboard/time.h" - namespace starboard { namespace shared { namespace starboard { @@ -48,8 +46,9 @@ namespace starboard { extern const char kNetArgsCommandSwitchWait[]; // Waits until args stream in with a socket connection and data reception. -// A timeout value of < 0 will signal infinite timeout. -std::vector NetArgsWaitForPayload(SbTime timeout); +// Timeout is in microseconds. A timeout value of < 0 will signal infinite +// timeout. +std::vector NetArgsWaitForPayload(int64_t timeout); } // namespace starboard } // namespace shared diff --git a/starboard/shared/starboard/net_log.cc b/starboard/shared/starboard/net_log.cc index 9ca41928fc36..147a70a3bfa3 100644 --- a/starboard/shared/starboard/net_log.cc +++ b/starboard/shared/starboard/net_log.cc @@ -29,6 +29,7 @@ #include "starboard/common/socket.h" #include "starboard/common/string.h" #include "starboard/common/thread.h" +#include "starboard/common/time.h" #include "starboard/once.h" #include "starboard/socket_waiter.h" @@ -267,7 +268,7 @@ class SocketListener { private: void Run(Semaphore* joined_sema) { - while (!joined_sema->TakeWait(100 * kSbTimeMillisecond)) { + while (!joined_sema->TakeWait(100'000)) { scoped_ptr client_connection(listen_socket_->Accept()); if (client_connection) { @@ -314,7 +315,7 @@ class NetLogServer { ScopedLock lock(socket_mutex_); client_socket_ = client_socket.Pass(); client_socket_->SetSendBufferSize(NET_LOG_SOCKET_BUFFER_SIZE); - client_socket_->SetTcpKeepAlive(true, kSbTimeSecond); + client_socket_->SetTcpKeepAlive(true, 1'000'000); } // Has a client ever connected? @@ -430,21 +431,21 @@ class ScopeGuard { const char kNetLogCommandSwitchWait[] = "net_log_wait_for_connection"; -void NetLogWaitForClientConnected(SbTime timeout) { +void NetLogWaitForClientConnected(int64_t timeout) { #if !SB_LOGGING_IS_OFFICIAL_BUILD ScopeGuard guard; if (guard.IsEnabled()) { - SbTimeMonotonic expire_time = (timeout >= 0) && (timeout < kSbTimeMax) - ? SbTimeGetMonotonicNow() + timeout - : kSbTimeMax; + int64_t expire_time = (timeout >= 0) && (timeout < kSbInt64Max) + ? CurrentMonotonicTime() + timeout + : kSbInt64Max; while (true) { if (NetLogServer::Instance()->HasClientConnected()) { break; } - if (SbTimeGetMonotonicNow() > expire_time) { + if (CurrentMonotonicTime() > expire_time) { break; } - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); } } #endif diff --git a/starboard/shared/starboard/net_log.h b/starboard/shared/starboard/net_log.h index 5695cf17425c..91f479104b86 100644 --- a/starboard/shared/starboard/net_log.h +++ b/starboard/shared/starboard/net_log.h @@ -36,7 +36,6 @@ #include "starboard/common/scoped_ptr.h" #include "starboard/common/socket.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -47,8 +46,9 @@ namespace starboard { extern const char kNetLogCommandSwitchWait[]; // Optional - Pauses execution of the current thread until a client has -// connected. A timeout value of < 0 will signal infinite timeout. -void NetLogWaitForClientConnected(SbTime timeout); +// connected. Timeout is in microseconds. A timeout value of < 0 will signal +// infinite timeout. +void NetLogWaitForClientConnected(int64_t timeout); // Writes to the netlog buffer socket stream. // Note that the NetLog is completely disabled for official diff --git a/starboard/shared/starboard/player/decoded_audio_internal.cc b/starboard/shared/starboard/player/decoded_audio_internal.cc index 61fffb63a018..f07afa806637 100644 --- a/starboard/shared/starboard/player/decoded_audio_internal.cc +++ b/starboard/shared/starboard/player/decoded_audio_internal.cc @@ -57,7 +57,7 @@ DecodedAudio::DecodedAudio() DecodedAudio::DecodedAudio(int channels, SbMediaAudioSampleType sample_type, SbMediaAudioFrameStorageType storage_type, - SbTime timestamp, + int64_t timestamp, int size_in_bytes) : channels_(channels), sample_type_(sample_type), @@ -76,7 +76,7 @@ DecodedAudio::DecodedAudio(int channels, DecodedAudio::DecodedAudio(int channels, SbMediaAudioSampleType sample_type, SbMediaAudioFrameStorageType storage_type, - SbTime timestamp, + int64_t timestamp, int size_in_bytes, Buffer&& storage) : channels_(channels), @@ -108,7 +108,7 @@ void DecodedAudio::ShrinkTo(int new_size_in_bytes) { size_in_bytes_ = new_size_in_bytes; } -void DecodedAudio::AdjustForSeekTime(int sample_rate, SbTime seeking_to_time) { +void DecodedAudio::AdjustForSeekTime(int sample_rate, int64_t seeking_to_time) { SB_DCHECK(!is_end_of_stream()); SB_DCHECK(sample_rate != 0); @@ -155,8 +155,8 @@ void DecodedAudio::AdjustForSeekTime(int sample_rate, SbTime seeking_to_time) { void DecodedAudio::AdjustForDiscardedDurations( int sample_rate, - SbTime discarded_duration_from_front, - SbTime discarded_duration_from_back) { + int64_t discarded_duration_from_front, + int64_t discarded_duration_from_back) { SB_DCHECK(discarded_duration_from_front >= 0); SB_DCHECK(discarded_duration_from_back >= 0); SB_DCHECK(storage_type() == kSbMediaAudioFrameStorageTypeInterleaved); diff --git a/starboard/shared/starboard/player/decoded_audio_internal.h b/starboard/shared/starboard/player/decoded_audio_internal.h index 0e9d20de625c..aa25e7b12414 100644 --- a/starboard/shared/starboard/player/decoded_audio_internal.h +++ b/starboard/shared/starboard/player/decoded_audio_internal.h @@ -39,13 +39,13 @@ class DecodedAudio : public RefCountedThreadSafe { DecodedAudio(int channels, SbMediaAudioSampleType sample_type, SbMediaAudioFrameStorageType storage_type, - SbTime timestamp, + int64_t timestamp, int size_in_bytes); DecodedAudio(int channels, SbMediaAudioSampleType sample_type, SbMediaAudioFrameStorageType storage_type, - SbTime timestamp, + int64_t timestamp, int size_in_bytes, Buffer&& storage); @@ -54,7 +54,7 @@ class DecodedAudio : public RefCountedThreadSafe { SbMediaAudioFrameStorageType storage_type() const { return storage_type_; } bool is_end_of_stream() const { return channels_ == 0; } - SbTime timestamp() const { return timestamp_; } + int64_t timestamp() const { return timestamp_; } const uint8_t* data() const { return storage_.data() + offset_in_bytes_; } const int16_t* data_as_int16() const { return reinterpret_cast(storage_.data() + offset_in_bytes_); @@ -78,10 +78,10 @@ class DecodedAudio : public RefCountedThreadSafe { // During seeking, the target time can be in the middle of the DecodedAudio // object. This function will adjust the object to the seek target time by // removing the frames in the beginning that are before the seek target time. - void AdjustForSeekTime(int sample_rate, SbTime seeking_to_time); + void AdjustForSeekTime(int sample_rate, int64_t seeking_to_time); void AdjustForDiscardedDurations(int sample_rate, - SbTime discarded_duration_from_front, - SbTime discarded_duration_from_back); + int64_t discarded_duration_from_front, + int64_t discarded_duration_from_back); bool IsFormat(SbMediaAudioSampleType sample_type, SbMediaAudioFrameStorageType storage_type) const; @@ -101,8 +101,8 @@ class DecodedAudio : public RefCountedThreadSafe { const int channels_; const SbMediaAudioSampleType sample_type_; const SbMediaAudioFrameStorageType storage_type_; - // The timestamp of the first audio frame. - SbTime timestamp_; + // The timestamp of the first audio frame in microseconds. + int64_t timestamp_; Buffer storage_; // The audio samples to be played are stored in the memory region starts from // `storage_.data() + offset_in_bytes_`, `size_in_bytes_` bytes in total. diff --git a/starboard/shared/starboard/player/decoded_audio_test_internal.cc b/starboard/shared/starboard/player/decoded_audio_test_internal.cc index 302927d68589..b9a213af5e13 100644 --- a/starboard/shared/starboard/player/decoded_audio_test_internal.cc +++ b/starboard/shared/starboard/player/decoded_audio_test_internal.cc @@ -30,7 +30,7 @@ namespace { using ::starboard::shared::starboard::media::GetBytesPerSample; constexpr int kChannels = 2; -constexpr SbTime kTimestamp = kSbTimeSecond; +constexpr int64_t kTimestampUsec = 1'000'000; constexpr int kSizeInBytes = 4192; constexpr int kSampleRate = 22050; @@ -190,7 +190,7 @@ TEST(DecodedAudioTest, CtorWithSize) { for (auto sample_type : kSampleTypes) { for (auto storage_type : kStorageTypes) { scoped_refptr decoded_audio(new DecodedAudio( - kChannels, sample_type, storage_type, kTimestamp, kSizeInBytes)); + kChannels, sample_type, storage_type, kTimestampUsec, kSizeInBytes)); EXPECT_FALSE(decoded_audio->is_end_of_stream()); EXPECT_EQ(decoded_audio->channels(), kChannels); @@ -214,8 +214,8 @@ TEST(DecodedAudioTest, CtorWithMoveCtor) { const uint8_t* original_data_pointer = original.data(); scoped_refptr decoded_audio( - new DecodedAudio(kChannels, kSampleTypes[0], kStorageTypes[0], kTimestamp, - 128, std::move(original))); + new DecodedAudio(kChannels, kSampleTypes[0], kStorageTypes[0], + kTimestampUsec, 128, std::move(original))); ASSERT_EQ(decoded_audio->size_in_bytes(), 128); ASSERT_NE(decoded_audio->data(), nullptr); ASSERT_EQ(decoded_audio->data(), original_data_pointer); @@ -230,7 +230,7 @@ TEST(DecodedAudioTest, AdjustForSeekTime) { for (auto sample_type : kSampleTypes) { scoped_refptr original_decoded_audio(new DecodedAudio( kChannels, sample_type, kSbMediaAudioFrameStorageTypeInterleaved, - kTimestamp, kSizeInBytes)); + kTimestampUsec, kSizeInBytes)); Fill(&original_decoded_audio); scoped_refptr adjusted_decoded_audio = @@ -244,24 +244,23 @@ TEST(DecodedAudioTest, AdjustForSeekTime) { // Adjust to an invalid timestamp before the time range of // `adjusted_decoded_audio`, it's a no-op. adjusted_decoded_audio->AdjustForSeekTime( - kSampleRate, adjusted_decoded_audio->timestamp() - kSbTimeSecond / 2); + kSampleRate, adjusted_decoded_audio->timestamp() - 1'000'000LL / 2); ASSERT_EQ(*original_decoded_audio, *adjusted_decoded_audio); // Adjust to an invalid timestamp after the time range of // `adjusted_decoded_audio`, it's also a no-op. adjusted_decoded_audio->AdjustForSeekTime( - kSampleRate, - adjusted_decoded_audio->timestamp() + kSbTimeSecond * 100); + kSampleRate, adjusted_decoded_audio->timestamp() + 1'000'000LL * 100); ASSERT_EQ(*original_decoded_audio, *adjusted_decoded_audio); - const SbTime duration = media::AudioFramesToDuration( + const int64_t duration = media::AudioFramesToDuration( adjusted_decoded_audio->frames(), kSampleRate); - const SbTime duration_of_one_frame = + const int64_t duration_of_one_frame = media::AudioFramesToDuration(1, kSampleRate) + 1; for (int i = 1; i < 10; ++i) { adjusted_decoded_audio = original_decoded_audio->Clone(); // Adjust to the middle of `adjusted_decoded_audio`. - SbTime seek_time = + int64_t seek_time = adjusted_decoded_audio->timestamp() + duration * i / 10; adjusted_decoded_audio->AdjustForSeekTime(kSampleRate, seek_time); ASSERT_NEAR(adjusted_decoded_audio->frames(), @@ -286,7 +285,7 @@ TEST(DecodedAudioTest, AdjustForDiscardedDurations) { for (auto sample_type : kSampleTypes) { scoped_refptr original_decoded_audio(new DecodedAudio( kChannels, sample_type, kSbMediaAudioFrameStorageTypeInterleaved, - kTimestamp, kSizeInBytes)); + kTimestampUsec, kSizeInBytes)); Fill(&original_decoded_audio); scoped_refptr adjusted_decoded_audio = @@ -329,9 +328,9 @@ TEST(DecodedAudioTest, AdjustForDiscardedDurations) { TEST(DecodedAudioTest, SwitchFormatTo) { for (auto original_sample_type : kSampleTypes) { for (auto original_storage_type : kStorageTypes) { - scoped_refptr original_decoded_audio( - new DecodedAudio(kChannels, original_sample_type, - original_storage_type, kTimestamp, kSizeInBytes)); + scoped_refptr original_decoded_audio(new DecodedAudio( + kChannels, original_sample_type, original_storage_type, + kTimestampUsec, kSizeInBytes)); Fill(&original_decoded_audio); @@ -365,7 +364,7 @@ TEST(DecodedAudioTest, Clone) { for (auto sample_type : kSampleTypes) { scoped_refptr decoded_audio(new DecodedAudio( kChannels, sample_type, kSbMediaAudioFrameStorageTypeInterleaved, - kTimestamp, kSizeInBytes)); + kTimestampUsec, kSizeInBytes)); Fill(&decoded_audio); auto copy = decoded_audio->Clone(); ASSERT_EQ(*copy, *decoded_audio); diff --git a/starboard/shared/starboard/player/filter/audio_frame_discarder.cc b/starboard/shared/starboard/player/filter/audio_frame_discarder.cc index b8f2c36a9888..e1933e778b21 100644 --- a/starboard/shared/starboard/player/filter/audio_frame_discarder.cc +++ b/starboard/shared/starboard/player/filter/audio_frame_discarder.cc @@ -69,9 +69,9 @@ void AudioFrameDiscarder::AdjustForDiscardedDurations( // We accept a small offset due to the precision of computation. If the // outputs have different timestamps than inputs, discarded durations will be // ignored. - const SbTimeMonotonic kTimestampOffset = 10; + const int64_t kTimestampOffsetUsec = 10; if (std::abs(input_info.timestamp - (*decoded_audio)->timestamp()) > - kTimestampOffset) { + kTimestampOffsetUsec) { SB_LOG(WARNING) << "Inconsistent timestamps between InputBuffer (@" << input_info.timestamp << ") and DecodedAudio (@" << (*decoded_audio)->timestamp() << ")."; diff --git a/starboard/shared/starboard/player/filter/audio_frame_discarder.h b/starboard/shared/starboard/player/filter/audio_frame_discarder.h index 80f5fbeb2e74..bb314a583357 100644 --- a/starboard/shared/starboard/player/filter/audio_frame_discarder.h +++ b/starboard/shared/starboard/player/filter/audio_frame_discarder.h @@ -22,7 +22,6 @@ #include "starboard/shared/internal_only.h" #include "starboard/shared/starboard/player/decoded_audio_internal.h" #include "starboard/shared/starboard/player/input_buffer_internal.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -47,9 +46,9 @@ class AudioFrameDiscarder { private: struct InputBufferInfo { - SbTime timestamp; - SbTime discarded_duration_from_front; - SbTime discarded_duration_from_back; + int64_t timestamp; // microseconds + int64_t discarded_duration_from_front; // microseconds + int64_t discarded_duration_from_back; // microseconds }; static constexpr size_t kMaxNumberOfPendingInputBufferInfos = 128; diff --git a/starboard/shared/starboard/player/filter/audio_renderer_internal_pcm.cc b/starboard/shared/starboard/player/filter/audio_renderer_internal_pcm.cc index 107d2ae96f31..676aad853e97 100644 --- a/starboard/shared/starboard/player/filter/audio_renderer_internal_pcm.cc +++ b/starboard/shared/starboard/player/filter/audio_renderer_internal_pcm.cc @@ -17,6 +17,7 @@ #include #include +#include "starboard/common/time.h" #include "starboard/memory.h" #include "starboard/shared/starboard/media/media_util.h" @@ -77,7 +78,7 @@ AudioRendererPcm::AudioRendererPcm( sink_sample_type_(GetSinkAudioSampleType(audio_renderer_sink.get())), bytes_per_frame_(media::GetBytesPerSample(sink_sample_type_) * channels_), frame_buffer_(max_cached_frames_ * bytes_per_frame_), - frames_consumed_set_at_(SbTimeGetMonotonicNow()), + frames_consumed_set_at_(CurrentMonotonicTime()), decoder_(decoder.Pass()), process_audio_data_job_( std::bind(&AudioRendererPcm::ProcessAudioData, this)), @@ -222,7 +223,7 @@ void AudioRendererPcm::SetPlaybackRate(double playback_rate) { } } -void AudioRendererPcm::Seek(SbTime seek_to_time) { +void AudioRendererPcm::Seek(int64_t seek_to_time) { SB_DCHECK(BelongsToCurrentThread()); SB_DCHECK(seek_to_time >= 0); @@ -233,7 +234,7 @@ void AudioRendererPcm::Seek(SbTime seek_to_time) { // GetCurrentMediaTime() returns |seeking_to_time_|. ScopedLock scoped_lock(mutex_); eos_state_ = kEOSNotReceived; - seeking_to_time_ = std::max(seek_to_time, 0); + seeking_to_time_ = std::max(seek_to_time, 0); last_media_time_ = seek_to_time; ended_cb_called_ = false; seeking_ = true; @@ -251,7 +252,7 @@ void AudioRendererPcm::Seek(SbTime seek_to_time) { frames_consumed_by_sink_since_last_get_current_time_ = 0; pending_decoder_outputs_ = 0; audio_frame_tracker_.Reset(); - frames_consumed_set_at_ = SbTimeGetMonotonicNow(); + frames_consumed_set_at_ = CurrentMonotonicTime(); can_accept_more_data_ = true; process_audio_data_job_token_.ResetToInvalid(); @@ -276,18 +277,18 @@ void AudioRendererPcm::Seek(SbTime seek_to_time) { #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK } -SbTime AudioRendererPcm::GetCurrentMediaTime(bool* is_playing, - bool* is_eos_played, - bool* is_underflow, - double* playback_rate) { +int64_t AudioRendererPcm::GetCurrentMediaTime(bool* is_playing, + bool* is_eos_played, + bool* is_underflow, + double* playback_rate) { SB_DCHECK(is_playing); SB_DCHECK(is_eos_played); SB_DCHECK(is_underflow); SB_DCHECK(playback_rate); - SbTime media_time = 0; - SbTimeMonotonic now = -1; - SbTimeMonotonic elasped_since_last_set = 0; + int64_t media_time = 0; + int64_t now = -1; + int64_t elasped_since_last_set = 0; int64_t frames_played = 0; int samples_per_second = 1; @@ -317,17 +318,17 @@ SbTime AudioRendererPcm::GetCurrentMediaTime(bool* is_playing, // a long delay. So ensure that ConsumeFrames() is called after Play() // before taking elapsed time into account. if (!paused_ && playback_rate_ > 0.f && consume_frames_called_) { - now = SbTimeGetMonotonicNow(); + now = CurrentMonotonicTime(); elasped_since_last_set = now - frames_consumed_set_at_; } samples_per_second = *decoder_sample_rate_; int64_t elapsed_frames = - elasped_since_last_set * samples_per_second / kSbTimeSecond; + elasped_since_last_set * samples_per_second / 1'000'000LL; frames_played = audio_frame_tracker_.GetFutureFramesPlayedAdjustedToPlaybackRate( elapsed_frames, playback_rate); media_time = - seeking_to_time_ + frames_played * kSbTimeSecond / samples_per_second; + seeking_to_time_ + frames_played * 1'000'000LL / samples_per_second; if (media_time < last_media_time_) { #if SB_LOG_MEDIA_TIME_STATS SB_LOG(WARNING) << "Audio time runs backwards from " << last_media_time_ @@ -343,8 +344,8 @@ SbTime AudioRendererPcm::GetCurrentMediaTime(bool* is_playing, system_and_media_time_offset_ = now - media_time; } if (system_and_media_time_offset_ > 0) { - SbTime offset = now - media_time; - SbTime drift = offset - system_and_media_time_offset_; + int64_t offset = now - media_time; + int64_t drift = offset - system_and_media_time_offset_; min_drift_ = std::min(drift, min_drift_); max_drift_ = std::max(drift, max_drift_); SB_LOG(ERROR) << "Media time stats: (" << now << "-" @@ -356,7 +357,7 @@ SbTime AudioRendererPcm::GetCurrentMediaTime(bool* is_playing, // How long the audio frames left in sink can be played. << (total_frames_sent_to_sink_ - total_frames_consumed_by_sink_) * - kSbTimeSecond / samples_per_second; + 1'000'000LL / samples_per_second; } #endif // SB_LOG_MEDIA_TIME_STATS @@ -421,7 +422,7 @@ void AudioRendererPcm::GetSourceStatus(int* frames_in_buffer, } void AudioRendererPcm::ConsumeFrames(int frames_consumed, - SbTime frames_consumed_at) { + int64_t frames_consumed_at) { #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK sink_callbacks_since_last_check_.increment(); #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK @@ -462,7 +463,7 @@ void AudioRendererPcm::OnError(bool capability_changed, } void AudioRendererPcm::UpdateVariablesOnSinkThread_Locked( - SbTime system_time_on_consume_frames) { + int64_t system_time_on_consume_frames) { mutex_.DCheckAcquired(); if (frames_consumed_on_sink_thread_ > 0) { @@ -590,8 +591,8 @@ void AudioRendererPcm::ProcessAudioData() { if (audio_renderer_sink_->HasStarted() && time_stretcher_.IsQueueFull()) { // There is no room to do any further processing, schedule the function // again for a later time. The delay time is 1/4 of the buffer size. - const SbTimeMonotonic delay = - max_cached_frames_ * kSbTimeSecond / *decoder_sample_rate_ / 4; + const int64_t delay = + max_cached_frames_ * 1'000'000LL / *decoder_sample_rate_ / 4; process_audio_data_job_token_ = Schedule(process_audio_data_job_, delay); return; } @@ -657,20 +658,19 @@ void AudioRendererPcm::ProcessAudioData() { } if (seeking_ || playback_rate_ == 0.0) { - process_audio_data_job_token_ = - Schedule(process_audio_data_job_, 5 * kSbTimeMillisecond); + process_audio_data_job_token_ = Schedule(process_audio_data_job_, 5'000); return; } if (is_frame_buffer_full) { // There are still audio data not appended so schedule a callback later. - SbTimeMonotonic delay = 0; + int64_t delay = 0; int64_t frames_in_buffer = total_frames_sent_to_sink_ - total_frames_consumed_by_sink_; if (max_cached_frames_ - frames_in_buffer < max_cached_frames_ / 4) { int frames_to_delay = static_cast( max_cached_frames_ / 4 - (max_cached_frames_ - frames_in_buffer)); - delay = frames_to_delay * kSbTimeSecond / *decoder_sample_rate_; + delay = frames_to_delay * 1'000'000LL / *decoder_sample_rate_; } process_audio_data_job_token_ = Schedule(process_audio_data_job_, delay); } @@ -764,11 +764,11 @@ void AudioRendererPcm::CheckAudioSinkStatus() { } // Check if sink has updated. - SbTimeMonotonic elapsed = SbTimeGetMonotonicNow() - frames_consumed_set_at_; + int64_t elapsed = CurrentMonotonicTime() - frames_consumed_set_at_; if (elapsed > kCheckAudioSinkStatusInterval) { ScopedLock lock(mutex_); SB_DLOG(WARNING) << "|frames_consumed_| has not been updated for " - << elapsed / kSbTimeSecond << " seconds, with " + << elapsed / 1'000'000LL << " seconds, with " << total_frames_sent_to_sink_ - total_frames_consumed_by_sink_ << " frames in sink, " << (underflow_ ? "underflow, " : "") diff --git a/starboard/shared/starboard/player/filter/audio_renderer_internal_pcm.h b/starboard/shared/starboard/player/filter/audio_renderer_internal_pcm.h index fd7ce93c49e3..2af3cc1787f4 100644 --- a/starboard/shared/starboard/player/filter/audio_renderer_internal_pcm.h +++ b/starboard/shared/starboard/player/filter/audio_renderer_internal_pcm.h @@ -37,7 +37,6 @@ #include "starboard/shared/starboard/player/filter/media_time_provider.h" #include "starboard/shared/starboard/player/input_buffer_internal.h" #include "starboard/shared/starboard/player/job_queue.h" -#include "starboard/time.h" #include "starboard/types.h" // Uncomment the following statement to log the media time stats with deviation @@ -91,11 +90,11 @@ class AudioRendererPcm : public AudioRenderer, void Play() override; void Pause() override; void SetPlaybackRate(double playback_rate) override; - void Seek(SbTime seek_to_time) override; - SbTime GetCurrentMediaTime(bool* is_playing, - bool* is_eos_played, - bool* is_underflow, - double* playback_rate) override; + void Seek(int64_t seek_to_time) override; + int64_t GetCurrentMediaTime(bool* is_playing, + bool* is_eos_played, + bool* is_underflow, + double* playback_rate) override; private: enum EOSState { @@ -120,8 +119,8 @@ class AudioRendererPcm : public AudioRenderer, bool paused_ = true; bool consume_frames_called_ = false; bool seeking_ = false; - SbTime seeking_to_time_ = 0; - SbTime last_media_time_ = 0; + int64_t seeking_to_time_ = 0; // microseconds + int64_t last_media_time_ = 0; // microseconds AudioFrameTracker audio_frame_tracker_; bool ended_cb_called_ = false; @@ -139,11 +138,12 @@ class AudioRendererPcm : public AudioRenderer, int* offset_in_frames, bool* is_playing, bool* is_eos_reached) override; - void ConsumeFrames(int frames_consumed, SbTime frames_consumed_at) override; + void ConsumeFrames(int frames_consumed, int64_t frames_consumed_at) override; void OnError(bool capability_changed, const std::string& error_message) override; - void UpdateVariablesOnSinkThread_Locked(SbTime system_time_on_consume_frames); + void UpdateVariablesOnSinkThread_Locked( + int64_t system_time_on_consume_frames); void OnFirstOutput(const SbMediaAudioSampleType decoded_sample_type, const SbMediaAudioFrameStorageType decoded_storage_type, @@ -187,13 +187,13 @@ class AudioRendererPcm : public AudioRenderer, int64_t frames_in_buffer_on_sink_thread_ = 0; int64_t offset_in_frames_on_sink_thread_ = 0; int64_t frames_consumed_on_sink_thread_ = 0; - SbTime frames_consumed_set_at_on_sink_thread_ = 0; + int64_t frames_consumed_set_at_on_sink_thread_ = 0; // microseconds int64_t silence_frames_written_after_eos_on_sink_thread_ = 0; #if SB_LOG_MEDIA_TIME_STATS - SbTime system_and_media_time_offset_ = -1; - SbTime min_drift_ = kSbTimeMax; - SbTime max_drift_ = 0; + int64_t system_and_media_time_offset_ = -1; // microseconds + int64_t min_drift_ = kSbInt64Max; // microseconds + int64_t max_drift_ = 0; // microseconds int64_t total_frames_consumed_ = 0; #endif // SB_LOG_MEDIA_TIME_STATS @@ -203,7 +203,7 @@ class AudioRendererPcm : public AudioRenderer, #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK static const int32_t kMaxSinkCallbacksBetweenCheck = 1024; - static const SbTime kCheckAudioSinkStatusInterval = kSbTimeSecond; + static const int64_t kCheckAudioSinkStatusInterval = 1'000'000; // 1 second void CheckAudioSinkStatus(); atomic_int32_t sink_callbacks_since_last_check_; diff --git a/starboard/shared/starboard/player/filter/audio_renderer_sink.h b/starboard/shared/starboard/player/filter/audio_renderer_sink.h index de4e394c06e7..416254186fdb 100644 --- a/starboard/shared/starboard/player/filter/audio_renderer_sink.h +++ b/starboard/shared/starboard/player/filter/audio_renderer_sink.h @@ -19,7 +19,6 @@ #include "starboard/audio_sink.h" #include "starboard/shared/internal_only.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -37,7 +36,7 @@ class AudioRendererSink { bool* is_playing, bool* is_eos_reached) = 0; virtual void ConsumeFrames(int frames_consumed, - SbTime frames_consumed_at) = 0; + int64_t frames_consumed_at) = 0; // When |capability_changed| is true, it hints that the error is caused by a // a transient capability on the platform. The app should retry playback @@ -59,7 +58,7 @@ class AudioRendererSink { int sampling_frequency_hz) const = 0; virtual bool HasStarted() const = 0; - virtual void Start(SbTime media_start_time, + virtual void Start(int64_t media_start_time, int channels, int sampling_frequency_hz, SbMediaAudioSampleType audio_sample_type, diff --git a/starboard/shared/starboard/player/filter/audio_renderer_sink_impl.cc b/starboard/shared/starboard/player/filter/audio_renderer_sink_impl.cc index c9136ae56be6..1f7ad987833e 100644 --- a/starboard/shared/starboard/player/filter/audio_renderer_sink_impl.cc +++ b/starboard/shared/starboard/player/filter/audio_renderer_sink_impl.cc @@ -28,7 +28,7 @@ namespace filter { AudioRendererSinkImpl::AudioRendererSinkImpl() : create_audio_sink_func_( - [](SbTime start_media_time, + [](int64_t start_media_time, int channels, int sampling_frequency_hz, SbMediaAudioSampleType audio_sample_type, @@ -78,7 +78,7 @@ bool AudioRendererSinkImpl::HasStarted() const { } void AudioRendererSinkImpl::Start( - SbTime media_start_time, + int64_t media_start_time, int channels, int sampling_frequency_hz, SbMediaAudioSampleType audio_sample_type, @@ -167,7 +167,7 @@ void AudioRendererSinkImpl::UpdateSourceStatusFunc(int* frames_in_buffer, // static void AudioRendererSinkImpl::ConsumeFramesFunc(int frames_consumed, - SbTime frames_consumed_at, + int64_t frames_consumed_at, void* context) { AudioRendererSinkImpl* audio_renderer_sink = static_cast(context); diff --git a/starboard/shared/starboard/player/filter/audio_renderer_sink_impl.h b/starboard/shared/starboard/player/filter/audio_renderer_sink_impl.h index bc60aa12d9f9..ce5099584ba9 100644 --- a/starboard/shared/starboard/player/filter/audio_renderer_sink_impl.h +++ b/starboard/shared/starboard/player/filter/audio_renderer_sink_impl.h @@ -33,7 +33,7 @@ namespace filter { class AudioRendererSinkImpl : public AudioRendererSink { public: typedef std::function(kSbTimeSecond / kSbTimeMillisecond); + const double kMillisecondsPerSeconds = 1000; return static_cast(ms * (samples_per_second_ / kMillisecondsPerSeconds)); } diff --git a/starboard/shared/starboard/player/filter/cpu_video_frame.cc b/starboard/shared/starboard/player/filter/cpu_video_frame.cc index 4b693a791baa..991fad01dbbc 100644 --- a/starboard/shared/starboard/player/filter/cpu_video_frame.cc +++ b/starboard/shared/starboard/player/filter/cpu_video_frame.cc @@ -185,7 +185,7 @@ scoped_refptr CpuVideoFrame::CreateYV12Frame( int height, int source_y_pitch_in_bytes, int source_uv_pitch_in_bytes, - SbTime timestamp, + int64_t timestamp, const uint8_t* y, const uint8_t* u, const uint8_t* v) { diff --git a/starboard/shared/starboard/player/filter/cpu_video_frame.h b/starboard/shared/starboard/player/filter/cpu_video_frame.h index 13c58f6d0cac..7da0ee1a7ded 100644 --- a/starboard/shared/starboard/player/filter/cpu_video_frame.h +++ b/starboard/shared/starboard/player/filter/cpu_video_frame.h @@ -55,7 +55,7 @@ class CpuVideoFrame : public VideoFrame { const uint8_t* data; }; - explicit CpuVideoFrame(SbTime timestamp) : VideoFrame(timestamp) {} + explicit CpuVideoFrame(int64_t timestamp) : VideoFrame(timestamp) {} Format format() const { return format_; } int width() const { return width_; } @@ -72,7 +72,7 @@ class CpuVideoFrame : public VideoFrame { int height, int source_y_pitch_in_bytes, int source_uv_pitch_in_bytes, - SbTime timestamp, + int64_t timestamp, // microseconds const uint8_t* y, const uint8_t* u, const uint8_t* v); diff --git a/starboard/shared/starboard/player/filter/filter_based_player_worker_handler.cc b/starboard/shared/starboard/player/filter/filter_based_player_worker_handler.cc index 0816518b90e1..14f62f045039 100644 --- a/starboard/shared/starboard/player/filter/filter_based_player_worker_handler.cc +++ b/starboard/shared/starboard/player/filter/filter_based_player_worker_handler.cc @@ -26,7 +26,6 @@ #include "starboard/shared/starboard/player/filter/audio_decoder_internal.h" #include "starboard/shared/starboard/player/filter/video_decoder_internal.h" #include "starboard/shared/starboard/player/input_buffer_internal.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -43,7 +42,7 @@ typedef shared::starboard::player::PlayerWorker::Handler::HandlerResult HandlerResult; // TODO: Make this configurable inside SbPlayerCreate(). -const SbTimeMonotonic kUpdateInterval = 200 * kSbTimeMillisecond; +const int64_t kUpdateIntervalUsec = 200'000; // 200ms #if defined(COBALT_BUILD_TYPE_GOLD) @@ -187,12 +186,12 @@ HandlerResult FilterBasedPlayerWorkerHandler::Init( kSbMediaTypeVideo)); } - update_job_token_ = Schedule(update_job_, kUpdateInterval); + update_job_token_ = Schedule(update_job_, kUpdateIntervalUsec); return HandlerResult{true}; } -HandlerResult FilterBasedPlayerWorkerHandler::Seek(SbTime seek_to_time, +HandlerResult FilterBasedPlayerWorkerHandler::Seek(int64_t seek_to_time, int ticket) { SB_DCHECK(BelongsToCurrentThread()); @@ -507,7 +506,7 @@ void FilterBasedPlayerWorkerHandler::Update() { } RemoveJobByToken(update_job_token_); - update_job_token_ = Schedule(update_job_, kUpdateInterval); + update_job_token_ = Schedule(update_job_, kUpdateIntervalUsec); } void FilterBasedPlayerWorkerHandler::Stop() { diff --git a/starboard/shared/starboard/player/filter/filter_based_player_worker_handler.h b/starboard/shared/starboard/player/filter/filter_based_player_worker_handler.h index e55377457367..3b77625082dd 100644 --- a/starboard/shared/starboard/player/filter/filter_based_player_worker_handler.h +++ b/starboard/shared/starboard/player/filter/filter_based_player_worker_handler.h @@ -32,7 +32,6 @@ #include "starboard/shared/starboard/player/input_buffer_internal.h" #include "starboard/shared/starboard/player/job_queue.h" #include "starboard/shared/starboard/player/player_worker.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -53,7 +52,7 @@ class FilterBasedPlayerWorkerHandler : public PlayerWorker::Handler, GetPlayerStateCB get_player_state_cb, UpdatePlayerStateCB update_player_state_cb, UpdatePlayerErrorCB update_player_error_cb) override; - HandlerResult Seek(SbTime seek_to_time, int ticket) override; + HandlerResult Seek(int64_t seek_to_time, int ticket) override; HandlerResult WriteSamples(const InputBuffers& input_buffers, int* samples_written) override; HandlerResult WriteEndOfStream(SbMediaType sample_type) override; diff --git a/starboard/shared/starboard/player/filter/media_time_provider.h b/starboard/shared/starboard/player/filter/media_time_provider.h index 7b2c1ad2e452..2a1374aff402 100644 --- a/starboard/shared/starboard/player/filter/media_time_provider.h +++ b/starboard/shared/starboard/player/filter/media_time_provider.h @@ -30,12 +30,12 @@ class MediaTimeProvider { virtual void Play() = 0; virtual void Pause() = 0; virtual void SetPlaybackRate(double playback_rate) = 0; - virtual void Seek(SbTime seek_to_pts) = 0; + virtual void Seek(int64_t seek_to_pts) = 0; // This function can be called from *any* thread. - virtual SbTime GetCurrentMediaTime(bool* is_playing, - bool* is_eos_played, - bool* is_underflow, - double* playback_rate) = 0; + virtual int64_t GetCurrentMediaTime(bool* is_playing, + bool* is_eos_played, + bool* is_underflow, + double* playback_rate) = 0; protected: virtual ~MediaTimeProvider() {} diff --git a/starboard/shared/starboard/player/filter/media_time_provider_impl.cc b/starboard/shared/starboard/player/filter/media_time_provider_impl.cc index 176afb34a7ca..f9df61a8bf88 100644 --- a/starboard/shared/starboard/player/filter/media_time_provider_impl.cc +++ b/starboard/shared/starboard/player/filter/media_time_provider_impl.cc @@ -64,7 +64,7 @@ void MediaTimeProviderImpl::SetPlaybackRate(double playback_rate) { playback_rate_ = playback_rate; } -void MediaTimeProviderImpl::Seek(SbTime seek_to_time) { +void MediaTimeProviderImpl::Seek(int64_t seek_to_time) { SB_DCHECK(BelongsToCurrentThread()); ScopedLock scoped_lock(mutex_); @@ -77,13 +77,13 @@ void MediaTimeProviderImpl::Seek(SbTime seek_to_time) { CancelPendingJobs(); } -SbTime MediaTimeProviderImpl::GetCurrentMediaTime(bool* is_playing, - bool* is_eos_played, - bool* is_underflow, - double* playback_rate) { +int64_t MediaTimeProviderImpl::GetCurrentMediaTime(bool* is_playing, + bool* is_eos_played, + bool* is_underflow, + double* playback_rate) { ScopedLock scoped_lock(mutex_); - SbTime current = GetCurrentMediaTime_Locked(); + int64_t current = GetCurrentMediaTime_Locked(); *is_playing = is_playing_; *is_eos_played = false; @@ -93,11 +93,11 @@ SbTime MediaTimeProviderImpl::GetCurrentMediaTime(bool* is_playing, return current; } -SbTime MediaTimeProviderImpl::GetCurrentMediaTime_Locked( - SbTimeMonotonic* current_time /*= NULL*/) { +int64_t MediaTimeProviderImpl::GetCurrentMediaTime_Locked( + int64_t* current_time /*= NULL*/) { mutex_.DCheckAcquired(); - SbTimeMonotonic now = system_time_provider_->GetMonotonicNow(); + int64_t now = system_time_provider_->GetMonotonicNow(); if (!is_playing_ || playback_rate_ == 0.0) { if (current_time) { @@ -106,7 +106,7 @@ SbTime MediaTimeProviderImpl::GetCurrentMediaTime_Locked( return seek_to_time_; } - SbTimeMonotonic elapsed = (now - seek_to_time_set_at_) * playback_rate_; + int64_t elapsed = (now - seek_to_time_set_at_) * playback_rate_; if (current_time) { *current_time = now; } diff --git a/starboard/shared/starboard/player/filter/media_time_provider_impl.h b/starboard/shared/starboard/player/filter/media_time_provider_impl.h index c619fb65a598..f783a573b2cc 100644 --- a/starboard/shared/starboard/player/filter/media_time_provider_impl.h +++ b/starboard/shared/starboard/player/filter/media_time_provider_impl.h @@ -17,11 +17,11 @@ #include "starboard/common/mutex.h" #include "starboard/common/scoped_ptr.h" +#include "starboard/common/time.h" #include "starboard/media.h" #include "starboard/shared/internal_only.h" #include "starboard/shared/starboard/player/filter/media_time_provider.h" #include "starboard/shared/starboard/player/job_queue.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -36,7 +36,7 @@ class MediaTimeProviderImpl : public MediaTimeProvider, class MonotonicSystemTimeProvider { public: virtual ~MonotonicSystemTimeProvider() {} - virtual SbTimeMonotonic GetMonotonicNow() const = 0; + virtual int64_t GetMonotonicNow() const = 0; }; explicit MediaTimeProviderImpl( @@ -45,18 +45,18 @@ class MediaTimeProviderImpl : public MediaTimeProvider, void Play() override; void Pause() override; void SetPlaybackRate(double playback_rate) override; - void Seek(SbTime seek_to_time) override; - SbTime GetCurrentMediaTime(bool* is_playing, - bool* is_eos_played, - bool* is_underflow, - double* playback_rate) override; + void Seek(int64_t seek_to_time) override; + int64_t GetCurrentMediaTime(bool* is_playing, + bool* is_eos_played, + bool* is_underflow, + double* playback_rate) override; private: // When not NULL, |current_time| will be set to the current monotonic time // used to calculate the returned media time. Note that it is possible that // |current_time| points to |seek_to_time_set_at_| and the implementation // should handle this properly. - SbTime GetCurrentMediaTime_Locked(SbTimeMonotonic* current_time = NULL); + int64_t GetCurrentMediaTime_Locked(int64_t* current_time = NULL); scoped_ptr system_time_provider_; @@ -64,8 +64,8 @@ class MediaTimeProviderImpl : public MediaTimeProvider, double playback_rate_ = 0.0; bool is_playing_ = false; - SbTime seek_to_time_ = 0; - SbTimeMonotonic seek_to_time_set_at_ = SbTimeGetMonotonicNow(); + int64_t seek_to_time_ = 0; // microseconds + int64_t seek_to_time_set_at_ = CurrentMonotonicTime(); }; } // namespace filter diff --git a/starboard/shared/starboard/player/filter/mock_audio_renderer_sink.h b/starboard/shared/starboard/player/filter/mock_audio_renderer_sink.h index f56e21f31118..fa73b516cd0d 100644 --- a/starboard/shared/starboard/player/filter/mock_audio_renderer_sink.h +++ b/starboard/shared/starboard/player/filter/mock_audio_renderer_sink.h @@ -38,7 +38,7 @@ class MockAudioRendererSink : public AudioRendererSink { int(int sampling_frequency_hz)); MOCK_CONST_METHOD0(HasStarted, bool()); MOCK_METHOD8(Start, - void(SbTime media_start_time, + void(int64_t media_start_time, int channels, int sampling_frequency_hz, SbMediaAudioSampleType audio_sample_type, diff --git a/starboard/shared/starboard/player/filter/player_components.cc b/starboard/shared/starboard/player/filter/player_components.cc index 624efd6503f8..5068ee46fd59 100644 --- a/starboard/shared/starboard/player/filter/player_components.cc +++ b/starboard/shared/starboard/player/filter/player_components.cc @@ -15,6 +15,7 @@ #include "starboard/shared/starboard/player/filter/player_components.h" #include "starboard/common/scoped_ptr.h" +#include "starboard/common/time.h" #include "starboard/shared/starboard/application.h" #include "starboard/shared/starboard/command_line.h" #include "starboard/shared/starboard/player/filter/adaptive_audio_decoder_internal.h" @@ -44,9 +45,7 @@ typedef MediaTimeProviderImpl::MonotonicSystemTimeProvider MonotonicSystemTimeProvider; class MonotonicSystemTimeProviderImpl : public MonotonicSystemTimeProvider { - SbTimeMonotonic GetMonotonicNow() const override { - return SbTimeGetMonotonicNow(); - } + int64_t GetMonotonicNow() const override { return CurrentMonotonicTime(); } }; class PlayerComponentsImpl : public PlayerComponents { @@ -252,7 +251,7 @@ void PlayerComponents::Factory::CreateStubVideoComponents( scoped_ptr* video_decoder, scoped_ptr* video_render_algorithm, scoped_refptr* video_renderer_sink) { - const SbTime kVideoSinkRenderInterval = 10 * kSbTimeMillisecond; + const int64_t kVideoSinkRenderIntervalUsec = 10'000; // 10ms SB_DCHECK(video_decoder); SB_DCHECK(video_render_algorithm); @@ -261,7 +260,7 @@ void PlayerComponents::Factory::CreateStubVideoComponents( video_decoder->reset(new StubVideoDecoder); video_render_algorithm->reset(new VideoRenderAlgorithmImpl); *video_renderer_sink = new PunchoutVideoRendererSink( - creation_parameters.player(), kVideoSinkRenderInterval); + creation_parameters.player(), kVideoSinkRenderIntervalUsec); } void PlayerComponents::Factory::GetAudioRendererParams( diff --git a/starboard/shared/starboard/player/filter/punchout_video_renderer_sink.cc b/starboard/shared/starboard/player/filter/punchout_video_renderer_sink.cc index 2d2b3b987666..85415fb65d60 100644 --- a/starboard/shared/starboard/player/filter/punchout_video_renderer_sink.cc +++ b/starboard/shared/starboard/player/filter/punchout_video_renderer_sink.cc @@ -28,7 +28,7 @@ using std::placeholders::_1; using std::placeholders::_2; PunchoutVideoRendererSink::PunchoutVideoRendererSink(SbPlayer player, - SbTime render_interval) + int64_t render_interval) : player_(player), render_interval_(render_interval), thread_(kSbThreadInvalid), diff --git a/starboard/shared/starboard/player/filter/punchout_video_renderer_sink.h b/starboard/shared/starboard/player/filter/punchout_video_renderer_sink.h index 4caf66e85432..dc6eab735785 100644 --- a/starboard/shared/starboard/player/filter/punchout_video_renderer_sink.h +++ b/starboard/shared/starboard/player/filter/punchout_video_renderer_sink.h @@ -21,7 +21,6 @@ #include "starboard/player.h" #include "starboard/shared/internal_only.h" #include "starboard/shared/starboard/player/filter/video_renderer_sink.h" -#include "starboard/time.h" #include "starboard/types.h" namespace starboard { @@ -32,7 +31,7 @@ namespace filter { class PunchoutVideoRendererSink : public VideoRendererSink { public: - PunchoutVideoRendererSink(SbPlayer player, SbTime render_interval); + PunchoutVideoRendererSink(SbPlayer player, int64_t render_interval); ~PunchoutVideoRendererSink() override; private: @@ -46,7 +45,7 @@ class PunchoutVideoRendererSink : public VideoRendererSink { static void* ThreadEntryPoint(void* context); SbPlayer player_; - SbTime render_interval_; + int64_t render_interval_; // microseconds RenderCB render_cb_; SbThread thread_; atomic_bool stop_requested_; diff --git a/starboard/shared/starboard/player/filter/stub_audio_decoder.cc b/starboard/shared/starboard/player/filter/stub_audio_decoder.cc index 39b5017a1644..fa83c8aab5ca 100644 --- a/starboard/shared/starboard/player/filter/stub_audio_decoder.cc +++ b/starboard/shared/starboard/player/filter/stub_audio_decoder.cc @@ -46,7 +46,7 @@ int CalculateFramesPerInputBuffer(int sample_rate, SB_DCHECK(first); SB_DCHECK(second); - SbTime duration = second->timestamp() - first->timestamp(); + int64_t duration = second->timestamp() - first->timestamp(); if (duration <= 0) { SB_LOG(ERROR) << "Duration (" << duration << ") for InputBuffer@ " << first->timestamp() << " is invalid."; @@ -57,7 +57,7 @@ int CalculateFramesPerInputBuffer(int sample_rate, } scoped_refptr CreateDecodedAudio( - SbTime timestamp, + int64_t timestamp, SbMediaAudioSampleType sample_type, int number_of_channels, int frames) { @@ -216,7 +216,7 @@ void StubAudioDecoder::DecodeOneBuffer( auto offset_in_frames = offset_in_bytes / (sample_size * number_of_channels_); - SbTime timestamp = + int64_t timestamp = decoded_audio->timestamp() + AudioDurationToFrames(offset_in_frames, samples_per_second_); diff --git a/starboard/shared/starboard/player/filter/stub_video_decoder.cc b/starboard/shared/starboard/player/filter/stub_video_decoder.cc index 681b6762513c..21b07accc1ce 100644 --- a/starboard/shared/starboard/player/filter/stub_video_decoder.cc +++ b/starboard/shared/starboard/player/filter/stub_video_decoder.cc @@ -37,8 +37,8 @@ size_t StubVideoDecoder::GetPrerollFrameCount() const { return 1; } -SbTime StubVideoDecoder::GetPrerollTimeout() const { - return kSbTimeMax; +int64_t StubVideoDecoder::GetPrerollTimeout() const { + return kSbInt64Max; } size_t StubVideoDecoder::GetMaxNumberOfCachedFrames() const { @@ -132,7 +132,7 @@ void StubVideoDecoder::DecodeEndOfStream() { } scoped_refptr StubVideoDecoder::CreateOutputFrame( - SbTime timestamp) const { + int64_t timestamp) const { int bits_per_channel = video_stream_info_.color_metadata.bits_per_channel; if (bits_per_channel == 0) { // Assume 8 bits when |bits_per_channel| is unknown (0). diff --git a/starboard/shared/starboard/player/filter/stub_video_decoder.h b/starboard/shared/starboard/player/filter/stub_video_decoder.h index 2defe61bf31f..513a49ec6942 100644 --- a/starboard/shared/starboard/player/filter/stub_video_decoder.h +++ b/starboard/shared/starboard/player/filter/stub_video_decoder.h @@ -37,7 +37,7 @@ class StubVideoDecoder : public VideoDecoder, private JobQueue::JobOwner { const ErrorCB& error_cb) override; size_t GetPrerollFrameCount() const override; - SbTime GetPrerollTimeout() const override; + int64_t GetPrerollTimeout() const override; size_t GetMaxNumberOfCachedFrames() const override; void WriteInputBuffers(const InputBuffers& input_buffers) override; @@ -50,14 +50,14 @@ class StubVideoDecoder : public VideoDecoder, private JobQueue::JobOwner { void DecodeBuffers(const InputBuffers& input_buffers); void DecodeEndOfStream(); - scoped_refptr CreateOutputFrame(SbTime timestamp) const; + scoped_refptr CreateOutputFrame(int64_t timestamp) const; DecoderStatusCB decoder_status_cb_; media::VideoStreamInfo video_stream_info_; scoped_ptr decoder_thread_; // std::set<> keeps frame timestamps sorted in ascending order. - std::set output_frame_timestamps_; + std::set output_frame_timestamps_; // Used to determine when to send kBufferFull in DecodeOneBuffer(). int total_input_count_ = 0; }; diff --git a/starboard/shared/starboard/player/filter/testing/adaptive_audio_decoder_test.cc b/starboard/shared/starboard/player/filter/testing/adaptive_audio_decoder_test.cc index 5d6f6e0e6cfd..c5d5cd842d43 100644 --- a/starboard/shared/starboard/player/filter/testing/adaptive_audio_decoder_test.cc +++ b/starboard/shared/starboard/player/filter/testing/adaptive_audio_decoder_test.cc @@ -23,6 +23,7 @@ #include "starboard/common/mutex.h" #include "starboard/common/scoped_ptr.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/shared/starboard/media/media_support_internal.h" #include "starboard/shared/starboard/player/filter/audio_decoder_internal.h" @@ -51,7 +52,7 @@ using ::testing::Combine; using ::testing::ValuesIn; using video_dmp::VideoDmpReader; -const SbTimeMonotonic kWaitForNextEventTimeOut = 5 * kSbTimeSecond; +const int64_t kWaitForNextEventTimeOut = 5'000'000; // 5 seconds scoped_refptr GetAudioInputBuffer(VideoDmpReader* dmp_reader, size_t index) { @@ -142,8 +143,8 @@ class AdaptiveAudioDecoderTest } void WaitAndProcessNextEvent(Event* event) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); - while (SbTimeGetMonotonicNow() - start < kWaitForNextEventTimeOut) { + int64_t start = CurrentMonotonicTime(); + while (CurrentMonotonicTime() - start < kWaitForNextEventTimeOut) { job_queue_.RunUntilIdle(); { ScopedLock scoped_lock(event_queue_mutex_); @@ -154,7 +155,7 @@ class AdaptiveAudioDecoderTest return; } } - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); } *event = kError; FAIL(); @@ -307,7 +308,7 @@ std::string GetAdaptiveAudioDecoderTestConfigName( } TEST_P(AdaptiveAudioDecoderTest, SingleInput) { - SbTime playing_duration = 0; + int64_t playing_duration = 0; // Skip buffer 0, as the difference between first and second opus buffer // timestamp is a little larger than it should be. size_t buffer_index = 1; @@ -317,13 +318,13 @@ TEST_P(AdaptiveAudioDecoderTest, SingleInput) { ASSERT_NO_FATAL_FAILURE( WriteMultipleInputs(dmp_reader.get(), buffer_index, kBuffersToWrite)); auto input_buffer = GetAudioInputBuffer(dmp_reader.get(), buffer_index); - SbTime input_timestamp = input_buffer->timestamp(); + int64_t input_timestamp = input_buffer->timestamp(); buffer_index += kBuffersToWrite; // Use next buffer here, need to make sure dmp file has enough buffers. SB_DCHECK(dmp_reader->number_of_audio_buffers() > buffer_index); auto next_input_buffer = GetAudioInputBuffer(dmp_reader.get(), buffer_index); - SbTime next_timestamp = next_input_buffer->timestamp(); + int64_t next_timestamp = next_input_buffer->timestamp(); playing_duration += next_timestamp - input_timestamp; } ASSERT_NO_FATAL_FAILURE(WriteEndOfStream()); @@ -331,8 +332,8 @@ TEST_P(AdaptiveAudioDecoderTest, SingleInput) { ASSERT_EQ(true, first_output_received_); ASSERT_NE(0, output_sample_rate_); - int expected_output_frames = playing_duration * output_sample_rate_ / - static_cast(kSbTimeSecond); + int expected_output_frames = + playing_duration * output_sample_rate_ / static_cast(1'000'000); // The |num_of_output_frames_| may not accurately match // |expected_output_frames|. Each time to switch decoder, it may have one // sample difference in output due to integer conversion. The total difference @@ -341,7 +342,7 @@ TEST_P(AdaptiveAudioDecoderTest, SingleInput) { } TEST_P(AdaptiveAudioDecoderTest, MultipleInput) { - SbTime playing_duration = 0; + int64_t playing_duration = 0; // Skip buffer 0, as the difference between first and second opus buffer // timestamp is a little larger than it should be. size_t buffer_index = 1; @@ -351,13 +352,13 @@ TEST_P(AdaptiveAudioDecoderTest, MultipleInput) { ASSERT_NO_FATAL_FAILURE( WriteMultipleInputs(dmp_reader.get(), buffer_index, kBuffersToWrite)); auto input_buffer = GetAudioInputBuffer(dmp_reader.get(), buffer_index); - SbTime input_timestamp = input_buffer->timestamp(); + int64_t input_timestamp = input_buffer->timestamp(); buffer_index += kBuffersToWrite; // Use next buffer here, need to make sure dmp file has enough buffers. SB_DCHECK(dmp_reader->number_of_audio_buffers() > buffer_index); auto next_input_buffer = GetAudioInputBuffer(dmp_reader.get(), buffer_index); - SbTime next_timestamp = next_input_buffer->timestamp(); + int64_t next_timestamp = next_input_buffer->timestamp(); playing_duration += next_timestamp - input_timestamp; } ASSERT_NO_FATAL_FAILURE(WriteEndOfStream()); @@ -365,8 +366,8 @@ TEST_P(AdaptiveAudioDecoderTest, MultipleInput) { ASSERT_EQ(true, first_output_received_); ASSERT_NE(0, output_sample_rate_); - int expected_output_frames = playing_duration * output_sample_rate_ / - static_cast(kSbTimeSecond); + int expected_output_frames = + playing_duration * output_sample_rate_ / static_cast(1'000'000); // The |num_of_output_frames_| may not accurately match // |expected_output_frames|. Each time to switch decoder, it may have one // sample difference in output due to integer conversion. The total difference diff --git a/starboard/shared/starboard/player/filter/testing/audio_decoder_test.cc b/starboard/shared/starboard/player/filter/testing/audio_decoder_test.cc index 4b233210444a..1702aa73d1e6 100644 --- a/starboard/shared/starboard/player/filter/testing/audio_decoder_test.cc +++ b/starboard/shared/starboard/player/filter/testing/audio_decoder_test.cc @@ -27,6 +27,7 @@ #include "starboard/common/mutex.h" #include "starboard/common/ref_counted.h" #include "starboard/common/scoped_ptr.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/media.h" #include "starboard/memory.h" @@ -56,7 +57,7 @@ using ::testing::Combine; using ::testing::ValuesIn; using video_dmp::VideoDmpReader; -const SbTimeMonotonic kWaitForNextEventTimeOut = 5 * kSbTimeSecond; +const int64_t kWaitForNextEventTimeOut = 5'000'000; // 5 seconds scoped_refptr ConsolidateDecodedAudios( const std::vector>& decoded_audios) { @@ -149,8 +150,8 @@ class AudioDecoderTest } void WaitForNextEvent(Event* event) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); - while (SbTimeGetMonotonicNow() - start < kWaitForNextEventTimeOut) { + int64_t start = CurrentMonotonicTime(); + while (CurrentMonotonicTime() - start < kWaitForNextEventTimeOut) { job_queue_.RunUntilIdle(); { ScopedLock scoped_lock(event_queue_mutex_); @@ -165,7 +166,7 @@ class AudioDecoderTest return; } } - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); } *event = kError; } @@ -189,8 +190,8 @@ class AudioDecoderTest } void WriteSingleInput(size_t index, - SbTime discarded_duration_from_front, - SbTime discarded_duration_from_back) { + int64_t discarded_duration_from_front, + int64_t discarded_duration_from_back) { SB_DCHECK(IsPartialAudioSupported()); ASSERT_TRUE(can_accept_more_input_); @@ -276,15 +277,15 @@ class AudioDecoderTest } // The start_index will be updated to the new position. - void WriteTimeLimitedInputs(int* start_index, SbTime time_limit) { + void WriteTimeLimitedInputs(int* start_index, int64_t time_limit) { SB_DCHECK(start_index); SB_DCHECK(*start_index >= 0); SB_DCHECK(*start_index < dmp_reader_.number_of_audio_buffers()); ASSERT_NO_FATAL_FAILURE( WriteSingleInput(static_cast(*start_index))); SB_DCHECK(last_input_buffer_); - SbTime last_timestamp = last_input_buffer_->timestamp(); - SbTime first_timestamp = last_timestamp; + int64_t last_timestamp = last_input_buffer_->timestamp(); + int64_t first_timestamp = last_timestamp; ++(*start_index); while (last_timestamp - first_timestamp < time_limit && @@ -374,8 +375,8 @@ class AudioDecoderTest scoped_refptr GetAudioInputBuffer( size_t index, - SbTime discarded_duration_from_front, - SbTime discarded_duration_from_back) { + int64_t discarded_duration_from_front, + int64_t discarded_duration_from_back) { SB_DCHECK(IsPartialAudioSupported()); auto input_buffer = testing::GetAudioInputBuffer( @@ -649,7 +650,7 @@ TEST_P(AudioDecoderTest, MultipleInputs) { } TEST_P(AudioDecoderTest, LimitedInput) { - SbTime duration = kSbTimeSecond / 2; + int64_t duration = 500'000; // 0.5 seconds #if SB_API_VERSION < 15 SbMediaSetAudioWriteDuration(duration); #endif // SB_API_VERSION < 15 @@ -668,12 +669,12 @@ TEST_P(AudioDecoderTest, LimitedInput) { TEST_P(AudioDecoderTest, ContinuedLimitedInput) { constexpr int kMaxAccessUnitsToDecode = 256; - SbTime duration = kSbTimeSecond / 2; + int64_t duration = 500'000; // 0.5 seconds #if SB_API_VERSION < 15 SbMediaSetAudioWriteDuration(duration); #endif // SB_API_VERSION < 15 - SbTime start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); int start_index = 0; Event event; while (true) { @@ -701,7 +702,7 @@ TEST_P(AudioDecoderTest, ContinuedLimitedInput) { } WriteEndOfStream(); ASSERT_NO_FATAL_FAILURE(DrainOutputs()); - SbTime elapsed = SbTimeGetMonotonicNow() - start; + int64_t elapsed = CurrentMonotonicTime() - start; SB_LOG(INFO) << "Decoding " << dmp_reader_.number_of_audio_buffers() << " access units of " << GetMediaAudioCodecName(dmp_reader_.audio_codec()) << " takes " @@ -761,7 +762,7 @@ TEST_P(AudioDecoderTest, PartialAudio) { ASSERT_GT(decoded_audio_sample_rate_, 0); auto frames_per_access_unit = reference_decoded_audio->frames() / number_of_input_to_write; - SbTime duration_to_discard = + int64_t duration_to_discard = media::AudioFramesToDuration(frames_per_access_unit, decoded_audio_sample_rate_) / 4; @@ -769,8 +770,8 @@ TEST_P(AudioDecoderTest, PartialAudio) { ResetDecoder(); for (int i = 0; i < number_of_input_to_write; ++i) { - SbTime duration_to_discard_from_front = i == 0 ? duration_to_discard : 0; - SbTime duration_to_discard_from_back = + int64_t duration_to_discard_from_front = i == 0 ? duration_to_discard : 0; + int64_t duration_to_discard_from_back = i == number_of_input_to_write - 1 ? duration_to_discard : 0; ASSERT_NO_FATAL_FAILURE(WriteSingleInput( i, duration_to_discard_from_front, duration_to_discard_from_back)); diff --git a/starboard/shared/starboard/player/filter/testing/audio_frame_discarder_test.cc b/starboard/shared/starboard/player/filter/testing/audio_frame_discarder_test.cc index 9fefefc8e759..4f895617aeb1 100644 --- a/starboard/shared/starboard/player/filter/testing/audio_frame_discarder_test.cc +++ b/starboard/shared/starboard/player/filter/testing/audio_frame_discarder_test.cc @@ -22,7 +22,6 @@ #include "starboard/shared/starboard/player/filter/testing/test_util.h" #include "starboard/shared/starboard/player/input_buffer_internal.h" #include "starboard/shared/starboard/player/video_dmp_reader.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -45,7 +44,7 @@ class AudioFrameDiscarderTest : public ::testing::TestWithParam { VideoDmpReader dmp_reader_; }; -scoped_refptr MakeDecodedAudio(int channels, SbTime timestamp) { +scoped_refptr MakeDecodedAudio(int channels, int64_t timestamp) { scoped_refptr decoded_audio = new DecodedAudio( channels, kSbMediaAudioSampleTypeFloat32, kSbMediaAudioFrameStorageTypeInterleaved, timestamp, @@ -105,7 +104,7 @@ TEST_P(AudioFrameDiscarderTest, PartialAudio) { InputBuffers input_buffers; std::vector> decoded_audios; const auto& audio_stream_info = dmp_reader_.audio_stream_info(); - const SbTime duration = media::AudioFramesToDuration( + const int64_t duration = media::AudioFramesToDuration( MakeDecodedAudio(audio_stream_info.number_of_channels, 0)->frames(), audio_stream_info.samples_per_second); diff --git a/starboard/shared/starboard/player/filter/testing/audio_renderer_internal_test.cc b/starboard/shared/starboard/player/filter/testing/audio_renderer_internal_test.cc index 81ca2bfba0cd..7c6fbca5cd7c 100644 --- a/starboard/shared/starboard/player/filter/testing/audio_renderer_internal_test.cc +++ b/starboard/shared/starboard/player/filter/testing/audio_renderer_internal_test.cc @@ -19,6 +19,7 @@ #include "starboard/common/log.h" #include "starboard/common/scoped_ptr.h" +#include "starboard/common/time.h" #include "starboard/media.h" #include "starboard/memory.h" #include "starboard/shared/starboard/media/media_util.h" @@ -128,14 +129,14 @@ class AudioRendererTest : public ::testing::Test { // until the renderer reaches its preroll threshold. // Once the renderer is "full", an EndOfStream is written. // Returns the number of frames written. - int FillRendererWithDecodedAudioAndWriteEOS(SbTime start_timestamp) { + int FillRendererWithDecodedAudioAndWriteEOS(int64_t start_timestamp) { const int kFramesPerBuffer = 1024; int frames_written = 0; while (!prerolled_) { - SbTime timestamp = start_timestamp + frames_written * kSbTimeSecond / - kDefaultSamplesPerSecond; + int64_t timestamp = start_timestamp + frames_written * 1'000'000LL / + kDefaultSamplesPerSecond; scoped_refptr input_buffer = CreateInputBuffer(timestamp); WriteSample(input_buffer); CallConsumedCB(); @@ -170,7 +171,7 @@ class AudioRendererTest : public ::testing::Test { audio_renderer_->WriteEndOfStream(); job_queue_.RunUntilIdle(); } - void Seek(SbTime seek_to_time) { + void Seek(int64_t seek_to_time) { EXPECT_TRUE(prerolled_); prerolled_ = false; audio_renderer_->Seek(seek_to_time); @@ -195,7 +196,7 @@ class AudioRendererTest : public ::testing::Test { job_queue_.RunUntilIdle(); } - scoped_refptr CreateInputBuffer(SbTime timestamp) { + scoped_refptr CreateInputBuffer(int64_t timestamp) { const int kInputBufferSize = 4; SbPlayerSampleInfo sample_info = {}; sample_info.buffer = malloc(kInputBufferSize); @@ -207,7 +208,8 @@ class AudioRendererTest : public ::testing::Test { return new InputBuffer(DeallocateSampleCB, NULL, this, sample_info); } - scoped_refptr CreateDecodedAudio(SbTime timestamp, int frames) { + scoped_refptr CreateDecodedAudio(int64_t timestamp, + int frames) { scoped_refptr decoded_audio = new DecodedAudio( kDefaultNumberOfChannels, sample_type_, storage_type_, timestamp, frames * kDefaultNumberOfChannels * @@ -336,7 +338,7 @@ TEST_F(AudioRendererTest, SunnyDay) { SendDecoderOutput(new DecodedAudio); - SbTime media_time = audio_renderer_->GetCurrentMediaTime( + int64_t media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_TRUE(is_playing); EXPECT_FALSE(is_eos_played); @@ -355,11 +357,11 @@ TEST_F(AudioRendererTest, SunnyDay) { // Consume frames in two batches, so we can test if |GetCurrentMediaTime()| // is incrementing in an expected manner. const int frames_to_consume = std::min(frames_written, frames_in_buffer) / 2; - SbTime new_media_time; + int64_t new_media_time; EXPECT_FALSE(audio_renderer_->IsEndOfStreamPlayed()); - renderer_callback_->ConsumeFrames(frames_to_consume, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(frames_to_consume, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_TRUE(is_playing); @@ -369,7 +371,7 @@ TEST_F(AudioRendererTest, SunnyDay) { media_time = new_media_time; const int remaining_frames = frames_in_buffer - frames_to_consume; - renderer_callback_->ConsumeFrames(remaining_frames, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(remaining_frames, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_TRUE(is_playing); @@ -427,7 +429,7 @@ TEST_F(AudioRendererTest, SunnyDayWithDoublePlaybackRateAndInt16Samples) { SendDecoderOutput(new DecodedAudio); - SbTime media_time = audio_renderer_->GetCurrentMediaTime( + int64_t media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); int frames_in_buffer; @@ -445,18 +447,18 @@ TEST_F(AudioRendererTest, SunnyDayWithDoublePlaybackRateAndInt16Samples) { // is incrementing in an expected manner. const int frames_to_consume = std::min(frames_written / kPlaybackRate, frames_in_buffer) / 2; - SbTime new_media_time; + int64_t new_media_time; EXPECT_FALSE(audio_renderer_->IsEndOfStreamPlayed()); - renderer_callback_->ConsumeFrames(frames_to_consume, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(frames_to_consume, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_GT(new_media_time, media_time); media_time = new_media_time; const int remaining_frames = frames_in_buffer - frames_to_consume; - renderer_callback_->ConsumeFrames(remaining_frames, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(remaining_frames, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_GT(new_media_time, media_time); @@ -492,7 +494,7 @@ TEST_F(AudioRendererTest, StartPlayBeforePreroll) { bool is_eos_played = true; bool is_underflow = true; double playback_rate = -1.0; - SbTime media_time = audio_renderer_->GetCurrentMediaTime( + int64_t media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); int frames_in_buffer; @@ -508,11 +510,11 @@ TEST_F(AudioRendererTest, StartPlayBeforePreroll) { // Consume frames in two batches, so we can test if |GetCurrentMediaTime()| // is incrementing in an expected manner. const int frames_to_consume = std::min(frames_written, frames_in_buffer) / 2; - SbTime new_media_time; + int64_t new_media_time; EXPECT_FALSE(audio_renderer_->IsEndOfStreamPlayed()); - renderer_callback_->ConsumeFrames(frames_to_consume, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(frames_to_consume, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_TRUE(is_playing); @@ -522,7 +524,7 @@ TEST_F(AudioRendererTest, StartPlayBeforePreroll) { media_time = new_media_time; const int remaining_frames = frames_in_buffer - frames_to_consume; - renderer_callback_->ConsumeFrames(remaining_frames, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(remaining_frames, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_TRUE(is_playing); @@ -649,13 +651,12 @@ TEST_F(AudioRendererTest, MoreNumberOfOutputBuffersThanInputBuffers) { int frames_written = 0; while (!prerolled_) { - SbTime timestamp = - frames_written * kSbTimeSecond / kDefaultSamplesPerSecond; + int64_t timestamp = frames_written * 1'000'000LL / kDefaultSamplesPerSecond; WriteSample(CreateInputBuffer(timestamp)); CallConsumedCB(); SendDecoderOutput(CreateDecodedAudio(timestamp, kFramesPerBuffer / 2)); frames_written += kFramesPerBuffer / 2; - timestamp = frames_written * kSbTimeSecond / kDefaultSamplesPerSecond; + timestamp = frames_written * 1'000'000LL / kDefaultSamplesPerSecond; SendDecoderOutput(CreateDecodedAudio(timestamp, kFramesPerBuffer / 2)); frames_written += kFramesPerBuffer / 2; } @@ -678,7 +679,7 @@ TEST_F(AudioRendererTest, MoreNumberOfOutputBuffersThanInputBuffers) { SendDecoderOutput(new DecodedAudio); - SbTime media_time = audio_renderer_->GetCurrentMediaTime( + int64_t media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); int frames_in_buffer; @@ -695,11 +696,11 @@ TEST_F(AudioRendererTest, MoreNumberOfOutputBuffersThanInputBuffers) { // Consume frames in two batches, so we can test if |GetCurrentMediaTime()| // is incrementing in an expected manner. const int frames_to_consume = std::min(frames_written, frames_in_buffer) / 2; - SbTime new_media_time; + int64_t new_media_time; EXPECT_FALSE(audio_renderer_->IsEndOfStreamPlayed()); - renderer_callback_->ConsumeFrames(frames_to_consume, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(frames_to_consume, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_TRUE(is_playing); @@ -709,7 +710,7 @@ TEST_F(AudioRendererTest, MoreNumberOfOutputBuffersThanInputBuffers) { media_time = new_media_time; const int remaining_frames = frames_in_buffer - frames_to_consume; - renderer_callback_->ConsumeFrames(remaining_frames, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(remaining_frames, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_TRUE(is_playing); @@ -747,13 +748,12 @@ TEST_F(AudioRendererTest, LessNumberOfOutputBuffersThanInputBuffers) { int frames_written = 0; while (!prerolled_) { - SbTime timestamp = - frames_written * kSbTimeSecond / kDefaultSamplesPerSecond; - SbTime output_time = timestamp; + int64_t timestamp = frames_written * 1'000'000LL / kDefaultSamplesPerSecond; + int64_t output_time = timestamp; WriteSample(CreateInputBuffer(timestamp)); CallConsumedCB(); frames_written += kFramesPerBuffer / 2; - timestamp = frames_written * kSbTimeSecond / kDefaultSamplesPerSecond; + timestamp = frames_written * 1'000'000LL / kDefaultSamplesPerSecond; WriteSample(CreateInputBuffer(timestamp)); CallConsumedCB(); frames_written += kFramesPerBuffer / 2; @@ -775,7 +775,7 @@ TEST_F(AudioRendererTest, LessNumberOfOutputBuffersThanInputBuffers) { SendDecoderOutput(new DecodedAudio); - SbTime media_time = audio_renderer_->GetCurrentMediaTime( + int64_t media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); int frames_in_buffer; @@ -791,18 +791,18 @@ TEST_F(AudioRendererTest, LessNumberOfOutputBuffersThanInputBuffers) { // Consume frames in two batches, so we can test if |GetCurrentMediaTime()| // is incrementing in an expected manner. const int frames_to_consume = std::min(frames_written, frames_in_buffer) / 2; - SbTime new_media_time; + int64_t new_media_time; EXPECT_FALSE(audio_renderer_->IsEndOfStreamPlayed()); - renderer_callback_->ConsumeFrames(frames_to_consume, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(frames_to_consume, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_GE(new_media_time, media_time); media_time = new_media_time; const int remaining_frames = frames_in_buffer - frames_to_consume; - renderer_callback_->ConsumeFrames(remaining_frames, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(remaining_frames, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_GE(new_media_time, media_time); @@ -816,7 +816,7 @@ TEST_F(AudioRendererTest, Seek) { return; } - const double kSeekTime = 0.5 * kSbTimeSecond; + const double kSeekTime = 0.5 * 1'000'000LL; { ::testing::InSequence seq; @@ -850,7 +850,7 @@ TEST_F(AudioRendererTest, Seek) { SendDecoderOutput(new DecodedAudio); - SbTime media_time = audio_renderer_->GetCurrentMediaTime( + int64_t media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); int frames_in_buffer; @@ -866,11 +866,11 @@ TEST_F(AudioRendererTest, Seek) { // Consume frames in multiple batches, so we can test if // |GetCurrentMediaTime()| is incrementing in an expected manner. const int frames_to_consume = std::min(frames_written, frames_in_buffer) / 10; - SbTime new_media_time; + int64_t new_media_time; EXPECT_FALSE(audio_renderer_->IsEndOfStreamPlayed()); - renderer_callback_->ConsumeFrames(frames_to_consume, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(frames_to_consume, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_GE(new_media_time, media_time); @@ -892,7 +892,7 @@ TEST_F(AudioRendererTest, Seek) { EXPECT_GE(offset_in_frames, 0); EXPECT_TRUE(is_playing); EXPECT_TRUE(is_eos_reached); - renderer_callback_->ConsumeFrames(frames_in_buffer, SbTimeGetMonotonicNow()); + renderer_callback_->ConsumeFrames(frames_in_buffer, CurrentMonotonicTime()); new_media_time = audio_renderer_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); EXPECT_GE(new_media_time, kSeekTime); diff --git a/starboard/shared/starboard/player/filter/testing/audio_resampler_test.cc b/starboard/shared/starboard/player/filter/testing/audio_resampler_test.cc index ad88fa6a14bd..ec992f456355 100644 --- a/starboard/shared/starboard/player/filter/testing/audio_resampler_test.cc +++ b/starboard/shared/starboard/player/filter/testing/audio_resampler_test.cc @@ -100,7 +100,7 @@ class AudioResamplerTest int audio_size = kSamplesPerInput * channels_ * sample_size; scoped_refptr input = new DecodedAudio( channels_, source_sample_type_, source_storage_type_, - kSbTimeSecond * total_frames / source_sample_rate_, audio_size); + 1'000'000LL * total_frames / source_sample_rate_, audio_size); total_frames += kSamplesPerInput; inputs_.push_back(input); } diff --git a/starboard/shared/starboard/player/filter/testing/media_time_provider_impl_test.cc b/starboard/shared/starboard/player/filter/testing/media_time_provider_impl_test.cc index d2aec8c102b9..e10f00c4221e 100644 --- a/starboard/shared/starboard/player/filter/testing/media_time_provider_impl_test.cc +++ b/starboard/shared/starboard/player/filter/testing/media_time_provider_impl_test.cc @@ -14,9 +14,9 @@ #include "starboard/shared/starboard/player/filter/media_time_provider_impl.h" +#include "starboard/common/time.h" #include "starboard/shared/starboard/player/job_queue.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -28,6 +28,8 @@ namespace filter { namespace testing { namespace { +const int64_t kOneSecondInMicroseconds = 1'000'000; + typedef MediaTimeProviderImpl::MonotonicSystemTimeProvider MonotonicSystemTimeProvider; @@ -35,10 +37,10 @@ using ::testing::AssertionResult; using ::testing::Return; using ::testing::StrictMock; -::testing::AssertionResult AlmostEqual(SbTime left, SbTime right) { +::testing::AssertionResult AlmostEqual(int64_t left, int64_t right) { // Use 1 millisecond as epsilon. - const SbTime kEpsilon = kSbTimeSecond / 1000; - SbTime diff = left > right ? left - right : right - left; + const int64_t kEpsilon = 1000; // 1ms + int64_t diff = left > right ? left - right : right - left; if (diff <= kEpsilon) return ::testing::AssertionSuccess(); @@ -53,25 +55,25 @@ class MockMonotonicSystemTimeProvider : public MonotonicSystemTimeProvider { MockMonotonicSystemTimeProvider() : current_time_(kDefaultSystemTime) { ResetExpectation(); } - void SetCurrentTime(SbTimeMonotonic time) { + void SetCurrentTime(int64_t time) { current_time_ = time; ResetExpectation(); } - void AdvanceTime(SbTimeMonotonic time) { + void AdvanceTime(int64_t time) { current_time_ += time; ResetExpectation(); } - MOCK_CONST_METHOD0(GetMonotonicNow, SbTimeMonotonic()); + MOCK_CONST_METHOD0(GetMonotonicNow, CurrentMonotonicTime()); private: // return a non-zero time by default. - const SbTimeMonotonic kDefaultSystemTime = kSbTimeSecond; + const int64_t kDefaultSystemTime = kOneSecondInMicroseconds; void ResetExpectation() { EXPECT_CALL(*this, GetMonotonicNow()).WillRepeatedly(Return(current_time_)); } - SbTimeMonotonic current_time_; + int64_t current_time_; // microseconds }; // TODO: Write tests to cover callbacks. @@ -107,7 +109,7 @@ TEST_F(MediaTimeProviderImplTest, DefaultStates) { } TEST_F(MediaTimeProviderImplTest, GetCurrentMediaTimeWhileNotPlaying) { - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); bool is_playing = true, is_eos_played = true, is_underflow = true; double playback_rate = -1.0; @@ -135,12 +137,12 @@ TEST_F(MediaTimeProviderImplTest, GetCurrentMediaTimeWhilePlaying) { EXPECT_FALSE(is_underflow); EXPECT_EQ(playback_rate, 1.0); - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); EXPECT_TRUE(AlmostEqual( media_time_provider_impl_.GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate), - kSbTimeSecond)); + kOneSecondInMicroseconds)); EXPECT_TRUE(is_playing); EXPECT_FALSE(is_eos_played); EXPECT_FALSE(is_underflow); @@ -150,36 +152,36 @@ TEST_F(MediaTimeProviderImplTest, GetCurrentMediaTimeWhilePlaying) { TEST_F(MediaTimeProviderImplTest, SetPlaybackRateWhilePlaying) { media_time_provider_impl_.Play(); - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); bool is_playing = true, is_eos_played = true, is_underflow = true; double playback_rate = -1.0; EXPECT_TRUE(AlmostEqual( media_time_provider_impl_.GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate), - kSbTimeSecond)); + kOneSecondInMicroseconds)); EXPECT_EQ(playback_rate, 1.0); EXPECT_EQ(playback_rate, 1.0); media_time_provider_impl_.SetPlaybackRate(2.0); - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); EXPECT_TRUE(AlmostEqual( media_time_provider_impl_.GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate), - kSbTimeSecond * 3)); + kOneSecondInMicroseconds * 3)); EXPECT_EQ(playback_rate, 2.0); media_time_provider_impl_.SetPlaybackRate(0.0); - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); EXPECT_TRUE(AlmostEqual( media_time_provider_impl_.GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate), - kSbTimeSecond * 3)); + kOneSecondInMicroseconds * 3)); EXPECT_EQ(playback_rate, 0.0); } TEST_F(MediaTimeProviderImplTest, SeekWhileNotPlaying) { - const SbTime kSeekToTime = 100 * kSbTimeSecond; + const int64_t kSeekToTime = 100 * kOneSecondInMicroseconds; media_time_provider_impl_.Seek(kSeekToTime); bool is_playing = true, is_eos_played = true, is_underflow = true; @@ -193,7 +195,7 @@ TEST_F(MediaTimeProviderImplTest, SeekWhileNotPlaying) { EXPECT_FALSE(is_underflow); EXPECT_EQ(playback_rate, 1.0); - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); EXPECT_TRUE(AlmostEqual( media_time_provider_impl_.GetCurrentMediaTime( @@ -202,7 +204,7 @@ TEST_F(MediaTimeProviderImplTest, SeekWhileNotPlaying) { } TEST_F(MediaTimeProviderImplTest, SeekForwardWhilePlaying) { - const SbTime kSeekToTime = 100 * kSbTimeSecond; + const int64_t kSeekToTime = 100 * kOneSecondInMicroseconds; media_time_provider_impl_.Play(); @@ -218,12 +220,12 @@ TEST_F(MediaTimeProviderImplTest, SeekForwardWhilePlaying) { EXPECT_FALSE(is_underflow); EXPECT_EQ(playback_rate, 1.0); - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); EXPECT_TRUE(AlmostEqual( media_time_provider_impl_.GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate), - kSeekToTime + kSbTimeSecond)); + kSeekToTime + kOneSecondInMicroseconds)); EXPECT_TRUE(is_playing); EXPECT_FALSE(is_eos_played); EXPECT_FALSE(is_underflow); @@ -233,7 +235,7 @@ TEST_F(MediaTimeProviderImplTest, SeekForwardWhilePlaying) { TEST_F(MediaTimeProviderImplTest, SeekBackwardWhilePlaying) { media_time_provider_impl_.Play(); - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); bool is_playing = true, is_eos_played = true, is_underflow = true; double playback_rate = -1.0; @@ -241,7 +243,7 @@ TEST_F(MediaTimeProviderImplTest, SeekBackwardWhilePlaying) { media_time_provider_impl_.GetCurrentMediaTime(&is_playing, &is_eos_played, &is_underflow, &playback_rate); - const SbTime kSeekToTime = 0; + const int64_t kSeekToTime = 0; media_time_provider_impl_.Seek(kSeekToTime); EXPECT_TRUE(AlmostEqual( media_time_provider_impl_.GetCurrentMediaTime( @@ -252,7 +254,7 @@ TEST_F(MediaTimeProviderImplTest, SeekBackwardWhilePlaying) { TEST_F(MediaTimeProviderImplTest, Pause) { media_time_provider_impl_.Play(); - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); bool is_playing = true, is_eos_played = true, is_underflow = true; double playback_rate = -1.0; @@ -261,14 +263,14 @@ TEST_F(MediaTimeProviderImplTest, Pause) { &is_underflow, &playback_rate); media_time_provider_impl_.Pause(); - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); EXPECT_TRUE(AlmostEqual( media_time_provider_impl_.GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate), - kSbTimeSecond)); + kOneSecondInMicroseconds)); media_time_provider_impl_.Seek(0); - system_time_provider_->AdvanceTime(kSbTimeSecond); + system_time_provider_->AdvanceTime(kOneSecondInMicroseconds); EXPECT_TRUE(AlmostEqual( media_time_provider_impl_.GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate), diff --git a/starboard/shared/starboard/player/filter/testing/player_components_test.cc b/starboard/shared/starboard/player/filter/testing/player_components_test.cc index 0e3b3ad0306c..5ad0d5cc6bb7 100644 --- a/starboard/shared/starboard/player/filter/testing/player_components_test.cc +++ b/starboard/shared/starboard/player/filter/testing/player_components_test.cc @@ -21,6 +21,7 @@ #include "starboard/common/scoped_ptr.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/media.h" #include "starboard/player.h" #include "starboard/shared/starboard/player/filter/testing/test_util.h" @@ -52,9 +53,9 @@ typedef PlayerComponents::Factory::CreationParameters CreationParameters; typedef std::tuple PlayerComponentsTestParam; -const SbTimeMonotonic kDefaultPrerollTimeOut = 5 * kSbTimeSecond; -const SbTimeMonotonic kDefaultEndTimeOut = 5 * kSbTimeSecond; -const SbTimeMonotonic kDefaultWriteTimeOut = 5 * kSbTimeSecond; +const int64_t kDefaultPrerollTimeOut = 5'000'000; // 5 seconds +const int64_t kDefaultEndTimeOut = 5'000'000; // 5 seconds +const int64_t kDefaultWriteTimeOut = 5'000'000; // 5 seconds const SbPlayer kDummyPlayer = reinterpret_cast(1); @@ -156,7 +157,7 @@ class PlayerComponentsTest return true; } - void Seek(SbTime seek_to_time) { + void Seek(int64_t seek_to_time) { has_error_ = false; audio_prerolled_ = false; video_prerolled_ = false; @@ -205,7 +206,7 @@ class PlayerComponentsTest GetMediaTimeProvider()->SetPlaybackRate(playback_rate_); } - SbTime GetMediaTime() { + int64_t GetMediaTime() { bool is_playing, is_eos_played, is_underflow; double playback_rate; return GetMediaTimeProvider()->GetCurrentMediaTime( @@ -220,7 +221,7 @@ class PlayerComponentsTest return is_playing; } - SbTime GetCurrentAudioBufferTimestamp() const { + int64_t GetCurrentAudioBufferTimestamp() const { if (!GetAudioRenderer()) { return 0; } @@ -231,7 +232,7 @@ class PlayerComponentsTest .timestamp; } - SbTime GetCurrentVideoBufferTimestamp() const { + int64_t GetCurrentVideoBufferTimestamp() const { if (!GetVideoRenderer()) { return 0; } @@ -244,7 +245,7 @@ class PlayerComponentsTest } // The buffers are ordered by decoding order. We need to find the // presentation timestamp of next frame. - SbTime next_timestamps[2] = { + int64_t next_timestamps[2] = { video_reader_->GetPlayerSampleInfo(kSbMediaTypeVideo, video_index_) .timestamp, video_reader_->GetPlayerSampleInfo(kSbMediaTypeVideo, video_index_ + 1) @@ -252,16 +253,16 @@ class PlayerComponentsTest return std::min(next_timestamps[0], next_timestamps[1]); } - SbTime GetMaxWrittenBufferTimestamp() const { + int64_t GetMaxWrittenBufferTimestamp() const { return std::max(GetCurrentVideoBufferTimestamp(), GetCurrentAudioBufferTimestamp()); } - void WriteDataUntilPrerolled(SbTime timeout = kDefaultPrerollTimeOut) { - SbTimeMonotonic start_time = SbTimeGetMonotonicNow(); - SbTime max_timestamp = GetMediaTime() + kMaxWriteAheadDuration; + void WriteDataUntilPrerolled(int64_t timeout = kDefaultPrerollTimeOut) { + int64_t start_time = CurrentMonotonicTime(); + int64_t max_timestamp = GetMediaTime() + kMaxWriteAheadDuration; while (!IsPlaybackPrerolled()) { - ASSERT_LE(SbTimeGetMonotonicNow() - start_time, timeout) + ASSERT_LE(CurrentMonotonicTime() - start_time, timeout) << "WriteDataUntilPrerolled() timed out, buffered audio (" << GetCurrentAudioBufferTimestamp() << "), buffered video (" << GetCurrentVideoBufferTimestamp() << "), max timestamp (" @@ -269,7 +270,7 @@ class PlayerComponentsTest bool written = TryToWriteOneInputBuffer(max_timestamp); if (!written) { ASSERT_NO_FATAL_FAILURE(RenderAndProcessPendingJobs()); - SbThreadSleep(5 * kSbTimeMillisecond); + SbThreadSleep(5000); } } } @@ -277,15 +278,16 @@ class PlayerComponentsTest // The function will exit after all buffers before |eos_timestamp| are written // into the player. Note that, to avoid audio or video underflow, the function // allow to write buffers of timestamp greater than |timestamp|. - void WriteDataUntil(SbTime timestamp, SbTime timeout = kDefaultWriteTimeOut) { + void WriteDataUntil(int64_t timestamp, + int64_t timeout = kDefaultWriteTimeOut) { SB_CHECK(playback_rate_ != 0); - SbTimeMonotonic last_input_filled_time = SbTimeGetMonotonicNow(); + int64_t last_input_filled_time = CurrentMonotonicTime(); while ( (GetAudioRenderer() && GetCurrentAudioBufferTimestamp() < timestamp) || (GetVideoRenderer() && GetCurrentVideoBufferTimestamp() < timestamp)) { if (last_input_filled_time != -1) { - ASSERT_LE(SbTimeGetMonotonicNow() - last_input_filled_time, timeout) + ASSERT_LE(CurrentMonotonicTime() - last_input_filled_time, timeout) << "WriteDataUntil() timed out, buffered audio (" << GetCurrentAudioBufferTimestamp() << "), buffered video (" << GetCurrentVideoBufferTimestamp() << "), timestamp (" << timestamp @@ -294,23 +296,23 @@ class PlayerComponentsTest bool written = TryToWriteOneInputBuffer(timestamp + kMaxWriteAheadDuration); if (written) { - last_input_filled_time = SbTimeGetMonotonicNow(); + last_input_filled_time = CurrentMonotonicTime(); } else { ASSERT_NO_FATAL_FAILURE(RenderAndProcessPendingJobs()); - SbThreadSleep(5 * kSbTimeMillisecond); + SbThreadSleep(5000); } } } // The function will write EOS immediately after all buffers before // |eos_timestamp| are written into the player. - void WriteDataAndEOS(SbTime eos_timestamp, - SbTime timeout = kDefaultWriteTimeOut) { + void WriteDataAndEOS(int64_t eos_timestamp, + int64_t timeout = kDefaultWriteTimeOut) { SB_CHECK(playback_rate_ != 0); bool audio_eos_written = !GetAudioRenderer(); bool video_eos_written = !GetVideoRenderer(); - SbTimeMonotonic last_input_filled_time = SbTimeGetMonotonicNow(); + int64_t last_input_filled_time = CurrentMonotonicTime(); while (!audio_eos_written || !video_eos_written) { if (!audio_eos_written && GetCurrentAudioBufferTimestamp() >= eos_timestamp) { @@ -323,7 +325,7 @@ class PlayerComponentsTest video_eos_written = true; } if (last_input_filled_time != -1) { - ASSERT_LE(SbTimeGetMonotonicNow() - last_input_filled_time, timeout) + ASSERT_LE(CurrentMonotonicTime() - last_input_filled_time, timeout) << "WriteDataAndEOS() timed out, buffered audio (" << GetCurrentAudioBufferTimestamp() << "), buffered video (" << GetCurrentVideoBufferTimestamp() << "), eos_timestamp (" @@ -331,10 +333,10 @@ class PlayerComponentsTest } bool written = TryToWriteOneInputBuffer(eos_timestamp); if (written) { - last_input_filled_time = SbTimeGetMonotonicNow(); + last_input_filled_time = CurrentMonotonicTime(); } else { ASSERT_NO_FATAL_FAILURE(RenderAndProcessPendingJobs()); - SbThreadSleep(5 * kSbTimeMillisecond); + SbThreadSleep(5000); } } } @@ -351,27 +353,27 @@ class PlayerComponentsTest void WaitUntilPlaybackEnded() { SB_CHECK(playback_rate_ != 0); - SbTime duration = std::max(GetCurrentAudioBufferTimestamp(), - GetCurrentVideoBufferTimestamp()); - SbTime current_time = GetMediaTime(); - SbTime expected_end_time = - SbTimeGetMonotonicNow() + - static_cast((duration - current_time) / playback_rate_) + + int64_t duration = std::max(GetCurrentAudioBufferTimestamp(), + GetCurrentVideoBufferTimestamp()); + int64_t current_time = GetMediaTime(); + int64_t expected_end_time = + CurrentMonotonicTime() + + static_cast((duration - current_time) / playback_rate_) + kDefaultEndTimeOut; while (!IsPlaybackEnded()) { // If this fails, timeout must have been reached. - ASSERT_LE(SbTimeGetMonotonicNow(), expected_end_time) + ASSERT_LE(CurrentMonotonicTime(), expected_end_time) << "WaitUntilPlaybackEnded() timed out, buffered audio (" << GetCurrentAudioBufferTimestamp() << "), buffered video (" << GetCurrentVideoBufferTimestamp() << "), current media time is " << GetMediaTime() << "."; ASSERT_NO_FATAL_FAILURE(RenderAndProcessPendingJobs()); - SbThreadSleep(5 * kSbTimeMillisecond); + SbThreadSleep(5000); } current_time = GetMediaTime(); // TODO: investigate and reduce the tolerance. - ASSERT_LE(std::abs(current_time - duration), 500 * kSbTimeMillisecond) + ASSERT_LE(std::abs(current_time - duration), 500'000) << "Media time difference is too large, buffered audio(" << GetCurrentAudioBufferTimestamp() << "), buffered video (" << GetCurrentVideoBufferTimestamp() << "), current media time is " @@ -398,7 +400,7 @@ class PlayerComponentsTest // We won't write audio data more than 1s ahead of current media time in // cobalt. So, to test with the same condition, we limit max inputs ahead to // 1.5s in the tests. - const SbTime kMaxWriteAheadDuration = kSbTimeMillisecond * 1500; + const int64_t kMaxWriteAheadDuration = 1'500'000; void OnError(SbPlayerError error, const std::string& error_message) { has_error_ = true; @@ -448,7 +450,7 @@ class PlayerComponentsTest } } - bool TryToWriteOneInputBuffer(SbTime max_timestamp) { + bool TryToWriteOneInputBuffer(int64_t max_timestamp) { bool input_buffer_written = false; if (GetAudioRenderer() && GetAudioRenderer()->CanAcceptMoreData() && audio_index_ < audio_reader_->number_of_audio_buffers() && @@ -513,23 +515,22 @@ TEST_P(PlayerComponentsTest, SunnyDay) { ASSERT_EQ(GetMediaTime(), 0); ASSERT_FALSE(IsPlaying()); - SbTimeMonotonic play_requested_at = SbTimeGetMonotonicNow(); + int64_t play_requested_at = CurrentMonotonicTime(); Play(); - SbTime eos_timestamp = - std::max(kSbTimeSecond, GetMaxWrittenBufferTimestamp()); + int64_t eos_timestamp = std::max(1'000'000LL, GetMaxWrittenBufferTimestamp()); ASSERT_NO_FATAL_FAILURE(WriteDataAndEOS(eos_timestamp)); ASSERT_NO_FATAL_FAILURE(WaitUntilPlaybackEnded()); // TODO: investigate and reduce the tolerance. // ASSERT_LE( - // std::abs(SbTimeGetMonotonicNow() - (play_requested_at + - // media_duration)), 300 * kSbTimeMillisecond); + // std::abs(CurrentMonotonicTime() - (play_requested_at + + // media_duration)), 300'000); } TEST_P(PlayerComponentsTest, ShortPlayback) { Seek(0); - ASSERT_NO_FATAL_FAILURE(WriteDataAndEOS(50 * kSbTimeMillisecond)); + ASSERT_NO_FATAL_FAILURE(WriteDataAndEOS(50'000)); Play(); ASSERT_NO_FATAL_FAILURE(WaitUntilPlaybackEnded()); } @@ -540,27 +541,27 @@ TEST_P(PlayerComponentsTest, EOSWithoutInput) { Play(); ASSERT_NO_FATAL_FAILURE(WaitUntilPlaybackEnded()); // TODO: investigate and reduce the tolerance. - // ASSERT_LE(std::abs(GetMediaTime()), 100 * kSbTimeMillisecond); + // ASSERT_LE(std::abs(GetMediaTime()), 100'000); } TEST_P(PlayerComponentsTest, Pause) { Seek(0); ASSERT_NO_FATAL_FAILURE(WriteDataUntilPrerolled()); Play(); - ASSERT_NO_FATAL_FAILURE(WriteDataUntil(kSbTimeSecond)); + ASSERT_NO_FATAL_FAILURE(WriteDataUntil(1'000'000)); Pause(); ASSERT_FALSE(IsPlaying()); - SbTimeMonotonic start_time = SbTimeGetMonotonicNow(); - while (SbTimeGetMonotonicNow() < start_time + 200 * kSbTimeMillisecond) { + int64_t start_time = CurrentMonotonicTime(); + while (CurrentMonotonicTime() < start_time + 200'000) { ASSERT_NO_FATAL_FAILURE(RenderAndProcessPendingJobs()); - SbThreadSleep(5 * kSbTimeMillisecond); + SbThreadSleep(5000); } - SbTime media_time = GetMediaTime(); - start_time = SbTimeGetMonotonicNow(); - while (SbTimeGetMonotonicNow() < start_time + 200 * kSbTimeMillisecond) { + int64_t media_time = GetMediaTime(); + start_time = CurrentMonotonicTime(); + while (CurrentMonotonicTime() < start_time + 200'000) { ASSERT_NO_FATAL_FAILURE(RenderAndProcessPendingJobs()); - SbThreadSleep(5 * kSbTimeMillisecond); + SbThreadSleep(5000); } ASSERT_EQ(media_time, GetMediaTime()); @@ -579,13 +580,14 @@ TEST_P(PlayerComponentsTest, Pause) { // ASSERT_EQ(GetMediaTime(), 0); // ASSERT_FALSE(IsPlaying()); -// SbTime media_duration_to_write = std::max(GetCurrentVideoBufferTimestamp(), -// GetCurrentAudioBufferTimestamp()); -// media_duration_to_write = std::max(kSbTimeSecond, media_duration_to_write); -// SbTime media_duration_to_play = -// static_cast(media_duration_to_write / kPlaybackRate); +// int64_t media_duration_to_write = +// std::max(GetCurrentVideoBufferTimestamp(), +// GetCurrentAudioBufferTimestamp()); +// media_duration_to_write = std::max(1'000'000LL, media_duration_to_write); +// int64_t media_duration_to_play = +// static_cast(media_duration_to_write / kPlaybackRate); -// SbTimeMonotonic play_requested_at = SbTimeGetMonotonicNow(); +// int64_t play_requested_at = CurrentMonotonicTime(); // Play(); // ASSERT_NO_FATAL_FAILURE(WriteDataAndEOS(media_duration_to_write)); @@ -593,9 +595,8 @@ TEST_P(PlayerComponentsTest, Pause) { // TODO: Enable the below check after we improve the accuracy of varied // playback rate time reporting. -// ASSERT_GE(SbTimeGetMonotonicNow(), -// play_requested_at + media_duration_to_play - 200 * -// kSbTimeMillisecond); +// ASSERT_GE(CurrentMonotonicTime(), +// play_requested_at + media_duration_to_play - 200'000); // } // TEST_P(PlayerComponentsTest, PlaybackRateDouble) { @@ -607,69 +608,69 @@ TEST_P(PlayerComponentsTest, Pause) { // ASSERT_EQ(GetMediaTime(), 0); // ASSERT_FALSE(IsPlaying()); -// SbTime media_duration_to_write = std::max(GetCurrentVideoBufferTimestamp(), -// GetCurrentAudioBufferTimestamp()); +// int64_t media_duration_to_write = +// std::max(GetCurrentVideoBufferTimestamp(), +// GetCurrentAudioBufferTimestamp()); // media_duration_to_write = -// std::max(kSbTimeSecond * 2, media_duration_to_write); -// SbTime media_duration_to_play = -// static_cast(media_duration_to_write / kPlaybackRate); +// std::max(2'000'000LL, media_duration_to_write); +// int64_t media_duration_to_play = +// static_cast(media_duration_to_write / kPlaybackRate); -// SbTimeMonotonic play_requested_at = SbTimeGetMonotonicNow(); +// int64_t play_requested_at = CurrentMonotonicTime(); // Play(); // ASSERT_NO_FATAL_FAILURE(WriteDataAndEOS(media_duration_to_write)); // ASSERT_NO_FATAL_FAILURE(WaitUntilPlaybackEnded()); // playback rate time reporting. -// ASSERT_LE(SbTimeGetMonotonicNow(), -// play_requested_at + media_duration_to_play + 200 * -// kSbTimeMillisecond); +// ASSERT_LE(CurrentMonotonicTime(), +// play_requested_at + media_duration_to_play + 200'000); // } TEST_P(PlayerComponentsTest, SeekForward) { - SbTime seek_to_time = 0; + int64_t seek_to_time = 0; Seek(seek_to_time); ASSERT_NO_FATAL_FAILURE(WriteDataUntilPrerolled()); ASSERT_EQ(GetMediaTime(), seek_to_time); ASSERT_FALSE(IsPlaying()); Play(); - ASSERT_NO_FATAL_FAILURE(WriteDataUntil(kSbTimeSecond)); + ASSERT_NO_FATAL_FAILURE(WriteDataUntil(1'000'000)); Pause(); - seek_to_time = 2 * kSbTimeSecond; + seek_to_time = 2'000'000LL; Seek(seek_to_time); ASSERT_NO_FATAL_FAILURE(WriteDataUntilPrerolled()); ASSERT_EQ(GetMediaTime(), seek_to_time); ASSERT_FALSE(IsPlaying()); Play(); - SbTime eos_timestamp = - std::max(GetMaxWrittenBufferTimestamp(), seek_to_time + kSbTimeSecond); + int64_t eos_timestamp = + std::max(GetMaxWrittenBufferTimestamp(), seek_to_time + 1'000'000LL); ASSERT_NO_FATAL_FAILURE(WriteDataAndEOS(eos_timestamp)); ASSERT_NO_FATAL_FAILURE(WaitUntilPlaybackEnded()); } TEST_P(PlayerComponentsTest, SeekBackward) { - SbTime seek_to_time = 3 * kSbTimeSecond; + int64_t seek_to_time = 3'000'000LL; Seek(seek_to_time); ASSERT_NO_FATAL_FAILURE(WriteDataUntilPrerolled()); ASSERT_EQ(GetMediaTime(), seek_to_time); ASSERT_FALSE(IsPlaying()); Play(); - ASSERT_NO_FATAL_FAILURE(WriteDataAndEOS(seek_to_time + kSbTimeSecond)); + ASSERT_NO_FATAL_FAILURE(WriteDataAndEOS(seek_to_time + 1'000'000LL)); Pause(); - seek_to_time = 1 * kSbTimeSecond; + seek_to_time = 1'000'000LL; Seek(seek_to_time); ASSERT_NO_FATAL_FAILURE(WriteDataUntilPrerolled()); ASSERT_EQ(GetMediaTime(), seek_to_time); ASSERT_FALSE(IsPlaying()); Play(); - SbTime eos_timestamp = - std::max(GetMaxWrittenBufferTimestamp(), seek_to_time + kSbTimeSecond); + int64_t eos_timestamp = + std::max(GetMaxWrittenBufferTimestamp(), seek_to_time + 1'000'000LL); ASSERT_NO_FATAL_FAILURE(WriteDataAndEOS(eos_timestamp)); ASSERT_NO_FATAL_FAILURE(WaitUntilPlaybackEnded()); } @@ -691,7 +692,7 @@ vector GetSupportedCreationParameters() { // Filter too short dmp files, as the tests need at least 4s of data. for (auto iter = audio_files.begin(); iter != audio_files.end();) { VideoDmpReader audio_dmp_reader(*iter, VideoDmpReader::kEnableReadOnDemand); - if (audio_dmp_reader.audio_duration() < 5 * kSbTimeSecond) { + if (audio_dmp_reader.audio_duration() < 5'000'000LL) { iter = audio_files.erase(iter); } else { iter++; @@ -700,7 +701,7 @@ vector GetSupportedCreationParameters() { for (auto iter = video_params.begin(); iter != video_params.end();) { VideoDmpReader video_dmp_reader(std::get<0>(*iter), VideoDmpReader::kEnableReadOnDemand); - if (video_dmp_reader.video_duration() < 5 * kSbTimeSecond) { + if (video_dmp_reader.video_duration() < 5'000'000LL) { iter = video_params.erase(iter); } else { iter++; diff --git a/starboard/shared/starboard/player/filter/testing/test_util.cc b/starboard/shared/starboard/player/filter/testing/test_util.cc index 39ae17dff578..831d7c163af0 100644 --- a/starboard/shared/starboard/player/filter/testing/test_util.cc +++ b/starboard/shared/starboard/player/filter/testing/test_util.cc @@ -200,7 +200,7 @@ std::vector GetSupportedVideoTests() { test_params.push_back(std::make_tuple(filename, output_mode)); break; } else if (need_to_check_with_wait && !decoder_has_been_checked_once) { - SbThreadSleep(kSbTimeSecond); + SbThreadSleep(1'000'000); } else { break; } @@ -246,9 +246,9 @@ bool CreateAudioComponents(bool using_stub_decoder, return false; } -AssertionResult AlmostEqualTime(SbTime time1, SbTime time2) { - const SbTime kEpsilon = kSbTimeSecond / 1000; - SbTime diff = time1 - time2; +AssertionResult AlmostEqualTime(int64_t time1, int64_t time2) { + const int64_t kEpsilon = 1000; // 1ms + int64_t diff = time1 - time2; if (-kEpsilon <= diff && diff <= kEpsilon) { return AssertionSuccess(); } @@ -296,8 +296,8 @@ scoped_refptr GetAudioInputBuffer( scoped_refptr GetAudioInputBuffer( video_dmp::VideoDmpReader* dmp_reader, size_t index, - SbTime discarded_duration_from_front, - SbTime discarded_duration_from_back) { + int64_t discarded_duration_from_front, + int64_t discarded_duration_from_back) { SB_DCHECK(dmp_reader); auto player_sample_info = dmp_reader->GetPlayerSampleInfo(kSbMediaTypeAudio, index); diff --git a/starboard/shared/starboard/player/filter/testing/test_util.h b/starboard/shared/starboard/player/filter/testing/test_util.h index fcc2817fc6ce..73fd92f4f339 100644 --- a/starboard/shared/starboard/player/filter/testing/test_util.h +++ b/starboard/shared/starboard/player/filter/testing/test_util.h @@ -27,7 +27,6 @@ #include "starboard/shared/starboard/player/filter/audio_renderer_sink.h" #include "starboard/shared/starboard/player/input_buffer_internal.h" #include "starboard/shared/starboard/player/video_dmp_reader.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -62,7 +61,7 @@ bool CreateAudioComponents(bool using_stub_decoder, scoped_ptr* audio_decoder, scoped_ptr* audio_renderer_sink); -::testing::AssertionResult AlmostEqualTime(SbTime time1, SbTime time2); +::testing::AssertionResult AlmostEqualTime(int64_t time1, int64_t time2); media::VideoStreamInfo CreateVideoStreamInfo(SbMediaVideoCodec codec); @@ -75,8 +74,8 @@ scoped_refptr GetAudioInputBuffer( scoped_refptr GetAudioInputBuffer( video_dmp::VideoDmpReader* dmp_reader, size_t index, - SbTime discarded_duration_from_front, - SbTime discarded_duration_from_back); + int64_t discarded_duration_from_front, + int64_t discarded_duration_from_back); } // namespace testing } // namespace filter diff --git a/starboard/shared/starboard/player/filter/testing/video_decoder_test.cc b/starboard/shared/starboard/player/filter/testing/video_decoder_test.cc index 02013b6646c8..0790ff4f2daa 100644 --- a/starboard/shared/starboard/player/filter/testing/video_decoder_test.cc +++ b/starboard/shared/starboard/player/filter/testing/video_decoder_test.cc @@ -24,6 +24,7 @@ #include "starboard/common/mutex.h" #include "starboard/common/scoped_ptr.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/drm.h" #include "starboard/media.h" @@ -37,7 +38,6 @@ #include "starboard/shared/starboard/player/video_dmp_reader.h" #include "starboard/testing/fake_graphics_context_provider.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -402,8 +402,8 @@ TEST_P(VideoDecoderTest, MultipleInputs) { } TEST_P(VideoDecoderTest, Preroll) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); - SbTime preroll_timeout = fixture_.video_decoder()->GetPrerollTimeout(); + int64_t start = CurrentMonotonicTime(); + int64_t preroll_timeout = fixture_.video_decoder()->GetPrerollTimeout(); bool error_occurred = false; ASSERT_NO_FATAL_FAILURE(fixture_.WriteMultipleInputs( 0, fixture_.dmp_reader().number_of_video_buffers(), @@ -418,7 +418,7 @@ TEST_P(VideoDecoderTest, Preroll) { *continue_process = false; return; } - if (SbTimeGetMonotonicNow() - start >= preroll_timeout) { + if (CurrentMonotonicTime() - start >= preroll_timeout) { // After preroll timeout, we should get at least 1 decoded frame. ASSERT_GT(fixture_.GetDecodedFramesCount(), 0); *continue_process = false; diff --git a/starboard/shared/starboard/player/filter/testing/video_decoder_test_fixture.cc b/starboard/shared/starboard/player/filter/testing/video_decoder_test_fixture.cc index 0d73ff0d6b95..46281328d273 100644 --- a/starboard/shared/starboard/player/filter/testing/video_decoder_test_fixture.cc +++ b/starboard/shared/starboard/player/filter/testing/video_decoder_test_fixture.cc @@ -27,6 +27,7 @@ #include "starboard/common/mutex.h" #include "starboard/common/scoped_ptr.h" #include "starboard/common/string.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/drm.h" #include "starboard/media.h" @@ -39,7 +40,6 @@ #include "starboard/shared/starboard/player/video_dmp_reader.h" #include "starboard/testing/fake_graphics_context_provider.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -157,11 +157,10 @@ void VideoDecoderTestFixture::AssertInvalidDecodeTarget() { } #endif // SB_HAS(GLES2) -void VideoDecoderTestFixture::WaitForNextEvent(Event* event, - SbTimeMonotonic timeout) { +void VideoDecoderTestFixture::WaitForNextEvent(Event* event, int64_t timeout) { ASSERT_TRUE(event); - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); do { job_queue_->RunUntilIdle(); GetDecodeTargetWhenSupported(); @@ -180,15 +179,14 @@ void VideoDecoderTestFixture::WaitForNextEvent(Event* event, return; } } - SbThreadSleep(kSbTimeMillisecond); - } while (SbTimeGetMonotonicNow() - start < timeout); + SbThreadSleep(1000); + } while (CurrentMonotonicTime() - start < timeout); event->status = kTimeout; SB_LOG(WARNING) << "WaitForNextEvent() timeout."; } bool VideoDecoderTestFixture::HasPendingEvents() { - const SbTime kDelay = 5 * kSbTimeMillisecond; - SbThreadSleep(kDelay); + SbThreadSleep(5000); ScopedLock scoped_lock(mutex_); return !event_queue_.empty(); } diff --git a/starboard/shared/starboard/player/filter/testing/video_decoder_test_fixture.h b/starboard/shared/starboard/player/filter/testing/video_decoder_test_fixture.h index 4376bf242e9b..f421b410bdc8 100644 --- a/starboard/shared/starboard/player/filter/testing/video_decoder_test_fixture.h +++ b/starboard/shared/starboard/player/filter/testing/video_decoder_test_fixture.h @@ -37,7 +37,6 @@ #include "starboard/shared/starboard/player/video_dmp_reader.h" #include "starboard/testing/fake_graphics_context_provider.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" // This has to be defined in the global namespace as its instance will be used @@ -53,8 +52,7 @@ namespace testing { class VideoDecoderTestFixture { public: - static const SbTimeMonotonic kDefaultWaitForNextEventTimeOut = - 5 * kSbTimeSecond; + static const int64_t kDefaultWaitForNextEventTimeOut = 5'000'000; // 5sec enum Status { kNeedMoreInput = VideoDecoder::kNeedMoreInput, @@ -105,9 +103,8 @@ class VideoDecoderTestFixture { void AssertInvalidDecodeTarget(); #endif // SB_HAS(GLES2) - void WaitForNextEvent( - Event* event, - SbTimeMonotonic timeout = kDefaultWaitForNextEventTimeOut); + void WaitForNextEvent(Event* event, + int64_t timeout = kDefaultWaitForNextEventTimeOut); bool HasPendingEvents(); @@ -165,7 +162,7 @@ class VideoDecoderTestFixture { scoped_ptr video_decoder_; bool need_more_input_ = true; - std::set outstanding_inputs_; + std::set outstanding_inputs_; std::deque> decoded_frames_; SbPlayerPrivate player_; diff --git a/starboard/shared/starboard/player/filter/testing/video_frame_rate_estimator_test.cc b/starboard/shared/starboard/player/filter/testing/video_frame_rate_estimator_test.cc index 9eb1a928bf8c..00de4c13d86b 100644 --- a/starboard/shared/starboard/player/filter/testing/video_frame_rate_estimator_test.cc +++ b/starboard/shared/starboard/player/filter/testing/video_frame_rate_estimator_test.cc @@ -20,7 +20,6 @@ #include "starboard/common/ref_counted.h" #include "starboard/shared/starboard/player/filter/video_frame_internal.h" #include "starboard/shared/starboard/player/filter/video_frame_rate_estimator.h" -#include "starboard/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace starboard { @@ -50,7 +49,7 @@ void SkipFrames(size_t frames_to_skip, } } -Frames CreateFrames(const std::initializer_list& timestamps) { +Frames CreateFrames(const std::initializer_list& timestamps) { Frames frames; for (auto timestamp : timestamps) { frames.push_back(new VideoFrame(timestamp)); diff --git a/starboard/shared/starboard/player/filter/tools/audio_dmp_player.cc b/starboard/shared/starboard/player/filter/tools/audio_dmp_player.cc index 2413431aa596..6869fe0f6bf3 100644 --- a/starboard/shared/starboard/player/filter/tools/audio_dmp_player.cc +++ b/starboard/shared/starboard/player/filter/tools/audio_dmp_player.cc @@ -46,7 +46,7 @@ scoped_ptr s_video_dmp_reader; scoped_ptr s_player_components; int s_audio_sample_index; scoped_ptr s_job_thread; -SbTime s_duration; +int64_t s_duration; static void DeallocateSampleFunc(SbPlayer player, void* context, @@ -60,7 +60,7 @@ starboard::scoped_refptr GetAudioInputBuffer(size_t index) { void OnTimer() { if (!s_player_components->GetAudioRenderer()->CanAcceptMoreData()) { - s_job_thread->job_queue()->Schedule(std::bind(OnTimer), kSbTimeMillisecond); + s_job_thread->job_queue()->Schedule(std::bind(OnTimer), 1000); return; } diff --git a/starboard/shared/starboard/player/filter/video_decoder_internal.h b/starboard/shared/starboard/player/filter/video_decoder_internal.h index 19edeec16c3b..63c63703729b 100644 --- a/starboard/shared/starboard/player/filter/video_decoder_internal.h +++ b/starboard/shared/starboard/player/filter/video_decoder_internal.h @@ -69,12 +69,12 @@ class VideoDecoder { // is considered to be complete. virtual size_t GetPrerollFrameCount() const = 0; - // Returns the timeout that preroll is considered to be finished. Once the - // first frame is decoded and the timeout has passed, the preroll will be - // considered as finished even if there isn't enough frames decoded as - // suggested by GetPrerollFrameCount(). - // On most platforms this can be simply set to |kSbTimeMax|. - virtual SbTime GetPrerollTimeout() const = 0; + // Returns the timeout (in microseconds) that preroll is considered to be + // finished. Once the first frame is decoded and the timeout has passed, the + // preroll will be considered as finished even if there isn't enough frames + // decoded as suggested by GetPrerollFrameCount(). + // On most platforms this can be simply set to |kSbInt64Max|. + virtual int64_t GetPrerollTimeout() const = 0; // Returns a soft limit of the maximum number of frames the user of this class // (usually the VideoRenderer) should cache, i.e. the user won't write more diff --git a/starboard/shared/starboard/player/filter/video_frame_internal.h b/starboard/shared/starboard/player/filter/video_frame_internal.h index 08084eb72669..949dcbe6639f 100644 --- a/starboard/shared/starboard/player/filter/video_frame_internal.h +++ b/starboard/shared/starboard/player/filter/video_frame_internal.h @@ -31,13 +31,13 @@ namespace filter { class VideoFrame : public RefCountedThreadSafe { public: // An invalid media timestamp to indicate end of stream. - static const SbTime kMediaTimeEndOfStream = -1; + static const int64_t kMediaTimeEndOfStream = -1; - explicit VideoFrame(SbTime timestamp) : timestamp_(timestamp) {} + explicit VideoFrame(int64_t timestamp) : timestamp_(timestamp) {} virtual ~VideoFrame() {} bool is_end_of_stream() const { return timestamp_ == kMediaTimeEndOfStream; } - SbTime timestamp() const { + int64_t timestamp() const { SB_DCHECK(!is_end_of_stream()); return timestamp_; } @@ -47,7 +47,7 @@ class VideoFrame : public RefCountedThreadSafe { } private: - SbTime timestamp_; + int64_t timestamp_; // microseconds VideoFrame(const VideoFrame&) = delete; void operator=(const VideoFrame&) = delete; diff --git a/starboard/shared/starboard/player/filter/video_frame_rate_estimator.cc b/starboard/shared/starboard/player/filter/video_frame_rate_estimator.cc index afa56ca2e430..20f3b7ff29e3 100644 --- a/starboard/shared/starboard/player/filter/video_frame_rate_estimator.cc +++ b/starboard/shared/starboard/player/filter/video_frame_rate_estimator.cc @@ -54,7 +54,7 @@ void VideoFrameRateEstimator::Reset() { void VideoFrameRateEstimator::CalculateInitialFrameRate( const Frames& frames, - SbTime previous_frame_duration) { + int64_t previous_frame_duration) { SB_DCHECK(frame_rate_ == kInvalidFrameRate); SB_DCHECK(!frames.empty()); SB_DCHECK(frames.size() >= 2 || previous_frame_duration > 0); @@ -102,7 +102,7 @@ void VideoFrameRateEstimator::CalculateInitialFrameRate( } auto average_frame_duration = accumulated_frame_durations_ / number_of_frame_durations_accumulated_; - frame_rate_ = static_cast(kSbTimeSecond) / average_frame_duration; + frame_rate_ = static_cast(1'000'000) / average_frame_duration; // Snap the frame rate to the nearest integer, so 29.97 will become 30. if (frame_rate_ - std::floor(frame_rate_) < kFrameRateEpsilon) { diff --git a/starboard/shared/starboard/player/filter/video_frame_rate_estimator.h b/starboard/shared/starboard/player/filter/video_frame_rate_estimator.h index e65408473252..10863adee1cd 100644 --- a/starboard/shared/starboard/player/filter/video_frame_rate_estimator.h +++ b/starboard/shared/starboard/player/filter/video_frame_rate_estimator.h @@ -20,7 +20,6 @@ #include "starboard/common/ref_counted.h" #include "starboard/shared/internal_only.h" #include "starboard/shared/starboard/player/filter/video_frame_internal.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -60,13 +59,13 @@ class VideoFrameRateEstimator { static constexpr double kFrameRateEpsilon = 0.1; void CalculateInitialFrameRate(const Frames& frames, - SbTime previous_frame_duration = 0); + int64_t previous_frame_duration = 0); void RefineFrameRate(const Frames& frames); double frame_rate_ = kInvalidFrameRate; - SbTime accumulated_frame_durations_; + int64_t accumulated_frame_durations_; // microseconds int number_of_frame_durations_accumulated_; - SbTime last_checked_frame_timestamp_; + int64_t last_checked_frame_timestamp_; // microseconds }; } // namespace filter diff --git a/starboard/shared/starboard/player/filter/video_render_algorithm.h b/starboard/shared/starboard/player/filter/video_render_algorithm.h index 94cac792f3da..23fb45a60486 100644 --- a/starboard/shared/starboard/player/filter/video_render_algorithm.h +++ b/starboard/shared/starboard/player/filter/video_render_algorithm.h @@ -23,7 +23,6 @@ #include "starboard/shared/starboard/player/filter/media_time_provider.h" #include "starboard/shared/starboard/player/filter/video_frame_internal.h" #include "starboard/shared/starboard/player/filter/video_renderer_sink.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -50,8 +49,8 @@ class VideoRenderAlgorithm { std::list>* frames, VideoRendererSink::DrawFrameCB draw_frame_cb) = 0; // Called during seek to reset the internal states of VideoRenderAlgorithm. - // |seek_to_time| will be set to the seek target. - virtual void Seek(SbTime seek_to_time) = 0; + // |seek_to_time| (microseconds) will be set to the seek target. + virtual void Seek(int64_t seek_to_time) = 0; virtual int GetDroppedFrames() = 0; }; diff --git a/starboard/shared/starboard/player/filter/video_render_algorithm_impl.cc b/starboard/shared/starboard/player/filter/video_render_algorithm_impl.cc index 48888104ab16..a5648724e82a 100644 --- a/starboard/shared/starboard/player/filter/video_render_algorithm_impl.cc +++ b/starboard/shared/starboard/player/filter/video_render_algorithm_impl.cc @@ -15,6 +15,7 @@ #include "starboard/shared/starboard/player/filter/video_render_algorithm_impl.h" #include "starboard/common/log.h" +#include "starboard/common/time.h" namespace starboard { namespace shared { @@ -52,7 +53,7 @@ void VideoRenderAlgorithmImpl::Render( bool is_audio_eos_played; bool is_underflow; double playback_rate; - SbTime media_time = media_time_provider->GetCurrentMediaTime( + int64_t media_time = media_time_provider->GetCurrentMediaTime( &is_audio_playing, &is_audio_eos_played, &is_underflow, &playback_rate); // Video frames are synced to the audio timestamp. However, the audio @@ -72,7 +73,7 @@ void VideoRenderAlgorithmImpl::Render( // * Then the frame with timestamp 40 is displayed twice (for sample // timestamps 31 and 40). // * Then the frame with timestamp 50 is dropped. - const SbTime kMediaTimeThreshold = kSbTimeSecond / 250; + const int64_t kMediaTimeThresholdUsec = 1'000'000LL / 250; // Favor advancing the frame sooner. This addresses the situation where the // audio timestamp query interval is a little shorter than a frame. This @@ -82,7 +83,7 @@ void VideoRenderAlgorithmImpl::Render( // to frame timestamp 30 when the sample time is 19. if (is_audio_playing && frames->size() > 1 && frames->front()->timestamp() == last_frame_timestamp_ && - last_frame_timestamp_ - kMediaTimeThreshold < media_time) { + last_frame_timestamp_ - kMediaTimeThresholdUsec < media_time) { frames->pop_front(); } @@ -96,10 +97,10 @@ void VideoRenderAlgorithmImpl::Render( // however, the "early advance" logic from above would force frame 30 to // move onto frame 40 on sample timestamp 31. while (frames->size() > 1 && !frames->front()->is_end_of_stream() && - frames->front()->timestamp() + kMediaTimeThreshold < media_time) { + frames->front()->timestamp() + kMediaTimeThresholdUsec < media_time) { if (frames->front()->timestamp() != last_frame_timestamp_) { #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK - auto now = SbTimeGetMonotonicNow(); + auto now = CurrentMonotonicTime(); SB_LOG(WARNING) << "Dropping frame @ " << frames->front()->timestamp() << " microseconds, the elasped media time/system time from" @@ -131,11 +132,11 @@ void VideoRenderAlgorithmImpl::Render( #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK media_time_of_last_render_call_ = media_time; - system_time_of_last_render_call_ = SbTimeGetMonotonicNow(); + system_time_of_last_render_call_ = CurrentMonotonicTime(); #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK } -void VideoRenderAlgorithmImpl::Seek(SbTime seek_to_time) { +void VideoRenderAlgorithmImpl::Seek(int64_t seek_to_time) { if (get_refresh_rate_fn_) { last_frame_timestamp_ = -1; current_frame_rendered_times_ = -1; @@ -167,7 +168,7 @@ void VideoRenderAlgorithmImpl::RenderWithCadence( bool is_audio_eos_played; bool is_underflow; double playback_rate; - SbTime media_time = media_time_provider->GetCurrentMediaTime( + int64_t media_time = media_time_provider->GetCurrentMediaTime( &is_audio_playing, &is_audio_eos_played, &is_underflow, &playback_rate); while (frames->size() > 1 && !frames->front()->is_end_of_stream() && @@ -189,7 +190,7 @@ void VideoRenderAlgorithmImpl::RenderWithCadence( cadence_pattern_generator_.UpdateFrameRate(frame_rate * playback_rate); SB_DCHECK(cadence_pattern_generator_.has_cadence()); - auto frame_duration = static_cast(kSbTimeSecond / refresh_rate); + auto frame_duration = static_cast(1'000'000LL / refresh_rate); if (current_frame_rendered_times_ >= cadence_pattern_generator_.GetNumberOfTimesCurrentFrameDisplays()) { @@ -216,7 +217,7 @@ void VideoRenderAlgorithmImpl::RenderWithCadence( if (frames->front()->timestamp() != last_frame_timestamp_) { #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK ++times_logged_; - auto now = SbTimeGetMonotonicNow(); + auto now = CurrentMonotonicTime(); SB_LOG_IF(WARNING, times_logged_ < kMaxLogPerPlaybackSession) << "Dropping frame @ " << frames->front()->timestamp() << " microseconds, the elasped media time/system time from" @@ -229,7 +230,7 @@ void VideoRenderAlgorithmImpl::RenderWithCadence( } else { #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK ++times_logged_; - auto now = SbTimeGetMonotonicNow(); + auto now = CurrentMonotonicTime(); SB_LOG_IF(WARNING, times_logged_ < kMaxLogPerPlaybackSession) << "Frame @ " << frames->front()->timestamp() << " microseconds should be displayed " @@ -287,7 +288,7 @@ void VideoRenderAlgorithmImpl::RenderWithCadence( #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK media_time_of_last_render_call_ = media_time; - system_time_of_last_render_call_ = SbTimeGetMonotonicNow(); + system_time_of_last_render_call_ = CurrentMonotonicTime(); #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK } diff --git a/starboard/shared/starboard/player/filter/video_render_algorithm_impl.h b/starboard/shared/starboard/player/filter/video_render_algorithm_impl.h index ff8d47400252..a60579de9885 100644 --- a/starboard/shared/starboard/player/filter/video_render_algorithm_impl.h +++ b/starboard/shared/starboard/player/filter/video_render_algorithm_impl.h @@ -28,7 +28,6 @@ #include "starboard/shared/starboard/player/filter/video_frame_rate_estimator.h" #include "starboard/shared/starboard/player/filter/video_render_algorithm.h" #include "starboard/shared/starboard/player/filter/video_renderer_sink.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -46,7 +45,7 @@ class VideoRenderAlgorithmImpl : public VideoRenderAlgorithm { void Render(MediaTimeProvider* media_time_provider, std::list>* frames, VideoRendererSink::DrawFrameCB draw_frame_cb) override; - void Seek(SbTime seek_to_time) override; + void Seek(int64_t seek_to_time) override; int GetDroppedFrames() override { return dropped_frames_; } private: @@ -63,11 +62,11 @@ class VideoRenderAlgorithmImpl : public VideoRenderAlgorithm { static constexpr int kMaxLogPerPlaybackSession = 32; int times_logged_ = 0; - SbTime media_time_of_last_render_call_; - SbTime system_time_of_last_render_call_; + int64_t media_time_of_last_render_call_; // microseconds + int64_t system_time_of_last_render_call_; // microseconds #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK - SbTime last_frame_timestamp_ = -1; + int64_t last_frame_timestamp_ = -1; // microseconds int current_frame_rendered_times_ = -1; int dropped_frames_ = 0; }; diff --git a/starboard/shared/starboard/player/filter/video_renderer_internal.h b/starboard/shared/starboard/player/filter/video_renderer_internal.h index 12546ee357d2..560c84d37f32 100644 --- a/starboard/shared/starboard/player/filter/video_renderer_internal.h +++ b/starboard/shared/starboard/player/filter/video_renderer_internal.h @@ -20,7 +20,6 @@ #include "starboard/shared/internal_only.h" #include "starboard/shared/starboard/player/filter/common.h" #include "starboard/shared/starboard/player/input_buffer_internal.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -43,7 +42,8 @@ class VideoRenderer { virtual void WriteEndOfStream() = 0; - virtual void Seek(SbTime seek_to_time) = 0; + // |seek_to_time| is microseconds. + virtual void Seek(int64_t seek_to_time) = 0; virtual bool IsEndOfStreamWritten() const = 0; virtual bool CanAcceptMoreData() const = 0; diff --git a/starboard/shared/starboard/player/filter/video_renderer_internal_impl.cc b/starboard/shared/starboard/player/filter/video_renderer_internal_impl.cc index 7f42d6137881..fd31dc6f80be 100644 --- a/starboard/shared/starboard/player/filter/video_renderer_internal_impl.cc +++ b/starboard/shared/starboard/player/filter/video_renderer_internal_impl.cc @@ -17,6 +17,8 @@ #include #include +#include "starboard/common/time.h" + namespace starboard { namespace shared { namespace starboard { @@ -28,7 +30,7 @@ namespace { using std::placeholders::_1; using std::placeholders::_2; -const SbTime kSeekTimeoutRetryInterval = 25 * kSbTimeMillisecond; +const int64_t kSeekTimeoutRetryInterval = 25'000; // 25ms } // namespace @@ -54,12 +56,12 @@ VideoRendererImpl::VideoRendererImpl(scoped_ptr decoder, << " Playback performance may not be ideal."; #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK - last_buffering_state_update_ = SbTimeGetMonotonicNow(); + last_buffering_state_update_ = CurrentMonotonicTime(); last_output_ = last_buffering_state_update_; last_can_accept_more_data = last_buffering_state_update_; Schedule(std::bind(&VideoRendererImpl::CheckBufferingState, this), kCheckBufferingStateInterval); - time_of_last_lag_warning_ = SbTimeGetMonotonicNow() - kMinLagWarningInterval; + time_of_last_lag_warning_ = CurrentMonotonicTime() - kMinLagWarningInterval; #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK } @@ -110,7 +112,7 @@ void VideoRendererImpl::WriteSamples(const InputBuffers& input_buffers) { #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK buffering_state_ = kWaitForConsumption; - last_buffering_state_update_ = SbTimeGetMonotonicNow(); + last_buffering_state_update_ = CurrentMonotonicTime(); #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK if (end_of_stream_written_.load()) { @@ -123,7 +125,7 @@ void VideoRendererImpl::WriteSamples(const InputBuffers& input_buffers) { if (!first_input_written_) { first_input_written_ = true; #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK - first_input_written_at_ = SbTimeGetMonotonicNow(); + first_input_written_at_ = CurrentMonotonicTime(); #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK } @@ -148,7 +150,7 @@ void VideoRendererImpl::WriteEndOfStream() { decoder_->WriteEndOfStream(); } -void VideoRendererImpl::Seek(SbTime seek_to_time) { +void VideoRendererImpl::Seek(int64_t seek_to_time) { SB_DCHECK(BelongsToCurrentThread()); SB_DCHECK(seek_to_time >= 0); @@ -159,7 +161,7 @@ void VideoRendererImpl::Seek(SbTime seek_to_time) { // After decoder_->Reset(), OnDecoderStatus() won't be called before another // WriteSample(). So it is safe to modify |seeking_to_time_| here. - seeking_to_time_ = std::max(seek_to_time, 0); + seeking_to_time_ = std::max(seek_to_time, 0); seeking_.store(true); end_of_stream_written_.store(false); end_of_stream_decoded_.store(false); @@ -169,7 +171,7 @@ void VideoRendererImpl::Seek(SbTime seek_to_time) { CancelPendingJobs(); auto preroll_timeout = decoder_->GetPrerollTimeout(); - if (preroll_timeout != kSbTimeMax) { + if (preroll_timeout != kSbInt64Max) { Schedule(std::bind(&VideoRendererImpl::OnSeekTimeout, this), preroll_timeout); } @@ -196,7 +198,7 @@ bool VideoRendererImpl::CanAcceptMoreData() const { !end_of_stream_written_.load() && need_more_input_.load(); #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK if (can_accept_more_data) { - last_can_accept_more_data = SbTimeGetMonotonicNow(); + last_can_accept_more_data = CurrentMonotonicTime(); } #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK return can_accept_more_data; @@ -219,7 +221,7 @@ SbDecodeTarget VideoRendererImpl::GetCurrentDecodeTarget() { SB_DCHECK(decoder_); #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK - auto start = SbTimeGetMonotonicNow(); + auto start = CurrentMonotonicTime(); #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK // TODO: Ensure that |sink_| is NULL when decode target is used across all @@ -231,7 +233,7 @@ SbDecodeTarget VideoRendererImpl::GetCurrentDecodeTarget() { auto decode_target = decoder_->GetCurrentDecodeTarget(); #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK - auto end = SbTimeGetMonotonicNow(); + auto end = CurrentMonotonicTime(); if (end - start > kMaxGetCurrentDecodeTargetDuration) { SB_LOG(WARNING) << "VideoRendererImpl::GetCurrentDecodeTarget() takes " << end - start << " microseconds."; @@ -254,7 +256,7 @@ void VideoRendererImpl::OnDecoderStatus( if (frame) { #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK - last_output_ = SbTimeGetMonotonicNow(); + last_output_ = CurrentMonotonicTime(); #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK SB_DCHECK(first_input_written_); @@ -288,7 +290,7 @@ void VideoRendererImpl::OnDecoderStatus( seeking_.exchange(false)) { #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK SB_LOG(INFO) << "Video preroll takes " - << SbTimeGetMonotonicNow() - first_input_written_at_ + << CurrentMonotonicTime() - first_input_written_at_ << " microseconds."; #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK Schedule(prerolled_cb_); @@ -298,7 +300,7 @@ void VideoRendererImpl::OnDecoderStatus( #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK if (status == VideoDecoder::kNeedMoreInput) { buffering_state_ = kWaitForBuffer; - last_buffering_state_update_ = SbTimeGetMonotonicNow(); + last_buffering_state_update_ = CurrentMonotonicTime(); } #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK @@ -307,7 +309,7 @@ void VideoRendererImpl::OnDecoderStatus( void VideoRendererImpl::Render(VideoRendererSink::DrawFrameCB draw_frame_cb) { #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK - auto now = SbTimeGetMonotonicNow(); + auto now = CurrentMonotonicTime(); if (time_of_last_render_call_ != -1) { auto time_since_last_call = now - time_of_last_render_call_; if (time_since_last_call > kMaxRenderIntervalBeforeWarning) { @@ -348,7 +350,7 @@ void VideoRendererImpl::Render(VideoRendererSink::DrawFrameCB draw_frame_cb) { #if SB_PLAYER_FILTER_ENABLE_STATE_CHECK // Update this at last to ensure that the delay of Render() call isn't caused // by the slowness of Render() itself. - time_of_last_render_call_ = SbTimeGetMonotonicNow(); + time_of_last_render_call_ = CurrentMonotonicTime(); #endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK } @@ -369,7 +371,7 @@ void VideoRendererImpl::CheckBufferingState() { if (end_of_stream_decoded_.load()) { return; } - auto now = SbTimeGetMonotonicNow(); + auto now = CurrentMonotonicTime(); if (!end_of_stream_written_.load()) { auto elapsed = now - last_buffering_state_update_; if (elapsed > kDelayBeforeWarning) { @@ -397,8 +399,8 @@ void VideoRendererImpl::CheckBufferingState() { kCheckBufferingStateInterval); } -void VideoRendererImpl::CheckForFrameLag(SbTime last_decoded_frame_timestamp) { - SbTimeMonotonic now = SbTimeGetMonotonicNow(); +void VideoRendererImpl::CheckForFrameLag(int64_t last_decoded_frame_timestamp) { + int64_t now = CurrentMonotonicTime(); // Limit check frequency to minimize call to GetCurrentMediaTime(). if (now - time_of_last_lag_warning_ < kMinLagWarningInterval) { return; @@ -409,18 +411,18 @@ void VideoRendererImpl::CheckForFrameLag(SbTime last_decoded_frame_timestamp) { bool is_eos_played; bool is_underflow; double playback_rate; - SbTime media_time = media_time_provider_->GetCurrentMediaTime( + int64_t media_time = media_time_provider_->GetCurrentMediaTime( &is_playing, &is_eos_played, &is_underflow, &playback_rate); if (is_eos_played) { return; } - SbTime frame_time = last_decoded_frame_timestamp; - SbTime diff_media_frame_time = media_time - frame_time; + int64_t frame_time = last_decoded_frame_timestamp; + int64_t diff_media_frame_time = media_time - frame_time; if (diff_media_frame_time <= kDelayBeforeWarning) { return; } SB_LOG(WARNING) << "Video renderer wrote sample with frame time" - << " lagging " << diff_media_frame_time * 1.0f / kSbTimeSecond + << " lagging " << diff_media_frame_time * 1.0f / 1'000'000LL << " s behind media time"; } diff --git a/starboard/shared/starboard/player/filter/video_renderer_internal_impl.h b/starboard/shared/starboard/player/filter/video_renderer_internal_impl.h index 1daf9af3246b..c292b0c59f5f 100644 --- a/starboard/shared/starboard/player/filter/video_renderer_internal_impl.h +++ b/starboard/shared/starboard/player/filter/video_renderer_internal_impl.h @@ -33,7 +33,6 @@ #include "starboard/shared/starboard/player/filter/video_renderer_sink.h" #include "starboard/shared/starboard/player/input_buffer_internal.h" #include "starboard/shared/starboard/player/job_queue.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -64,7 +63,7 @@ class VideoRendererImpl : public VideoRenderer, private JobQueue::JobOwner { void WriteEndOfStream() override; - void Seek(SbTime seek_to_time) override; + void Seek(int64_t seek_to_time) override; bool IsEndOfStreamWritten() const override { return end_of_stream_written_.load(); @@ -104,7 +103,7 @@ class VideoRendererImpl : public VideoRenderer, private JobQueue::JobOwner { atomic_bool need_more_input_; atomic_bool seeking_; - SbTime seeking_to_time_ = 0; + int64_t seeking_to_time_ = 0; // microseconds // |number_of_frames_| = decoder_frames_.size() + sink_frames_.size() atomic_int32_t number_of_frames_; @@ -126,29 +125,27 @@ class VideoRendererImpl : public VideoRenderer, private JobQueue::JobOwner { kWaitForConsumption, }; - static const SbTimeMonotonic kCheckBufferingStateInterval = kSbTimeSecond; - static const SbTimeMonotonic kDelayBeforeWarning = 2 * kSbTimeSecond; - static const SbTimeMonotonic kMinLagWarningInterval = 10 * kSbTimeSecond; + static const int64_t kCheckBufferingStateInterval = 1'000'000; // 1 second + static const int64_t kDelayBeforeWarning = 2'000'000; // 2 seconds + static const int64_t kMinLagWarningInterval = 10'000'000; // 10 seconds - static const SbTimeMonotonic kMaxRenderIntervalBeforeWarning = - 66 * kSbTimeMillisecond; - static const SbTimeMonotonic kMaxGetCurrentDecodeTargetDuration = - 16 * kSbTimeMillisecond; + static const int64_t kMaxRenderIntervalBeforeWarning = 66'000; // 66ms + static const int64_t kMaxGetCurrentDecodeTargetDuration = 16'000; // 16ms void CheckBufferingState(); - void CheckForFrameLag(SbTime last_decoded_frame_timestamp); + void CheckForFrameLag(int64_t last_decoded_frame_timestamp); volatile BufferingState buffering_state_ = kWaitForBuffer; - volatile SbTimeMonotonic last_buffering_state_update_ = 0; - volatile SbTimeMonotonic last_output_ = 0; - mutable volatile SbTime last_can_accept_more_data = 0; + volatile int64_t last_buffering_state_update_ = 0; // microseconds + volatile int64_t last_output_ = 0; // microseconds + mutable volatile int64_t last_can_accept_more_data = 0; // microseconds - SbTimeMonotonic time_of_last_lag_warning_; + int64_t time_of_last_lag_warning_; // microseconds - SbTimeMonotonic time_of_last_render_call_ = -1; + int64_t time_of_last_render_call_ = -1; // microseconds - SbTimeMonotonic first_input_written_at_ = 0; -#endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK + int64_t first_input_written_at_ = 0; // microseconds +#endif // SB_PLAYER_FILTER_ENABLE_STATE_CHECK }; } // namespace filter diff --git a/starboard/shared/starboard/player/input_buffer_internal.h b/starboard/shared/starboard/player/input_buffer_internal.h index 0ae44e1f2aed..da1fe9003212 100644 --- a/starboard/shared/starboard/player/input_buffer_internal.h +++ b/starboard/shared/starboard/player/input_buffer_internal.h @@ -48,7 +48,7 @@ class InputBuffer : public RefCountedThreadSafe { const std::vector& side_data() const { return side_data_; } - SbTime timestamp() const { return timestamp_; } + int64_t timestamp() const { return timestamp_; } const media::AudioSampleInfo& audio_sample_info() const { SB_DCHECK(sample_type_ == kSbMediaTypeAudio); return audio_sample_info_; @@ -83,7 +83,7 @@ class InputBuffer : public RefCountedThreadSafe { const uint8_t* data_; int size_; std::vector side_data_; - SbTime timestamp_; + int64_t timestamp_; // microseconds media::AudioSampleInfo audio_sample_info_; media::VideoSampleInfo video_sample_info_; diff --git a/starboard/shared/starboard/player/job_queue.cc b/starboard/shared/starboard/player/job_queue.cc index 82c5ebe5675d..e2476053c339 100644 --- a/starboard/shared/starboard/player/job_queue.cc +++ b/starboard/shared/starboard/player/job_queue.cc @@ -75,13 +75,12 @@ JobQueue::~JobQueue() { } JobQueue::JobToken JobQueue::Schedule(const Job& job, - SbTimeMonotonic delay /*= 0*/) { - return Schedule(job, NULL, delay); + int64_t delay_usec /*= 0*/) { + return Schedule(job, NULL, delay_usec); } -JobQueue::JobToken JobQueue::Schedule(Job&& job, - SbTimeMonotonic delay /*= 0*/) { - return Schedule(std::move(job), NULL, delay); +JobQueue::JobToken JobQueue::Schedule(Job&& job, int64_t delay_usec /*= 0*/) { + return Schedule(std::move(job), NULL, delay_usec); } void JobQueue::ScheduleAndWait(const Job& job) { @@ -167,15 +166,15 @@ JobQueue* JobQueue::current() { JobQueue::JobToken JobQueue::Schedule(const Job& job, JobOwner* owner, - SbTimeMonotonic delay) { - return Schedule(Job(job), owner, delay); + int64_t delay_usec) { + return Schedule(Job(job), owner, delay_usec); } JobQueue::JobToken JobQueue::Schedule(Job&& job, JobOwner* owner, - SbTimeMonotonic delay) { + int64_t delay_usec) { SB_DCHECK(job); - SB_DCHECK(delay >= 0) << delay; + SB_DCHECK(delay_usec >= 0) << delay_usec; ScopedLock scoped_lock(mutex_); if (stopped_) { @@ -193,7 +192,7 @@ JobQueue::JobToken JobQueue::Schedule(Job&& job, } #endif // ENABLE_JOB_QUEUE_PROFILING - SbTimeMonotonic time_to_run_job = SbTimeGetMonotonicNow() + delay; + int64_t time_to_run_job = CurrentMonotonicTime() + delay_usec; bool is_first_job = time_to_job_record_map_.empty() || time_to_run_job < time_to_job_record_map_.begin()->first; @@ -230,8 +229,7 @@ bool JobQueue::TryToRunOneJob(bool wait_for_next_job) { return false; } if (time_to_job_record_map_.empty() && wait_for_next_job) { - // |kSbTimeMax| makes more sense here, but |kSbTimeDay| is much safer. - condition_.WaitTimed(kSbTimeDay); + condition_.WaitTimed(kSbInt64Max); #if ENABLE_JOB_QUEUE_PROFILING ++wait_times_; #endif // ENABLE_JOB_QUEUE_PROFILING @@ -241,10 +239,10 @@ bool JobQueue::TryToRunOneJob(bool wait_for_next_job) { } TimeToJobRecordMap::iterator first_delayed_job = time_to_job_record_map_.begin(); - SbTimeMonotonic delay = first_delayed_job->first - SbTimeGetMonotonicNow(); - if (delay > 0) { + int64_t delay_usec = first_delayed_job->first - CurrentMonotonicTime(); + if (delay_usec > 0) { if (wait_for_next_job) { - condition_.WaitTimed(delay); + condition_.WaitTimed(delay_usec); #if ENABLE_JOB_QUEUE_PROFILING ++wait_times_; #endif // ENABLE_JOB_QUEUE_PROFILING @@ -258,8 +256,8 @@ bool JobQueue::TryToRunOneJob(bool wait_for_next_job) { // Try to retrieve the job again as the job map can be altered during the // wait. first_delayed_job = time_to_job_record_map_.begin(); - delay = first_delayed_job->first - SbTimeGetMonotonicNow(); - if (delay > 0) { + delay_usec = first_delayed_job->first - CurrentMonotonicTime(); + if (delay_usec > 0) { return false; } job_record = std::move(first_delayed_job->second); @@ -269,7 +267,7 @@ bool JobQueue::TryToRunOneJob(bool wait_for_next_job) { SB_DCHECK(job_record.job); #if ENABLE_JOB_QUEUE_PROFILING - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); #endif // ENABLE_JOB_QUEUE_PROFILING job_record.job(); @@ -277,13 +275,13 @@ bool JobQueue::TryToRunOneJob(bool wait_for_next_job) { #if ENABLE_JOB_QUEUE_PROFILING ++jobs_processed_; - auto now = SbTimeGetMonotonicNow(); + auto now = CurrentMonotonicTime(); auto elapsed = now - start; if (elapsed > max_job_interval_) { job_record_with_max_interval_ = job_record; max_job_interval_ = elapsed; } - if (now - last_reset_time_ > kProfileResetInterval) { + if (now - last_reset_time_ > kProfileResetIntervalUsec) { SB_LOG(INFO) << "================ " << jobs_processed_ << " jobs processed, and waited for " << wait_times_ << " times since last reset on 0x" << this diff --git a/starboard/shared/starboard/player/job_queue.h b/starboard/shared/starboard/player/job_queue.h index f45949f70e31..fab15b95ad1c 100644 --- a/starboard/shared/starboard/player/job_queue.h +++ b/starboard/shared/starboard/player/job_queue.h @@ -22,9 +22,9 @@ #include "starboard/common/condition_variable.h" #include "starboard/common/log.h" #include "starboard/common/mutex.h" +#include "starboard/common/time.h" #include "starboard/shared/internal_only.h" #include "starboard/thread.h" -#include "starboard/time.h" #ifndef __cplusplus #error "Only C++ files can include this header." @@ -76,11 +76,11 @@ class JobQueue { return job_queue_->BelongsToCurrentThread(); } - JobToken Schedule(const Job& job, SbTimeMonotonic delay = 0) { - return job_queue_->Schedule(job, this, delay); + JobToken Schedule(const Job& job, int64_t delay_usec = 0) { + return job_queue_->Schedule(job, this, delay_usec); } - JobToken Schedule(Job&& job, SbTimeMonotonic delay = 0) { - return job_queue_->Schedule(std::move(job), this, delay); + JobToken Schedule(Job&& job, int64_t delay_usec = 0) { + return job_queue_->Schedule(std::move(job), this, delay_usec); } void RemoveJobByToken(JobToken job_token) { @@ -126,8 +126,8 @@ class JobQueue { JobQueue(); ~JobQueue(); - JobToken Schedule(const Job& job, SbTimeMonotonic delay = 0); - JobToken Schedule(Job&& job, SbTimeMonotonic delay = 0); + JobToken Schedule(const Job& job, int64_t delay_usec = 0); + JobToken Schedule(Job&& job, int64_t delay_usec = 0); void ScheduleAndWait(const Job& job); void ScheduleAndWait(Job&& job); void RemoveJobByToken(JobToken job_token); @@ -146,7 +146,7 @@ class JobQueue { private: #if ENABLE_JOB_QUEUE_PROFILING // Reset the max value periodically to catch all local peaks. - static const SbTime kProfileResetInterval = kSbTimeSecond; + static const int64_t kProfileResetIntervalUsec = 1'000'000; // 1 second static const int kProfileStackDepth = 10; #endif // ENABLE_JOB_QUEUE_PROFILING @@ -159,10 +159,10 @@ class JobQueue { int stack_size; #endif // ENABLE_JOB_QUEUE_PROFILING }; - typedef std::multimap TimeToJobRecordMap; + typedef std::multimap TimeToJobRecordMap; - JobToken Schedule(const Job& job, JobOwner* owner, SbTimeMonotonic delay); - JobToken Schedule(Job&& job, JobOwner* owner, SbTimeMonotonic delay); + JobToken Schedule(const Job& job, JobOwner* owner, int64_t delay_usec); + JobToken Schedule(Job&& job, JobOwner* owner, int64_t delay_usec); void RemoveJobsByOwner(JobOwner* owner); // Return true if a job is run, otherwise return false. When there is no job // ready to run currently and |wait_for_next_job| is true, the function will @@ -179,9 +179,9 @@ class JobQueue { bool stopped_ = false; #if ENABLE_JOB_QUEUE_PROFILING - SbTimeMonotonic last_reset_time_ = SbTimeGetMonotonicNow(); + int64_t last_reset_time_ = CurrentMonotonicTime(); JobRecord job_record_with_max_interval_; - SbTimeMonotonic max_job_interval_ = 0; + int64_t max_job_interval_ = 0; int jobs_processed_ = 0; int wait_times_ = 0; #endif // ENABLE_JOB_QUEUE_PROFILING diff --git a/starboard/shared/starboard/player/job_queue_test.cc b/starboard/shared/starboard/player/job_queue_test.cc index e0b855a84b58..520868367dbe 100644 --- a/starboard/shared/starboard/player/job_queue_test.cc +++ b/starboard/shared/starboard/player/job_queue_test.cc @@ -31,7 +31,7 @@ namespace { using ::testing::ElementsAre; // Require at least millisecond-level precision. -const SbTime kPrecision = kSbTimeMillisecond; +const int64_t kPrecisionUsec = 1000; class JobQueueTest : public ::testing::Test, @@ -50,14 +50,14 @@ TEST_F(JobQueueTest, OwnedScheduledJobsAreExecutedInOrder) { Schedule([&]() { values.push_back(1); }); Schedule([&]() { values.push_back(2); }); Schedule([&]() { values.push_back(3); }); - Schedule([&]() { values.push_back(4); }, 1 * kPrecision); - Schedule([&]() { values.push_back(5); }, 1 * kPrecision); - Schedule([&]() { values.push_back(6); }, 1 * kPrecision); - Schedule([&]() { values.push_back(7); }, 2 * kPrecision); - Schedule([&]() { values.push_back(8); }, 3 * kPrecision); + Schedule([&]() { values.push_back(4); }, 1 * kPrecisionUsec); + Schedule([&]() { values.push_back(5); }, 1 * kPrecisionUsec); + Schedule([&]() { values.push_back(6); }, 1 * kPrecisionUsec); + Schedule([&]() { values.push_back(7); }, 2 * kPrecisionUsec); + Schedule([&]() { values.push_back(8); }, 3 * kPrecisionUsec); // Sleep past the last scheduled job. - SbThreadSleep(4 * kPrecision); + SbThreadSleep(4 * kPrecisionUsec); job_queue_.RunUntilIdle(); EXPECT_THAT(values, ElementsAre(1, 2, 3, 4, 5, 6, 7, 8)); @@ -119,12 +119,12 @@ TEST_F(JobQueueTest, RemovedJobsAreRemoved) { } TEST_F(JobQueueTest, RunUntilStoppedExecutesAllRemainingJobs) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); std::atomic_bool job_1 = {false}, job_2 = {false}, job_3 = {false}; job_queue_.Schedule([&job_1]() { job_1 = true; }); - job_queue_.Schedule([&job_2]() { job_2 = true; }, 1 * kPrecision); - job_queue_.Schedule([&job_3]() { job_3 = true; }, 2 * kPrecision); - job_queue_.Schedule([&]() { job_queue_.StopSoon(); }, 3 * kPrecision); + job_queue_.Schedule([&job_2]() { job_2 = true; }, 1 * kPrecisionUsec); + job_queue_.Schedule([&job_3]() { job_3 = true; }, 2 * kPrecisionUsec); + job_queue_.Schedule([&]() { job_queue_.StopSoon(); }, 3 * kPrecisionUsec); job_queue_.RunUntilIdle(); // Job 1 should have been executed. @@ -137,7 +137,7 @@ TEST_F(JobQueueTest, RunUntilStoppedExecutesAllRemainingJobs) { EXPECT_TRUE(job_3); // Time passed should at least be as long as the delay of the last job. - EXPECT_GE(SbTimeGetMonotonicNow() - start, 3 * kPrecision); + EXPECT_GE(CurrentMonotonicTime() - start, 3 * kPrecisionUsec); } TEST_F(JobQueueTest, JobsAreMovedAndNotCopied) { diff --git a/starboard/shared/starboard/player/job_thread.h b/starboard/shared/starboard/player/job_thread.h index c6ae99c687b2..2ad61b465d71 100644 --- a/starboard/shared/starboard/player/job_thread.h +++ b/starboard/shared/starboard/player/job_thread.h @@ -50,16 +50,16 @@ class JobThread { } JobQueue::JobToken Schedule(const JobQueue::Job& job, - SbTimeMonotonic delay = 0) { + int64_t delay_usec = 0) { SB_DCHECK(job_queue_); - return job_queue_->Schedule(job, delay); + return job_queue_->Schedule(job, delay_usec); } - JobQueue::JobToken Schedule(JobQueue::Job&& job, SbTimeMonotonic delay = 0) { + JobQueue::JobToken Schedule(JobQueue::Job&& job, int64_t delay_usec = 0) { SB_DCHECK(job_queue_); - return job_queue_->Schedule(std::move(job), delay); + return job_queue_->Schedule(std::move(job), delay_usec); } void ScheduleAndWait(const JobQueue::Job& job) { diff --git a/starboard/shared/starboard/player/job_thread_test.cc b/starboard/shared/starboard/player/job_thread_test.cc index 961b070fbe6e..a6c1a9eeba7e 100644 --- a/starboard/shared/starboard/player/job_thread_test.cc +++ b/starboard/shared/starboard/player/job_thread_test.cc @@ -17,6 +17,7 @@ #include #include +#include "starboard/common/time.h" #include "starboard/shared/starboard/player/job_queue.h" #include "starboard/thread.h" #include "testing/gmock/include/gmock/gmock.h" @@ -32,7 +33,7 @@ namespace { using ::testing::ElementsAre; // Require at least millisecond-level precision. -constexpr SbTime kPrecision = kSbTimeMillisecond; +constexpr int64_t kPrecisionUsec = 1000; void ExecutePendingJobs(JobThread* job_thread) { job_thread->ScheduleAndWait([]() {}); @@ -44,14 +45,14 @@ TEST(JobThreadTest, ScheduledJobsAreExecutedInOrder) { job_thread.Schedule([&]() { values.push_back(1); }); job_thread.Schedule([&]() { values.push_back(2); }); job_thread.Schedule([&]() { values.push_back(3); }); - job_thread.Schedule([&]() { values.push_back(4); }, 1 * kPrecision); - job_thread.Schedule([&]() { values.push_back(5); }, 1 * kPrecision); - job_thread.Schedule([&]() { values.push_back(6); }, 1 * kPrecision); - job_thread.Schedule([&]() { values.push_back(7); }, 2 * kPrecision); - job_thread.Schedule([&]() { values.push_back(8); }, 3 * kPrecision); + job_thread.Schedule([&]() { values.push_back(4); }, 1 * kPrecisionUsec); + job_thread.Schedule([&]() { values.push_back(5); }, 1 * kPrecisionUsec); + job_thread.Schedule([&]() { values.push_back(6); }, 1 * kPrecisionUsec); + job_thread.Schedule([&]() { values.push_back(7); }, 2 * kPrecisionUsec); + job_thread.Schedule([&]() { values.push_back(8); }, 3 * kPrecisionUsec); // Sleep past the last scheduled job. - SbThreadSleep(4 * kPrecision); + SbThreadSleep(4 * kPrecisionUsec); ExecutePendingJobs(&job_thread); @@ -59,16 +60,16 @@ TEST(JobThreadTest, ScheduledJobsAreExecutedInOrder) { } TEST(JobThreadTest, ScheduleAndWaitWaits) { - SbTimeMonotonic start = SbTimeGetMonotonicNow(); + int64_t start = CurrentMonotonicTime(); std::atomic_bool job_1 = {false}; JobThread job_thread{"JobThreadTests"}; job_thread.ScheduleAndWait([&]() { - SbThreadSleep(1 * kPrecision); + SbThreadSleep(1 * kPrecisionUsec); job_1 = true; }); // Verify that the job ran and that it took at least as long as it slept. EXPECT_TRUE(job_1); - EXPECT_GE(SbTimeGetMonotonicNow() - start, 1 * kPrecision); + EXPECT_GE(CurrentMonotonicTime() - start, 1 * kPrecisionUsec); } TEST(JobThreadTest, ScheduledJobsShouldNotExecuteAfterGoingOutOfScope) { @@ -77,19 +78,19 @@ TEST(JobThreadTest, ScheduledJobsShouldNotExecuteAfterGoingOutOfScope) { JobThread job_thread{"JobThreadTests"}; std::function job = [&]() { counter++; - job_thread.Schedule(job, 2 * kPrecision); + job_thread.Schedule(job, 2 * kPrecisionUsec); }; job_thread.Schedule(job); // Wait for the job to run at least once and reschedule itself. - SbThreadSleep(1 * kPrecision); + SbThreadSleep(1 * kPrecisionUsec); ExecutePendingJobs(&job_thread); } int end_value = counter; EXPECT_GE(counter, 1); // Sleep past two more (potential) executions and verify there were none. - SbThreadSleep(4 * kPrecision); + SbThreadSleep(4 * kPrecisionUsec); EXPECT_EQ(counter, end_value); } @@ -120,7 +121,7 @@ TEST(JobThreadTest, CanceledJobsAreCanceled) { int checkpoint_2 = counter_2; // Sleep and wait for pending jobs to run. - SbThreadSleep(1 * kPrecision); + SbThreadSleep(1 * kPrecisionUsec); ExecutePendingJobs(&job_thread); // Job 1 should not have run again. diff --git a/starboard/shared/starboard/player/player_get_audio_configuration.cc b/starboard/shared/starboard/player/player_get_audio_configuration.cc index bdc0d63b2a22..36a3e110bd84 100644 --- a/starboard/shared/starboard/player/player_get_audio_configuration.cc +++ b/starboard/shared/starboard/player/player_get_audio_configuration.cc @@ -17,7 +17,6 @@ #include "starboard/common/log.h" #include "starboard/media.h" #include "starboard/shared/starboard/player/player_internal.h" -#include "starboard/time.h" #if SB_API_VERSION >= 15 diff --git a/starboard/shared/starboard/player/player_internal.cc b/starboard/shared/starboard/player/player_internal.cc index 7247adce31ba..4e67ee0161d6 100644 --- a/starboard/shared/starboard/player/player_internal.cc +++ b/starboard/shared/starboard/player/player_internal.cc @@ -19,7 +19,7 @@ #include "starboard/common/log.h" #include "starboard/common/media.h" -#include "starboard/time.h" +#include "starboard/common/time.h" #if SB_PLAYER_ENABLE_VIDEO_DUMPER #include SB_PLAYER_DMP_WRITER_INCLUDE_PATH @@ -32,11 +32,11 @@ using std::placeholders::_2; using std::placeholders::_3; using std::placeholders::_4; -SbTime CalculateMediaTime(SbTime media_time, - SbTimeMonotonic media_time_update_time, - double playback_rate) { - SbTimeMonotonic elapsed = SbTimeGetMonotonicNow() - media_time_update_time; - return media_time + static_cast(elapsed * playback_rate); +int64_t CalculateMediaTime(int64_t media_time, + int64_t media_time_update_time, + double playback_rate) { + int64_t elapsed = starboard::CurrentMonotonicTime() - media_time_update_time; + return media_time + static_cast(elapsed * playback_rate); } } // namespace @@ -54,7 +54,7 @@ SbPlayerPrivate::SbPlayerPrivate( starboard::scoped_ptr player_worker_handler) : sample_deallocate_func_(sample_deallocate_func), context_(context), - media_time_updated_at_(SbTimeGetMonotonicNow()) { + media_time_updated_at_(starboard::CurrentMonotonicTime()) { worker_ = starboard::make_scoped_ptr(PlayerWorker::CreateInstance( audio_codec, video_codec, player_worker_handler.Pass(), std::bind(&SbPlayerPrivate::UpdateMediaInfo, this, _1, _2, _3, _4), @@ -88,12 +88,12 @@ SbPlayerPrivate* SbPlayerPrivate::CreateInstance( return nullptr; } -void SbPlayerPrivate::Seek(SbTime seek_to_time, int ticket) { +void SbPlayerPrivate::Seek(int64_t seek_to_time, int ticket) { { starboard::ScopedLock lock(mutex_); SB_DCHECK(ticket_ != ticket); media_time_ = seek_to_time; - media_time_updated_at_ = SbTimeGetMonotonicNow(); + media_time_updated_at_ = starboard::CurrentMonotonicTime(); is_progressing_ = false; ticket_ = ticket; } @@ -156,7 +156,7 @@ void SbPlayerPrivate::SetVolume(double volume) { worker_->SetVolume(volume_); } -void SbPlayerPrivate::UpdateMediaInfo(SbTime media_time, +void SbPlayerPrivate::UpdateMediaInfo(int64_t media_time, int dropped_video_frames, int ticket, bool is_progressing) { @@ -166,7 +166,7 @@ void SbPlayerPrivate::UpdateMediaInfo(SbTime media_time, } media_time_ = media_time; is_progressing_ = is_progressing; - media_time_updated_at_ = SbTimeGetMonotonicNow(); + media_time_updated_at_ = starboard::CurrentMonotonicTime(); dropped_video_frames_ = dropped_video_frames; } @@ -183,7 +183,7 @@ bool SbPlayerPrivate::GetAudioConfiguration( starboard::ScopedLock lock(audio_configurations_mutex_); if (audio_configurations_.empty()) { #if !defined(COBALT_BUILD_TYPE_GOLD) - SbTime start = SbTimeGetMonotonicNow(); + int64_t start = starboard::CurrentMonotonicTime(); #endif // !defined(COBALT_BUILD_TYPE_GOLD) for (int i = 0; i < 32; ++i) { SbMediaAudioConfiguration audio_configuration; @@ -205,7 +205,7 @@ bool SbPlayerPrivate::GetAudioConfiguration( } } #if !defined(COBALT_BUILD_TYPE_GOLD) - SbTime elapsed = SbTimeGetMonotonicNow() - start; + int64_t elapsed = starboard::CurrentMonotonicTime() - start; SB_LOG(INFO) << "GetAudioConfiguration(): Updating audio configurations takes " << elapsed << " microseconds."; diff --git a/starboard/shared/starboard/player/player_internal.h b/starboard/shared/starboard/player/player_internal.h index d6391ff45afa..8f036b5b0b48 100644 --- a/starboard/shared/starboard/player/player_internal.h +++ b/starboard/shared/starboard/player/player_internal.h @@ -26,7 +26,6 @@ #include "starboard/shared/internal_only.h" #include "starboard/shared/starboard/media/media_util.h" #include "starboard/shared/starboard/player/player_worker.h" -#include "starboard/time.h" #include "starboard/window.h" #if SB_PLAYER_ENABLE_VIDEO_DUMPER @@ -48,7 +47,7 @@ struct SbPlayerPrivate { void* context, starboard::scoped_ptr player_worker_handler); - void Seek(SbTime seek_to_time, int ticket); + void Seek(int64_t seek_to_time, int ticket); template void WriteSamples(const PlayerSampleInfo* sample_infos, int number_of_sample_infos); @@ -89,7 +88,7 @@ struct SbPlayerPrivate { SbPlayerPrivate(const SbPlayerPrivate&) = delete; SbPlayerPrivate& operator=(const SbPlayerPrivate&) = delete; - void UpdateMediaInfo(SbTime media_time, + void UpdateMediaInfo(int64_t media_time, int dropped_video_frames, int ticket, bool is_progressing); @@ -99,8 +98,8 @@ struct SbPlayerPrivate { starboard::Mutex mutex_; int ticket_ = SB_PLAYER_INITIAL_TICKET; - SbTime media_time_ = 0; - SbTimeMonotonic media_time_updated_at_; + int64_t media_time_ = 0; // microseconds + int64_t media_time_updated_at_; // microseconds int frame_width_ = 0; int frame_height_ = 0; bool is_paused_ = false; diff --git a/starboard/shared/starboard/player/player_seek.cc b/starboard/shared/starboard/player/player_seek.cc index 9ea1a082f559..9b1281488bbc 100644 --- a/starboard/shared/starboard/player/player_seek.cc +++ b/starboard/shared/starboard/player/player_seek.cc @@ -18,9 +18,9 @@ #include "starboard/shared/starboard/player/player_internal.h" #if SB_API_VERSION >= 15 -void SbPlayerSeek(SbPlayer player, SbTime seek_to_timestamp, int ticket) { +void SbPlayerSeek(SbPlayer player, int64_t seek_to_timestamp, int ticket) { #else // SB_API_VERSION >= 15 -void SbPlayerSeek2(SbPlayer player, SbTime seek_to_timestamp, int ticket) { +void SbPlayerSeek2(SbPlayer player, int64_t seek_to_timestamp, int ticket) { #endif // SB_API_VERSION >= 15 if (!SbPlayerIsValid(player)) { SB_DLOG(WARNING) << "player is invalid."; diff --git a/starboard/shared/starboard/player/player_worker.cc b/starboard/shared/starboard/player/player_worker.cc index 09947e895f9d..bc2cdb3e549b 100644 --- a/starboard/shared/starboard/player/player_worker.cc +++ b/starboard/shared/starboard/player/player_worker.cc @@ -47,7 +47,7 @@ const int kPlayerStackSize = 0; // TODO: Reduce this as there should be enough frames caches in the renderers. // Also this should be configurable for platforms with very limited video // backlogs. -const SbTimeMonotonic kWritePendingSampleDelay = 8 * kSbTimeMillisecond; +const int64_t kWritePendingSampleDelayUsec = 8'000; // 8ms DECLARE_INSTANCE_COUNTER(PlayerWorker); @@ -138,7 +138,7 @@ PlayerWorker::PlayerWorker(SbMediaAudioCodec audio_codec, SB_DCHECK(job_queue_); } -void PlayerWorker::UpdateMediaInfo(SbTime time, +void PlayerWorker::UpdateMediaInfo(int64_t time, int dropped_video_frames, bool is_progressing) { if (player_state_ == kSbPlayerStatePresenting) { @@ -222,7 +222,7 @@ void PlayerWorker::DoInit() { } } -void PlayerWorker::DoSeek(SbTime seek_to_time, int ticket) { +void PlayerWorker::DoSeek(int64_t seek_to_time, int ticket) { SB_DCHECK(job_queue_->BelongsToCurrentThread()); SB_DCHECK(player_state_ != kSbPlayerStateDestroyed); @@ -309,7 +309,7 @@ void PlayerWorker::DoWriteSamples(InputBuffers input_buffers) { if (!write_pending_sample_job_token_.is_valid()) { write_pending_sample_job_token_ = job_queue_->Schedule( std::bind(&PlayerWorker::DoWritePendingSamples, this), - kWritePendingSampleDelay); + kWritePendingSampleDelayUsec); } } } diff --git a/starboard/shared/starboard/player/player_worker.h b/starboard/shared/starboard/player/player_worker.h index 96bae3d002cf..3e6953da5cd6 100644 --- a/starboard/shared/starboard/player/player_worker.h +++ b/starboard/shared/starboard/player/player_worker.h @@ -30,7 +30,6 @@ #include "starboard/shared/starboard/player/input_buffer_internal.h" #include "starboard/shared/starboard/player/job_queue.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "starboard/window.h" namespace starboard { @@ -46,7 +45,7 @@ namespace player { // they needn't maintain the thread and queue internally. class PlayerWorker { public: - typedef std::function @@ -75,7 +74,7 @@ class PlayerWorker { typedef ::starboard::shared::starboard::player::InputBuffers InputBuffers; typedef std::function< - void(SbTime media_time, int dropped_video_frames, bool is_progressing)> + void(int64_t media_time, int dropped_video_frames, bool is_progressing)> UpdateMediaInfoCB; typedef std::function GetPlayerStateCB; typedef std::function UpdatePlayerStateCB; @@ -94,7 +93,7 @@ class PlayerWorker { GetPlayerStateCB get_player_state_cb, UpdatePlayerStateCB update_player_state_cb, UpdatePlayerErrorCB update_player_error_cb) = 0; - virtual HandlerResult Seek(SbTime seek_to_time, int ticket) = 0; + virtual HandlerResult Seek(int64_t seek_to_time, int ticket) = 0; virtual HandlerResult WriteSamples(const InputBuffers& input_buffers, int* samples_written) = 0; virtual HandlerResult WriteEndOfStream(SbMediaType sample_type) = 0; @@ -129,7 +128,7 @@ class PlayerWorker { ~PlayerWorker(); - void Seek(SbTime seek_to_time, int ticket) { + void Seek(int64_t seek_to_time, int ticket) { job_queue_->Schedule( std::bind(&PlayerWorker::DoSeek, this, seek_to_time, ticket)); } @@ -191,7 +190,7 @@ class PlayerWorker { PlayerWorker(const PlayerWorker&) = delete; PlayerWorker& operator=(const PlayerWorker&) = delete; - void UpdateMediaInfo(SbTime time, int dropped_video_frames, bool underflow); + void UpdateMediaInfo(int64_t time, int dropped_video_frames, bool underflow); SbPlayerState player_state() const { return player_state_; } void UpdatePlayerState(SbPlayerState player_state); @@ -202,7 +201,7 @@ class PlayerWorker { static void* ThreadEntryPoint(void* context); void RunLoop(); void DoInit(); - void DoSeek(SbTime seek_to_time, int ticket); + void DoSeek(int64_t seek_to_time, int ticket); void DoWriteSamples(InputBuffers input_buffers); void DoWritePendingSamples(); void DoWriteEndOfStream(SbMediaType sample_type); diff --git a/starboard/shared/starboard/player/video_dmp_common.h b/starboard/shared/starboard/player/video_dmp_common.h index 0920269ee638..897841ad3fe3 100644 --- a/starboard/shared/starboard/player/video_dmp_common.h +++ b/starboard/shared/starboard/player/video_dmp_common.h @@ -49,7 +49,7 @@ namespace video_dmp { // // audio/video access unit: // fourcc type: 'adat'/'vdat' -// <8 bytes time stamp in SbTime> +// <8 bytes time stamp int64_t> // <1 byte of drm_sample_info_present in bool> // <4 bytes size of key_id> + |size| bytes of key id // <4 bytes size of iv> + |size| bytes of iv diff --git a/starboard/shared/starboard/player/video_dmp_reader.cc b/starboard/shared/starboard/player/video_dmp_reader.cc index 53660b87f502..5f70ea7cb9fa 100644 --- a/starboard/shared/starboard/player/video_dmp_reader.cc +++ b/starboard/shared/starboard/player/video_dmp_reader.cc @@ -36,7 +36,7 @@ int64_t CalculateAverageBitrate(const std::vector& access_units) { return 1024; } - SbTime duration = + int64_t duration = access_units.back().timestamp() - access_units.front().timestamp(); SB_DCHECK(duration > 0); @@ -46,7 +46,7 @@ int64_t CalculateAverageBitrate(const std::vector& access_units) { total_bitrate += au.data().size(); } - return total_bitrate * 8 * kSbTimeSecond / duration; + return total_bitrate * 8 * 1'000'000LL / duration; } static void DeallocateSampleFunc(SbPlayer player, @@ -305,8 +305,8 @@ void VideoDmpReader::Parse() { } // Guestimate the video fps. if (video_access_units_.size() > 1) { - SbTime first_timestamp = video_access_units_.front().timestamp(); - SbTime second_timestamp = video_access_units_.back().timestamp(); + int64_t first_timestamp = video_access_units_.front().timestamp(); + int64_t second_timestamp = video_access_units_.back().timestamp(); for (const auto& au : video_access_units_) { if (au.timestamp() != first_timestamp && au.timestamp() < second_timestamp) { @@ -314,10 +314,10 @@ void VideoDmpReader::Parse() { } } SB_DCHECK(first_timestamp < second_timestamp); - SbTime frame_duration = second_timestamp - first_timestamp; - dmp_info_.video_fps = kSbTimeSecond / frame_duration; + int64_t frame_duration = second_timestamp - first_timestamp; + dmp_info_.video_fps = 1'000'000LL / frame_duration; - SbTime last_frame_timestamp = video_access_units_.back().timestamp(); + int64_t last_frame_timestamp = video_access_units_.back().timestamp(); for (auto it = video_access_units_.rbegin(); it != video_access_units_.rend(); it++) { if (it->timestamp() > last_frame_timestamp) { @@ -351,7 +351,7 @@ void VideoDmpReader::EnsureSampleLoaded(SbMediaType type, size_t index) { } VideoDmpReader::AudioAccessUnit VideoDmpReader::ReadAudioAccessUnit() { - SbTime timestamp; + int64_t timestamp; Read(read_cb_, reverse_byte_order_.value(), ×tamp); bool drm_sample_info_present; @@ -376,7 +376,7 @@ VideoDmpReader::AudioAccessUnit VideoDmpReader::ReadAudioAccessUnit() { } VideoDmpReader::VideoAccessUnit VideoDmpReader::ReadVideoAccessUnit() { - SbTime timestamp; + int64_t timestamp; Read(read_cb_, reverse_byte_order_.value(), ×tamp); bool drm_sample_info_present; diff --git a/starboard/shared/starboard/player/video_dmp_reader.h b/starboard/shared/starboard/player/video_dmp_reader.h index 9b745a1e7a0b..a4d385ca7470 100644 --- a/starboard/shared/starboard/player/video_dmp_reader.h +++ b/starboard/shared/starboard/player/video_dmp_reader.h @@ -47,7 +47,7 @@ class VideoDmpReader { class AccessUnit { public: - AccessUnit(SbTime timestamp, + AccessUnit(int64_t timestamp, const SbDrmSampleInfoWithSubSampleMapping* drm_sample_info, std::vector data) : timestamp_(timestamp), @@ -56,14 +56,14 @@ class VideoDmpReader { ? SbDrmSampleInfoWithSubSampleMapping() : *drm_sample_info), data_(std::move(data)) {} - SbTime timestamp() const { return timestamp_; } + int64_t timestamp() const { return timestamp_; } const SbDrmSampleInfo* drm_sample_info() const { return drm_sample_info_present_ ? &drm_sample_info_ : NULL; } const std::vector& data() const { return data_; } private: - SbTime timestamp_; + int64_t timestamp_; // microseconds bool drm_sample_info_present_; SbDrmSampleInfoWithSubSampleMapping drm_sample_info_; std::vector data_; @@ -71,7 +71,7 @@ class VideoDmpReader { class AudioAccessUnit : public AccessUnit { public: - AudioAccessUnit(SbTime timestamp, + AudioAccessUnit(int64_t timestamp, const SbDrmSampleInfoWithSubSampleMapping* drm_sample_info, std::vector data, media::AudioSampleInfo audio_sample_info) @@ -87,7 +87,7 @@ class VideoDmpReader { class VideoAccessUnit : public AccessUnit { public: - VideoAccessUnit(SbTime timestamp, + VideoAccessUnit(int64_t timestamp, const SbDrmSampleInfoWithSubSampleMapping* drm_sample_info, std::vector data, media::VideoSampleInfo video_sample_info) @@ -117,13 +117,13 @@ class VideoDmpReader { } int64_t audio_bitrate() const { return dmp_info_.audio_bitrate; } std::string audio_mime_type() const; - SbTime audio_duration() const { return dmp_info_.audio_duration; } + int64_t audio_duration() const { return dmp_info_.audio_duration; } SbMediaVideoCodec video_codec() const { return dmp_info_.video_codec; } int64_t video_bitrate() const { return dmp_info_.video_bitrate; } int video_fps() const { return dmp_info_.video_fps; } std::string video_mime_type(); - SbTime video_duration() const { return dmp_info_.video_duration; } + int64_t video_duration() const { return dmp_info_.video_duration; } size_t number_of_audio_buffers() const { return dmp_info_.audio_access_units_size; diff --git a/starboard/shared/starboard/player/video_dmp_writer.cc b/starboard/shared/starboard/player/video_dmp_writer.cc index c421f0e37a62..dab55d485435 100644 --- a/starboard/shared/starboard/player/video_dmp_writer.cc +++ b/starboard/shared/starboard/player/video_dmp_writer.cc @@ -154,7 +154,7 @@ void VideoDmpWriter::DumpAccessUnit( const SbMediaType& sample_type = input_buffer->sample_type(); const void* sample_buffer = static_cast(input_buffer->data()); const int& sample_buffer_size = input_buffer->size(); - const SbTime& sample_timestamp = input_buffer->timestamp(); + const int64_t& sample_timestamp = input_buffer->timestamp(); const SbDrmSampleInfo* drm_sample_info = input_buffer->drm_info(); if (sample_type == kSbMediaTypeAudio) { diff --git a/starboard/shared/starboard/queue_application.cc b/starboard/shared/starboard/queue_application.cc index b6289770636c..bb4a186821ab 100644 --- a/starboard/shared/starboard/queue_application.cc +++ b/starboard/shared/starboard/queue_application.cc @@ -17,8 +17,8 @@ #include "starboard/common/atomic.h" #include "starboard/common/condition_variable.h" #include "starboard/common/log.h" +#include "starboard/common/time.h" #include "starboard/event.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -61,7 +61,7 @@ Application::Event* QueueApplication::GetNextEvent() { // Then we block indefinitely on the Window's DFB queue. event = WaitForSystemEventWithTimeout(GetNextTimedEventTargetTime() - - SbTimeGetMonotonicNow()); + CurrentMonotonicTime()); } return event; @@ -113,7 +113,7 @@ Application::TimedEvent* QueueApplication::GetNextDueTimedEvent() { return timed_event_queue_.Get(); } -SbTimeMonotonic QueueApplication::GetNextTimedEventTargetTime() { +int64_t QueueApplication::GetNextTimedEventTargetTime() { return timed_event_queue_.GetTime(); } @@ -130,7 +130,7 @@ QueueApplication::TimedEventQueue::~TimedEventQueue() { bool QueueApplication::TimedEventQueue::Inject(TimedEvent* timed_event) { ScopedLock lock(mutex_); - SbTimeMonotonic oldTime = GetTimeLocked(); + int64_t oldTime = GetTimeLocked(); map_[timed_event->id] = timed_event; set_.insert(timed_event); return (timed_event->target_time < oldTime); @@ -156,7 +156,7 @@ Application::TimedEvent* QueueApplication::TimedEventQueue::Get() { } TimedEvent* timed_event = *(set_.begin()); - if (timed_event->target_time > SbTimeGetMonotonicNow()) { + if (timed_event->target_time > CurrentMonotonicTime()) { return NULL; } @@ -165,19 +165,19 @@ Application::TimedEvent* QueueApplication::TimedEventQueue::Get() { return timed_event; } -SbTimeMonotonic QueueApplication::TimedEventQueue::GetTime() { +int64_t QueueApplication::TimedEventQueue::GetTime() { ScopedLock lock(mutex_); return GetTimeLocked(); } -SbTimeMonotonic QueueApplication::TimedEventQueue::GetTimeLocked() { +int64_t QueueApplication::TimedEventQueue::GetTimeLocked() { if (set_.empty()) { - return kSbTimeMax; + return kSbInt64Max; } TimedEvent* timed_event = *(set_.begin()); - SbTimeMonotonic time = timed_event->target_time; - SbTimeMonotonic now = SbTimeGetMonotonicNow(); + int64_t time = timed_event->target_time; + int64_t now = CurrentMonotonicTime(); if (time < now) { return now; } @@ -188,7 +188,7 @@ SbTimeMonotonic QueueApplication::TimedEventQueue::GetTimeLocked() { // static bool QueueApplication::TimedEventQueue::IsLess(const TimedEvent* lhs, const TimedEvent* rhs) { - SbTimeMonotonic time_difference = lhs->target_time - rhs->target_time; + int64_t time_difference = lhs->target_time - rhs->target_time; if (time_difference != 0) { return time_difference < 0; } @@ -214,8 +214,7 @@ Application::Event* QueueApplication::PollNextInjectedEvent() { Application::Event* QueueApplication::GetNextInjectedEvent() { for (;;) { - SbTimeMonotonic delay = - GetNextTimedEventTargetTime() - SbTimeGetMonotonicNow(); + int64_t delay = GetNextTimedEventTargetTime() - CurrentMonotonicTime(); Event* event = event_queue_.GetTimed(delay); if (event != NULL) { return event; diff --git a/starboard/shared/starboard/queue_application.h b/starboard/shared/starboard/queue_application.h index 63fea544f7bd..c32237cca49b 100644 --- a/starboard/shared/starboard/queue_application.h +++ b/starboard/shared/starboard/queue_application.h @@ -53,7 +53,7 @@ class QueueApplication : public Application { void InjectTimedEvent(TimedEvent* timed_event) override; void CancelTimedEvent(SbEventId event_id) override; TimedEvent* GetNextDueTimedEvent() override; - SbTimeMonotonic GetNextTimedEventTargetTime() override; + int64_t GetNextTimedEventTargetTime() override; // Add the given event onto the event queue, then process the queue until the // event is handled. This is similar to DispatchAndDelete but will process @@ -68,13 +68,14 @@ class QueueApplication : public Application { // Returns an event if one exists, otherwise returns NULL. virtual Event* PollNextSystemEvent() { - return WaitForSystemEventWithTimeout(SbTime()); + return WaitForSystemEventWithTimeout(0); } - // Waits for an event until the timeout |time| runs out. If an event occurs - // in this time, it is returned, otherwise NULL is returned. If |time| is zero - // or negative, then this should function effectively like a no-wait poll. - virtual Event* WaitForSystemEventWithTimeout(SbTime time) = 0; + // Waits for an event until the timeout |time| (in microseconds) runs out. If + // an event occurs in this time, it is returned, otherwise NULL is returned. + // If |time| is zero or negative, then this should function effectively like + // a no-wait poll. + virtual Event* WaitForSystemEventWithTimeout(int64_t time) = 0; // Wakes up any thread waiting within a call to // WaitForSystemEventWithTimeout(). @@ -110,10 +111,10 @@ class QueueApplication : public Application { bool Inject(TimedEvent* timed_event); void Cancel(SbEventId event_id); TimedEvent* Get(); - SbTimeMonotonic GetTime(); + int64_t GetTime(); private: - SbTimeMonotonic GetTimeLocked(); + int64_t GetTimeLocked(); typedef bool (*TimedEventComparator)(const TimedEvent* lhs, const TimedEvent* rhs); static bool IsLess(const TimedEvent* lhs, const TimedEvent* rhs); diff --git a/starboard/shared/starboard/socket/socket_tracker.cc b/starboard/shared/starboard/socket/socket_tracker.cc index 782f819976cc..eddd4cc064cd 100644 --- a/starboard/shared/starboard/socket/socket_tracker.cc +++ b/starboard/shared/starboard/socket/socket_tracker.cc @@ -18,6 +18,7 @@ #include #include "starboard/common/log.h" +#include "starboard/common/time.h" namespace starboard { namespace shared { @@ -37,7 +38,7 @@ void SocketTracker::OnCreate(SbSocket socket, record.thread_id = SbThreadGetId(); record.address_type = address_type; record.protocol = protocol; - record.last_activity = SbTimeGetMonotonicNow(); + record.last_activity = CurrentMonotonicTime(); record.state = kCreated; ScopedLock scoped_lock(mutex_); @@ -77,7 +78,7 @@ void SocketTracker::OnAccept(SbSocket listening_socket, auto iter = sockets_.find(listening_socket); SB_DCHECK(iter != sockets_.end()); - iter->second.last_activity = SbTimeGetMonotonicNow(); + iter->second.last_activity = CurrentMonotonicTime(); SocketRecord record; record.thread_id = SbThreadGetId(); @@ -96,7 +97,7 @@ void SocketTracker::OnReceiveFrom(SbSocket socket, auto iter = sockets_.find(socket); SB_DCHECK(iter != sockets_.end()); - iter->second.last_activity = SbTimeGetMonotonicNow(); + iter->second.last_activity = CurrentMonotonicTime(); if (source) { iter->second.remote_address = *source; } @@ -108,7 +109,7 @@ void SocketTracker::OnSendTo(SbSocket socket, auto iter = sockets_.find(socket); SB_DCHECK(iter != sockets_.end()); - iter->second.last_activity = SbTimeGetMonotonicNow(); + iter->second.last_activity = CurrentMonotonicTime(); if (destination) { iter->second.remote_address = *destination; } @@ -141,7 +142,7 @@ void SocketTracker::OnListen(SbSocket socket) { auto iter = sockets_.find(socket); SB_DCHECK(iter != sockets_.end()); - iter->second.last_activity = SbTimeGetMonotonicNow(); + iter->second.last_activity = CurrentMonotonicTime(); SB_DCHECK(iter->second.state == kCreated); iter->second.state = kListened; } @@ -158,7 +159,7 @@ void SocketTracker::OnAddWaiter(SbSocket socket, SbSocketWaiter waiter) { auto iter = sockets_.find(socket); SB_DCHECK(iter != sockets_.end()); - iter->second.last_activity = SbTimeGetMonotonicNow(); + iter->second.last_activity = CurrentMonotonicTime(); SB_DCHECK(!SbSocketWaiterIsValid(iter->second.waiter)); SB_DCHECK(SbSocketWaiterIsValid(waiter)); iter->second.waiter = waiter; @@ -169,7 +170,7 @@ void SocketTracker::OnRemoveWaiter(SbSocket socket, SbSocketWaiter waiter) { auto iter = sockets_.find(socket); SB_DCHECK(iter != sockets_.end()); - iter->second.last_activity = SbTimeGetMonotonicNow(); + iter->second.last_activity = CurrentMonotonicTime(); SB_DCHECK(waiter == iter->second.waiter); SB_DCHECK(SbSocketWaiterIsValid(waiter)); iter->second.waiter = kSbSocketWaiterInvalid; @@ -198,14 +199,14 @@ std::string SocketTracker::ConvertToString_Locked( return ss.str(); } -std::multimap +std::multimap SocketTracker::ComputeIdleTimePerSocketForThreadId(SbThreadId thread_id) { - std::multimap idle_times_to_sockets; + std::multimap idle_times_to_sockets; for (auto it = sockets_.begin(); it != sockets_.end(); ++it) { if (it->second.thread_id != thread_id || it->second.state == kListened) { continue; } - SbTimeMonotonic time_idle = ComputeTimeIdle(it->second); + int64_t time_idle = ComputeTimeIdle(it->second); idle_times_to_sockets.insert(std::make_pair(time_idle, it->first)); } return idle_times_to_sockets; @@ -235,14 +236,14 @@ std::string SocketTracker::ConvertToString_Locked( ss << ", listen called,"; break; } - ss << " has been idle for " << ComputeTimeIdle(record) * 1.0f / kSbTimeSecond + ss << " has been idle for " << ComputeTimeIdle(record) * 1.0f / 1'000'000LL << " seconds"; return ss.str(); } // static -SbTimeMonotonic SocketTracker::ComputeTimeIdle(const SocketRecord& record) { - return SbTimeGetMonotonicNow() - record.last_activity; +int64_t SocketTracker::ComputeTimeIdle(const SocketRecord& record) { + return CurrentMonotonicTime() - record.last_activity; } } // namespace socket diff --git a/starboard/shared/starboard/socket/socket_tracker.h b/starboard/shared/starboard/socket/socket_tracker.h index d5475c427097..cd6b84c1ee8c 100644 --- a/starboard/shared/starboard/socket/socket_tracker.h +++ b/starboard/shared/starboard/socket/socket_tracker.h @@ -26,7 +26,6 @@ #include "starboard/memory.h" #include "starboard/socket_waiter.h" #include "starboard/thread.h" -#include "starboard/time.h" // TODO: Move this to starboard/socket.h. inline bool operator<(const SbSocketAddress& left, @@ -84,7 +83,7 @@ class SocketTracker { State GetState(SbSocket socket); void LogTrackedSockets(); - std::multimap ComputeIdleTimePerSocketForThreadId( + std::multimap ComputeIdleTimePerSocketForThreadId( SbThreadId thread_id); private: @@ -93,7 +92,7 @@ class SocketTracker { SbSocketProtocol protocol; optional local_address; optional remote_address; - SbTime last_activity; + int64_t last_activity; SbSocketWaiter waiter = kSbSocketWaiterInvalid; SbThreadId thread_id; State state; @@ -101,7 +100,7 @@ class SocketTracker { std::string ConvertToString_Locked(SbSocketAddress address) const; std::string ConvertToString_Locked(const SocketRecord& record) const; - static SbTimeMonotonic ComputeTimeIdle(const SocketRecord& record); + static int64_t ComputeTimeIdle(const SocketRecord& record); Mutex mutex_; std::map sockets_; diff --git a/starboard/shared/stub/condition_variable_wait_timed.cc b/starboard/shared/stub/condition_variable_wait_timed.cc index f7fcd31c3cc5..dfc22d29771a 100644 --- a/starboard/shared/stub/condition_variable_wait_timed.cc +++ b/starboard/shared/stub/condition_variable_wait_timed.cc @@ -17,6 +17,6 @@ SbConditionVariableResult SbConditionVariableWaitTimed( SbConditionVariable* condition, SbMutex* mutex, - SbTime timeout) { + int64_t timeout) { return kSbConditionVariableFailed; } diff --git a/starboard/shared/stub/media_get_buffer_garbage_collection_duration_threshold.cc b/starboard/shared/stub/media_get_buffer_garbage_collection_duration_threshold.cc index b9f8650b80b3..09578a2e3150 100644 --- a/starboard/shared/stub/media_get_buffer_garbage_collection_duration_threshold.cc +++ b/starboard/shared/stub/media_get_buffer_garbage_collection_duration_threshold.cc @@ -14,6 +14,6 @@ #include "starboard/media.h" -SbTime SbMediaGetBufferGarbageCollectionDurationThreshold() { +int64_t SbMediaGetBufferGarbageCollectionDurationThreshold() { return 0; } diff --git a/starboard/shared/stub/media_set_audio_write_duration.cc b/starboard/shared/stub/media_set_audio_write_duration.cc index 0d2776e1f36d..67898e1da052 100644 --- a/starboard/shared/stub/media_set_audio_write_duration.cc +++ b/starboard/shared/stub/media_set_audio_write_duration.cc @@ -18,10 +18,10 @@ #if SB_API_VERSION < 15 -void SbMediaSetAudioWriteDuration(SbTime duration) { +void SbMediaSetAudioWriteDuration(int64_t duration) { // The stub implementation assumes no further action is needed from the // platform to be compatible with limits >= 0.5 second. - SB_DCHECK(duration >= kSbTimeSecond / 2) + SB_DCHECK(duration >= 500'000) << "Limiting audio to less than 0.5 seconds is unexpected."; } diff --git a/starboard/shared/stub/player_seek.cc b/starboard/shared/stub/player_seek.cc index 755f344e3897..43acbe2b842b 100644 --- a/starboard/shared/stub/player_seek.cc +++ b/starboard/shared/stub/player_seek.cc @@ -15,7 +15,7 @@ #include "starboard/player.h" #if SB_API_VERSION >= 15 -void SbPlayerSeek(SbPlayer player, SbTime seek_to_timestamp, int ticket) {} +void SbPlayerSeek(SbPlayer player, int64_t seek_to_timestamp, int ticket) {} #else // SB_API_VERSION >= 15 -void SbPlayerSeek2(SbPlayer player, SbTime seek_to_timestamp, int ticket) {} +void SbPlayerSeek2(SbPlayer player, int64_t seek_to_timestamp, int ticket) {} #endif // SB_API_VERSION >= 15 diff --git a/starboard/shared/stub/socket_set_tcp_keep_alive.cc b/starboard/shared/stub/socket_set_tcp_keep_alive.cc index 16f9be3b1c4e..40f35b716612 100644 --- a/starboard/shared/stub/socket_set_tcp_keep_alive.cc +++ b/starboard/shared/stub/socket_set_tcp_keep_alive.cc @@ -14,6 +14,6 @@ #include "starboard/common/socket.h" -bool SbSocketSetTcpKeepAlive(SbSocket socket, bool value, SbTime period) { +bool SbSocketSetTcpKeepAlive(SbSocket socket, bool value, int64_t period) { return false; } diff --git a/starboard/shared/stub/socket_waiter_wait_timed.cc b/starboard/shared/stub/socket_waiter_wait_timed.cc index f742ab4581ac..e58ecfc77857 100644 --- a/starboard/shared/stub/socket_waiter_wait_timed.cc +++ b/starboard/shared/stub/socket_waiter_wait_timed.cc @@ -15,6 +15,6 @@ #include "starboard/socket_waiter.h" SbSocketWaiterResult SbSocketWaiterWaitTimed(SbSocketWaiter waiter, - SbTime duration) { + int64_t duration) { return kSbSocketWaiterResultInvalid; } diff --git a/starboard/shared/stub/thread_sleep.cc b/starboard/shared/stub/thread_sleep.cc index 49eb0a20d7e5..a3397e51e1eb 100644 --- a/starboard/shared/stub/thread_sleep.cc +++ b/starboard/shared/stub/thread_sleep.cc @@ -14,4 +14,4 @@ #include "starboard/thread.h" -void SbThreadSleep(SbTime duration) {} +void SbThreadSleep(int64_t duration) {} diff --git a/starboard/shared/stub/time_get_monotonic_now.cc b/starboard/shared/stub/time_get_monotonic_now.cc index 8b6a3aa94028..a012ce20ab38 100644 --- a/starboard/shared/stub/time_get_monotonic_now.cc +++ b/starboard/shared/stub/time_get_monotonic_now.cc @@ -12,8 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if SB_API_VERSION < 16 + #include "starboard/time.h" SbTimeMonotonic SbTimeGetMonotonicNow() { return SbTimeMonotonic(); } + +#endif // SB_API_VERSION < 16 diff --git a/starboard/shared/stub/time_get_now.cc b/starboard/shared/stub/time_get_now.cc index bc3914753e21..25362a35846b 100644 --- a/starboard/shared/stub/time_get_now.cc +++ b/starboard/shared/stub/time_get_now.cc @@ -12,8 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if SB_API_VERSION < 16 + #include "starboard/time.h" SbTime SbTimeGetNow() { return SbTime(); } + +#endif // SB_API_VERSION < 16 diff --git a/starboard/shared/uwp/analog_thumbstick_input_thread.cc b/starboard/shared/uwp/analog_thumbstick_input_thread.cc index 2e756b49a546..fcaa59c29494 100644 --- a/starboard/shared/uwp/analog_thumbstick_input_thread.cc +++ b/starboard/shared/uwp/analog_thumbstick_input_thread.cc @@ -44,7 +44,7 @@ class AnalogThumbstickThread::Impl : public Thread { while (!join_called()) { Update(); // 120hz to provide smooth 60fps playback. - SbThreadSleep(kSbTimeSecond / kPollingFrequency); + SbThreadSleep(1'000'000LL / kPollingFrequency); } } diff --git a/starboard/shared/uwp/application_uwp.cc b/starboard/shared/uwp/application_uwp.cc index de19fb02d649..c800916c39c7 100644 --- a/starboard/shared/uwp/application_uwp.cc +++ b/starboard/shared/uwp/application_uwp.cc @@ -38,6 +38,7 @@ #include "starboard/common/string.h" #include "starboard/common/system_property.h" #include "starboard/common/thread.h" +#include "starboard/common/time.h" #include "starboard/configuration_constants.h" #include "starboard/event.h" #include "starboard/input.h" @@ -144,11 +145,6 @@ const Platform::String ^ kGenericPnpMonitorAqs = ref new Platform::String( const uint32_t kYuv420BitsPerPixelForHdr10Mode = 24; -// The number of seconds to wait after requesting application stop. This is used -// to exit the app when a suspend has been requested. This is a temporary -// behavior that should be removed when not needed anymore. -const SbTime kAppExitWaitTime = kSbTimeSecond * 30; - // Per Microsoft, HdcpProtection::On means HDCP 1.x required. const HdcpProtection kHDCPProtectionMode = HdcpProtection::On; @@ -273,7 +269,8 @@ void TryAddCommandArgsFromStarboardFile(std::vector* args) { AddArgumentsFromFile(arguments_file_path.c_str(), args); } -void AddCommandArgsFromNetArgs(SbTime timeout, std::vector* args) { +void AddCommandArgsFromNetArgs(int64_t timeout, + std::vector* args) { // Detect if NetArgs is enabled for this run. If so then receive and // then merge the arguments into this run. SB_LOG(INFO) << "Waiting for net args..."; @@ -333,7 +330,7 @@ std::string GetBinaryName() { void OnDeviceAdded(DeviceWatcher ^, DeviceInformation ^) { SB_LOG(INFO) << "DisplayStatusWatcher::OnDeviceAdded"; // We need delay to give time for the display initializing after connect. - SbThreadSleep(15 * kSbTimeMillisecond); + SbThreadSleep(15'000); MimeSupportabilityCache::GetInstance()->ClearCachedMimeSupportabilities(); @@ -370,7 +367,7 @@ extern void DrmSystemOnUwpResume(); ref class App sealed : public IFrameworkView { public: - App(SbTimeMonotonic start_time) + App(int64_t start_time) : application_start_time_{start_time}, previously_activated_(false), #if SB_API_VERSION >= 15 @@ -661,12 +658,12 @@ ref class App sealed : public IFrameworkView { CommandLine cmd_line(args_); if (cmd_line.HasSwitch(kNetArgsCommandSwitchWait)) { // Wait for net args is flaky and needs extended wait time on Xbox. - SbTime timeout = kSbTimeSecond * 30; + int64_t timeout_usec = 30'000'000; // 30 seconds std::string val = cmd_line.GetSwitchValue(kNetArgsCommandSwitchWait); if (!val.empty()) { - timeout = atoi(val.c_str()); + timeout_usec = atoi(val.c_str()); } - AddCommandArgsFromNetArgs(timeout, &args_); + AddCommandArgsFromNetArgs(timeout_usec, &args_); } #endif // defined(ENABLE_DEBUG_COMMAND_LINE_SWITCHES) @@ -703,13 +700,13 @@ ref class App sealed : public IFrameworkView { } if (command_line->HasSwitch(kNetLogCommandSwitchWait)) { - SbTime timeout = kSbTimeSecond; + int64_t timeout_usec = 1'000'000; // 1 second std::string val = command_line->GetSwitchValue(kNetLogCommandSwitchWait); if (!val.empty()) { - timeout = atoi(val.c_str()); + timeout_usec = atoi(val.c_str()); } - NetLogWaitForClientConnected(timeout); + NetLogWaitForClientConnected(timeout_usec); } if (command_line->HasSwitch(kLogPathSwitch)) { @@ -794,16 +791,16 @@ ref class App sealed : public IFrameworkView { shared::uwp::ApplicationUwp application_; SuspendingDeferral ^ suspend_deferral_ = nullptr; - SbTimeMonotonic application_start_time_; + int64_t application_start_time_; }; ref class Direct3DApplicationSource sealed : IFrameworkViewSource { public: - Direct3DApplicationSource(SbTimeMonotonic start_time) + Direct3DApplicationSource(int64_t start_time) : application_start_time_{start_time} {} virtual IFrameworkView ^ CreateView() { return ref new App(application_start_time_); - } private : SbTimeMonotonic application_start_time_; + } private : int64_t application_start_time_; }; namespace shared { @@ -1059,14 +1056,13 @@ void ApplicationUwp::InjectKeypress(SbKey key) { } void ApplicationUwp::InjectTimedEvent(Application::TimedEvent* timed_event) { - SbTimeMonotonic delay_usec = - timed_event->target_time - SbTimeGetMonotonicNow(); + int64_t delay_usec = timed_event->target_time - CurrentMonotonicTime(); if (delay_usec < 0) { delay_usec = 0; } // TimeSpan ticks are, like FILETIME, 100ns - const SbTimeMonotonic kTicksPerUsec = 10; + const int64_t kTicksPerUsec = 10; TimeSpan timespan; timespan.Duration = delay_usec * kTicksPerUsec; @@ -1107,7 +1103,7 @@ Application::TimedEvent* ApplicationUwp::GetNextDueTimedEvent() { return nullptr; } -SbTimeMonotonic ApplicationUwp::GetNextTimedEventTargetTime() { +int64_t ApplicationUwp::GetNextTimedEventTargetTime() { SB_NOTIMPLEMENTED(); return 0; } @@ -1215,7 +1211,7 @@ bool ApplicationUwp::SetOutputProtection(bool should_enable_dhcp) { << (should_enable_dhcp ? "enable" : "disable") << " output protection. Current status: " << (is_hdcp_on ? "enabled" : "disabled"); - SbTimeMonotonic tick = SbTimeGetMonotonicNow(); + int64_t tick = CurrentMonotonicTime(); bool hdcp_success = false; if (should_enable_dhcp) { @@ -1226,10 +1222,10 @@ bool ApplicationUwp::SetOutputProtection(bool should_enable_dhcp) { is_hdcp_on = (hdcp_success ? should_enable_dhcp : !should_enable_dhcp); - SbTimeMonotonic tock = SbTimeGetMonotonicNow(); + int64_t tock = CurrentMonotonicTime(); SB_LOG(INFO) << "Output protection is " << (is_hdcp_on ? "enabled" : "disabled") - << ". Toggling HDCP took " << (tock - tick) / kSbTimeMillisecond + << ". Toggling HDCP took " << (tock - tick) / 1000 << " milliseconds."; return hdcp_success; } @@ -1270,7 +1266,7 @@ namespace { // thread. class CoreApplicationThread : public ::starboard::Thread { public: - explicit CoreApplicationThread(SbTimeMonotonic start_time) + explicit CoreApplicationThread(int64_t start_time) : application_start_time_{start_time}, Thread("core_app") {} void Run() override { CoreApplication::Run( @@ -1279,13 +1275,13 @@ class CoreApplicationThread : public ::starboard::Thread { } private: - SbTimeMonotonic application_start_time_; + int64_t application_start_time_; }; } // namespace int InternalMain() { - volatile auto start_time = SbTimeGetMonotonicNow(); + volatile auto start_time = CurrentMonotonicTime(); if (!IsDebuggerPresent()) { // By default, a Windows application will display a dialog box // when it crashes. This is extremely undesirable when run offline. diff --git a/starboard/shared/uwp/application_uwp.h b/starboard/shared/uwp/application_uwp.h index c11945c44828..8deeb9138616 100644 --- a/starboard/shared/uwp/application_uwp.h +++ b/starboard/shared/uwp/application_uwp.h @@ -72,7 +72,7 @@ class ApplicationUwp : public shared::starboard::Application, bool DestroyWindow(SbWindow window); - void DispatchStart(SbTimeMonotonic timestamp) { + void DispatchStart(int64_t timestamp) { shared::starboard::Application::DispatchStart(timestamp); } @@ -177,7 +177,7 @@ class ApplicationUwp : public shared::starboard::Application, void InjectTimedEvent(TimedEvent* timed_event) override; void CancelTimedEvent(SbEventId event_id) override; TimedEvent* GetNextDueTimedEvent() override; - SbTimeMonotonic GetNextTimedEventTargetTime() override; + int64_t GetNextTimedEventTargetTime() override; int device_id() const { return device_id_; } void OnJoystickUpdate(SbKey key, SbInputVector value) override; diff --git a/starboard/shared/uwp/audio_renderer_passthrough.cc b/starboard/shared/uwp/audio_renderer_passthrough.cc index 940bb83e73a7..e6a1e6b115e4 100644 --- a/starboard/shared/uwp/audio_renderer_passthrough.cc +++ b/starboard/shared/uwp/audio_renderer_passthrough.cc @@ -172,12 +172,12 @@ void AudioRendererPassthrough::SetPlaybackRate(double playback_rate) { sink_->SetPlaybackRate(playback_rate); } -void AudioRendererPassthrough::Seek(SbTime seek_to_time) { +void AudioRendererPassthrough::Seek(int64_t seek_to_time) { SB_DCHECK(BelongsToCurrentThread()); SB_DCHECK(seek_to_time >= 0); { ScopedLock lock(mutex_); - seeking_to_time_ = std::max(seek_to_time, 0); + seeking_to_time_ = std::max(seek_to_time, 0); seeking_ = true; } @@ -194,10 +194,10 @@ void AudioRendererPassthrough::Seek(SbTime seek_to_time) { CancelPendingJobs(); } -SbTime AudioRendererPassthrough::GetCurrentMediaTime(bool* is_playing, - bool* is_eos_played, - bool* is_underflow, - double* playback_rate) { +int64_t AudioRendererPassthrough::GetCurrentMediaTime(bool* is_playing, + bool* is_eos_played, + bool* is_underflow, + double* playback_rate) { SB_DCHECK(is_playing); SB_DCHECK(is_eos_played); SB_DCHECK(is_underflow); @@ -214,7 +214,7 @@ SbTime AudioRendererPassthrough::GetCurrentMediaTime(bool* is_playing, } uint64_t sink_playback_time_updated_at; - SbTime sink_playback_time = static_cast( + int64_t sink_playback_time = static_cast( sink_->GetCurrentPlaybackTime(&sink_playback_time_updated_at)); if (sink_playback_time <= 0) { if (sink_playback_time < 0) { @@ -224,7 +224,7 @@ SbTime AudioRendererPassthrough::GetCurrentMediaTime(bool* is_playing, return seeking_to_time_; } - SbTime media_time = seeking_to_time_ + sink_playback_time; + int64_t media_time = seeking_to_time_ + sink_playback_time; if (!sink_->playing()) { return media_time; } @@ -258,7 +258,7 @@ void AudioRendererPassthrough::ProcessAudioBuffers() { SB_DCHECK(!pending_inputs_.empty()); process_audio_buffers_job_token_.ResetToInvalid(); - SbTime process_audio_buffers_job_delay = 5 * kSbTimeMillisecond; + int64_t process_audio_buffers_job_delay_usec = 5'000; // 5ms scoped_refptr decoded_audio = pending_inputs_.front(); SB_DCHECK(decoded_audio); @@ -283,7 +283,7 @@ void AudioRendererPassthrough::ProcessAudioBuffers() { if (decoded_audio && TryToWriteAudioBufferToSink(decoded_audio)) { pending_inputs_.pop(); - process_audio_buffers_job_delay = 0; + process_audio_buffers_job_delay_usec = 0; if (seeking_ && total_buffers_sent_to_sink_ >= kNumPrerollDecodedAudios) { seeking_ = false; Schedule(prerolled_cb_); @@ -292,8 +292,8 @@ void AudioRendererPassthrough::ProcessAudioBuffers() { } if (!pending_inputs_.empty()) { - process_audio_buffers_job_token_ = - Schedule(process_audio_buffers_job_, process_audio_buffers_job_delay); + process_audio_buffers_job_token_ = Schedule( + process_audio_buffers_job_, process_audio_buffers_job_delay_usec); return; } @@ -321,7 +321,7 @@ void AudioRendererPassthrough::TryToEndStream() { int64_t total_frames_played_by_sink = GetCurrentMediaTime(&is_playing, &is_eos_played, &is_underflow, &playback_rate) * - iec_sample_rate_ / kSbTimeSecond; + iec_sample_rate_ / 1'000'000; // Wait for the audio sink to output the remaining frames before calling // Pause(). if (total_frames_played_by_sink >= total_frames_sent_to_sink_) { @@ -330,11 +330,10 @@ void AudioRendererPassthrough::TryToEndStream() { ended_cb_(); return; } - Schedule(std::bind(&AudioRendererPassthrough::TryToEndStream, this), - 5 * kSbTimeMillisecond); + Schedule(std::bind(&AudioRendererPassthrough::TryToEndStream, this), 5'000); } -SbTime AudioRendererPassthrough::CalculateElapsedPlaybackTime( +int64_t AudioRendererPassthrough::CalculateElapsedPlaybackTime( uint64_t update_time) { LARGE_INTEGER current_time; QueryPerformanceCounter(¤t_time); @@ -345,15 +344,14 @@ SbTime AudioRendererPassthrough::CalculateElapsedPlaybackTime( (10000000.0 / static_cast(performance_frequency_.QuadPart)); SB_DCHECK(current_time_converted >= update_time); - // Convert elapsed time to SbTime. - return ((current_time_converted - update_time) * 100) / - kSbTimeNanosecondsPerMicrosecond; + // Convert elapsed time to microseconds. + return ((current_time_converted - update_time) * 100) / 1000; } -SbTime AudioRendererPassthrough::CalculateLastOutputTime( +int64_t AudioRendererPassthrough::CalculateLastOutputTime( scoped_refptr& decoded_audio) { return decoded_audio->timestamp() + - (decoded_audio->frames() / iec_sample_rate_ * kSbTimeSecond); + (decoded_audio->frames() / iec_sample_rate_ * 1'000'000); } } // namespace uwp diff --git a/starboard/shared/uwp/audio_renderer_passthrough.h b/starboard/shared/uwp/audio_renderer_passthrough.h index 3bfa7e52bf05..a169b18c37da 100644 --- a/starboard/shared/uwp/audio_renderer_passthrough.h +++ b/starboard/shared/uwp/audio_renderer_passthrough.h @@ -31,7 +31,6 @@ #include "starboard/shared/starboard/player/input_buffer_internal.h" #include "starboard/shared/starboard/player/job_queue.h" #include "starboard/shared/uwp/wasapi_audio_sink.h" -#include "starboard/time.h" #include "starboard/types.h" namespace starboard { @@ -70,11 +69,11 @@ class AudioRendererPassthrough : public AudioRenderer, void Play() override; void Pause() override; void SetPlaybackRate(double playback_rate) override; - void Seek(SbTime seek_to_time) override; - SbTime GetCurrentMediaTime(bool* is_playing, - bool* is_eos_played, - bool* is_underflow, - double* playback_rate) override; + void Seek(int64_t seek_to_time) override; + int64_t GetCurrentMediaTime(bool* is_playing, + bool* is_eos_played, + bool* is_underflow, + double* playback_rate) override; private: void OnDecoderConsumed(); @@ -87,11 +86,11 @@ class AudioRendererPassthrough : public AudioRenderer, // output. void TryToEndStream(); - // Calculates the playback time elapsed since the last time the timestamp was - // queried using WASAPIAudioSink::GetCurrentPlaybackTime(). - SbTime CalculateElapsedPlaybackTime(uint64_t update_time); - // Calculates the final output timestamp of a DecodedAudio. - SbTime CalculateLastOutputTime(scoped_refptr& decoded_audio); + // Calculates the playback time elapsed (microseconds) since the last time the + // timestamp was queried using WASAPIAudioSink::GetCurrentPlaybackTime(). + int64_t CalculateElapsedPlaybackTime(uint64_t update_time); + // Calculates the final output timestamp (microseconds) of a DecodedAudio. + int64_t CalculateLastOutputTime(scoped_refptr& decoded_audio); const int kMaxDecodedAudios = 16; // About 250 ms of (E)AC3 audio. @@ -105,7 +104,7 @@ class AudioRendererPassthrough : public AudioRenderer, bool paused_ = true; bool seeking_ = false; double playback_rate_ = 1.0; - SbTime seeking_to_time_ = 0; + int64_t seeking_to_time_ = 0; atomic_bool end_of_stream_written_{false}; atomic_bool end_of_stream_played_{false}; diff --git a/starboard/shared/uwp/decoder_utils.h b/starboard/shared/uwp/decoder_utils.h index e33dc4f37d1b..cf0b9e6284b7 100644 --- a/starboard/shared/uwp/decoder_utils.h +++ b/starboard/shared/uwp/decoder_utils.h @@ -21,7 +21,6 @@ #include #include "starboard/media.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -33,7 +32,7 @@ Microsoft::WRL::ComPtr GetDirectX11Device(void* display); // in containers. Useful in decoders for getting data from buffers keeped in // input queues; template -const auto FindByTimestamp(const Container& container, SbTime timestamp) { +const auto FindByTimestamp(const Container& container, int64_t timestamp) { return std::find_if(container.begin(), container.end(), [=](const typename Container::value_type& value) { return value->timestamp() == timestamp; @@ -44,7 +43,7 @@ const auto FindByTimestamp(const Container& container, SbTime timestamp) { // from containers. Useful in decoders for cleaning up input and output queues // from expired buffers. template -void RemoveByTimestamp(Container* container, SbTime timestamp) { +void RemoveByTimestamp(Container* container, int64_t timestamp) { auto to_remove = std::find_if(container->begin(), container->end(), [=](const typename Container::value_type& value) { diff --git a/starboard/shared/uwp/extended_resources_manager.cc b/starboard/shared/uwp/extended_resources_manager.cc index 21d2821441c7..3be4467c98e0 100644 --- a/starboard/shared/uwp/extended_resources_manager.cc +++ b/starboard/shared/uwp/extended_resources_manager.cc @@ -23,7 +23,6 @@ #include "starboard/shared/starboard/media/mime_supportability_cache.h" #include "starboard/shared/win32/video_decoder.h" #include "starboard/thread.h" -#include "starboard/time.h" #include "starboard/xb1/shared/internal_shims.h" #if defined(INTERNAL_BUILD) #include "internal/starboard/xb1/dav1d_video_decoder.h" @@ -46,7 +45,7 @@ using ::starboard::xb1::shared::GpuVideoDecoderBase; using ::starboard::xb1::shared::VpxVideoDecoder; #endif // defined(INTERNAL_BUILD) -const SbTime kReleaseTimeout = kSbTimeSecond; +const int64_t kReleaseTimeoutUsec = 1'000'000; // kFrameBuffersPoolMemorySize is the size of gpu memory heap for common use // by vpx & av1 sw decoders. @@ -115,9 +114,9 @@ void ExtendedResourcesManager::Run() { bool retrying_acquire = false; // Delay before retry acquiring to avoid pinning a core. - constexpr SbTime kRetryDelay = kSbTimeSecond / 10; + constexpr int64_t kRetryDelayUsec = 1'000'000 / 10; for (;;) { - switch (retrying_acquire ? event_queue_.GetTimed(kRetryDelay) + switch (retrying_acquire ? event_queue_.GetTimed(kRetryDelayUsec) : event_queue_.Get()) { case kTimeout: SB_DCHECK(retrying_acquire); @@ -324,7 +323,7 @@ bool ExtendedResourcesManager::AcquireExtendedResourcesInternal() { } semaphore.Put(); }); - if (semaphore.TakeWait(10 * kSbTimeSecond)) { + if (semaphore.TakeWait(10'000'000)) { acquisition_condition_.Signal(); // If extended resource acquisition was not successful after the wait // time, signal a nonrecoverable failure, unless a release of @@ -539,7 +538,7 @@ void ExtendedResourcesManager::ReleaseExtendedResourcesInternal() { pending_extended_resources_release_.store(false); semaphore.Put(); }); - if (!semaphore.TakeWait(kReleaseTimeout)) { + if (!semaphore.TakeWait(kReleaseTimeoutUsec)) { acquisition_condition_.Signal(); // If extended resources are still acquired or the release is still pending // after the wait time, signal a nonrecoverable failure. diff --git a/starboard/shared/uwp/microphone_impl.cc b/starboard/shared/uwp/microphone_impl.cc index a07b8f033003..34be711d1795 100644 --- a/starboard/shared/uwp/microphone_impl.cc +++ b/starboard/shared/uwp/microphone_impl.cc @@ -33,12 +33,12 @@ #include "starboard/common/semaphore.h" #include "starboard/common/string.h" #include "starboard/common/thread.h" +#include "starboard/common/time.h" #include "starboard/shared/uwp/app_accessors.h" #include "starboard/shared/uwp/application_uwp.h" #include "starboard/shared/uwp/async_utils.h" #include "starboard/shared/win32/error_utils.h" #include "starboard/shared/win32/wchar_utils.h" -#include "starboard/time.h" using concurrency::task_continuation_context; using Microsoft::WRL::ComPtr; @@ -87,7 +87,7 @@ const int kMicGain = 1; // before it signals a read error. Without this trigger, the app // will continuously wait for audio data. This happens with the Kinect // device, which when disconnected will still record 0-value samples. -const SbTime kTimeMutedThreshold = 3 * kSbTimeSecond; +const int64_t kTimeMutedThresholdUsec = 3'000'000; // 3 seconds. // Maps [-1.0f, 1.0f] -> [-32768, 32767] // Values outside of [-1.0f, 1.0] are clamped. @@ -185,7 +185,7 @@ AudioGraph ^ AudioGraph ^ graph) { std::vector output; - SbTime start_time = SbTimeGetMonotonicNow(); + int64_t start_time = starboard::CurrentMonotonicTime(); bool had_permissions_error = false; for (DeviceInformation ^ mic : microphone_devices) { @@ -215,8 +215,8 @@ AudioGraph ^ output.push_back(input_node); } - SbTime delta_time = SbTimeGetMonotonicNow() - start_time; - const bool had_ui_interaction = delta_time > (kSbTimeMillisecond * 250); + int64_t delta_time = starboard::CurrentMonotonicTime() - start_time; + const bool had_ui_interaction = delta_time > 250'000; // We only care to retry permissions if there were // 1. No microphones that could be opened. @@ -274,23 +274,23 @@ class MutedTrigger { return; } state_ = kIsMuted; - time_start_ = SbTimeGetMonotonicNow(); + time_start_ = starboard::CurrentMonotonicTime(); } void SignalSound() { state_ = kFoundSound; } - bool IsMuted(SbTimeMonotonic duration_threshold) const { + bool IsMuted(int64_t duration_threshold) const { if (state_ != kIsMuted) { return false; } - SbTimeMonotonic duration = SbTimeGetMonotonicNow() - time_start_; + int64_t duration = starboard::CurrentMonotonicTime() - time_start_; return duration > duration_threshold; } private: enum State { kInitialized, kIsMuted, kFoundSound }; State state_ = kInitialized; - SbTimeMonotonic time_start_ = 0; + int64_t time_start_ = 0; }; // MicrophoneProcessor encapsulates Microsoft's audio api. All available @@ -334,7 +334,7 @@ class MicrophoneProcessor : public starboard::Thread { // was a read error. int Read(int16_t* out_audio_data, size_t out_audio_count) { ScopedLock lock(mutex_); - if (muted_timer_.IsMuted(kTimeMutedThreshold)) { + if (muted_timer_.IsMuted(kTimeMutedThresholdUsec)) { return -1; } diff --git a/starboard/shared/uwp/wasapi_audio_sink.cc b/starboard/shared/uwp/wasapi_audio_sink.cc index d8f5990b572e..4a6a6b0900e2 100644 --- a/starboard/shared/uwp/wasapi_audio_sink.cc +++ b/starboard/shared/uwp/wasapi_audio_sink.cc @@ -226,7 +226,7 @@ double WASAPIAudioSink::GetCurrentPlaybackTime(uint64_t* updated_at) { return (static_cast(pos) / static_cast(audio_clock_frequency_)) * - kSbTimeSecond; + 1'000'000; } void WASAPIAudioSink::OutputFrames() { @@ -240,7 +240,7 @@ void WASAPIAudioSink::OutputFrames() { int frames_copied = 0; uint32_t frames_in_client_buffer = 0; - SbTime output_frames_job_delay = 5 * kSbTimeMillisecond; + int64_t output_frames_job_delay_usec = 5'000; // 5ms HRESULT hr = audio_client_->GetCurrentPadding(&frames_in_client_buffer); CHECK_HRESULT_OK(hr); int frames_available = static_cast(client_buffer_size_in_frames_) - @@ -267,13 +267,13 @@ void WASAPIAudioSink::OutputFrames() { hr = render_client_->ReleaseBuffer(frames_copied, 0 /* dwFlags */); CHECK_HRESULT_OK(hr); - output_frames_job_delay = 0; + output_frames_job_delay_usec = 0; } if (!pending_decoded_audios_.empty()) { job_thread_->job_queue()->Schedule( std::bind(&WASAPIAudioSink::OutputFrames, this), - output_frames_job_delay); + output_frames_job_delay_usec); } } diff --git a/starboard/shared/uwp/wasapi_audio_sink.h b/starboard/shared/uwp/wasapi_audio_sink.h index 3d94f5329bb6..6b14f8f28c0e 100644 --- a/starboard/shared/uwp/wasapi_audio_sink.h +++ b/starboard/shared/uwp/wasapi_audio_sink.h @@ -31,7 +31,6 @@ #include "starboard/shared/starboard/player/job_thread.h" #include "starboard/shared/starboard/thread_checker.h" #include "starboard/shared/win32/wasapi_include.h" -#include "starboard/time.h" namespace starboard { namespace shared { diff --git a/starboard/shared/uwp/watchdog_log.cc b/starboard/shared/uwp/watchdog_log.cc index a7c1711fa7e6..270d4643d55e 100644 --- a/starboard/shared/uwp/watchdog_log.cc +++ b/starboard/shared/uwp/watchdog_log.cc @@ -43,7 +43,7 @@ class WatchDogThread : public Thread { ~WatchDogThread() { Join(); } void Run() override { - static const SbTime kSleepTime = kSbTimeMillisecond * 250; + static const int64_t kSleepTime = 250'000; // 250ms int counter = 0; bool created_ok = false; SbFileError out_error = kSbFileOk; @@ -68,7 +68,7 @@ class WatchDogThread : public Thread { SbFileWrite(file_handle, kDone, static_cast(strlen(kDone))); RecordFileWriteStat(result); SbFileFlush(file_handle); - SbThreadSleep(50 * kSbTimeMillisecond); + SbThreadSleep(50'000); bool closed = SbFileClose(file_handle); SB_LOG_IF(ERROR, closed) << "Could not close file " << file_path_; } diff --git a/starboard/shared/uwp/window_internal.h b/starboard/shared/uwp/window_internal.h index 374ab04a5428..46a8a7d1468d 100644 --- a/starboard/shared/uwp/window_internal.h +++ b/starboard/shared/uwp/window_internal.h @@ -18,7 +18,6 @@ #include #include "starboard/atomic.h" -#include "starboard/time.h" #include "starboard/window.h" struct SbWindowPrivate { diff --git a/starboard/shared/widevine/drm_system_widevine.cc b/starboard/shared/widevine/drm_system_widevine.cc index d321c3459a69..701d5a2f291e 100644 --- a/starboard/shared/widevine/drm_system_widevine.cc +++ b/starboard/shared/widevine/drm_system_widevine.cc @@ -30,7 +30,6 @@ #include "starboard/shared/starboard/media/mime_type.h" #include "starboard/shared/widevine/widevine_storage.h" #include "starboard/shared/widevine/widevine_timer.h" -#include "starboard/time.h" #include "third_party/internal/ce_cdm/core/include/log.h" // for wvcdm::InitLogging(); #include "third_party/internal/ce_cdm/core/include/string_conversions.h" @@ -48,7 +47,7 @@ const char kWidevineStorageFileName[] = "wvcdm.dat"; // Key usage may be blocked due to incomplete HDCP authentication which could // take up to 5 seconds. For such a case it is good to give a try few times to // get HDCP authentication complete. We set a timeout of 6 seconds for retries. -const SbTimeMonotonic kUnblockKeyRetryTimeout = kSbTimeSecond * 6; +const int64_t kUnblockKeyRetryTimeoutUsec = 6'000'000; DECLARE_INSTANCE_COUNTER(DrmSystemWidevine); @@ -500,11 +499,11 @@ SbDrmSystemPrivate::DecryptStatus DrmSystemWidevine::Decrypt( { ScopedLock lock(unblock_key_retry_mutex_); if (!unblock_key_retry_start_time_) { - unblock_key_retry_start_time_ = SbTimeGetMonotonicNow(); + unblock_key_retry_start_time_ = CurrentMonotonicTime(); } } - if (SbTimeGetMonotonicNow() - unblock_key_retry_start_time_.value() < - kUnblockKeyRetryTimeout) { + if (CurrentMonotonicTime() - unblock_key_retry_start_time_.value() < + kUnblockKeyRetryTimeoutUsec) { return kRetry; } } diff --git a/starboard/shared/widevine/drm_system_widevine.h b/starboard/shared/widevine/drm_system_widevine.h index 6a9d28620437..a3a907e2e2de 100644 --- a/starboard/shared/widevine/drm_system_widevine.h +++ b/starboard/shared/widevine/drm_system_widevine.h @@ -192,7 +192,7 @@ class DrmSystemWidevine : public SbDrmSystemPrivate, volatile bool quitting_ = false; Mutex unblock_key_retry_mutex_; - optional unblock_key_retry_start_time_; + optional unblock_key_retry_start_time_; #if !defined(COBALT_BUILD_TYPE_GOLD) int number_of_session_updates_sent_ = 0; diff --git a/starboard/shared/widevine/widevine_timer.cc b/starboard/shared/widevine/widevine_timer.cc index b949e88765e6..3b84ab1dbf0a 100644 --- a/starboard/shared/widevine/widevine_timer.cc +++ b/starboard/shared/widevine/widevine_timer.cc @@ -15,7 +15,6 @@ #include "starboard/shared/widevine/widevine_timer.h" #include "starboard/common/log.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -62,7 +61,7 @@ void WidevineTimer::setTimeout(int64_t delay_in_milliseconds, } iter->second->Schedule([=]() { client->onTimerExpired(context); }, - delay_in_milliseconds * kSbTimeMillisecond); + delay_in_milliseconds * 1000); } void WidevineTimer::cancel(IClient* client) { diff --git a/starboard/shared/win32/application_win32.cc b/starboard/shared/win32/application_win32.cc index f729a751ef8c..0e337f06d48b 100644 --- a/starboard/shared/win32/application_win32.cc +++ b/starboard/shared/win32/application_win32.cc @@ -203,7 +203,7 @@ bool ApplicationWin32::OnSbSystemRaisePlatformError( } Application::Event* ApplicationWin32::WaitForSystemEventWithTimeout( - SbTime time) { + int64_t time) { ProcessNextSystemMessage(); if (pending_event_) { Event* out = pending_event_; @@ -212,7 +212,7 @@ Application::Event* ApplicationWin32::WaitForSystemEventWithTimeout( } ScopedLock lock(stop_waiting_for_system_events_mutex_); - if (time <= SbTimeGetMonotonicNow() || stop_waiting_for_system_events_) { + if (time <= CurrentMonotonicTime() || stop_waiting_for_system_events_) { stop_waiting_for_system_events_ = false; return nullptr; } diff --git a/starboard/shared/win32/application_win32.h b/starboard/shared/win32/application_win32.h index 7ea6a666306a..52955d044c71 100644 --- a/starboard/shared/win32/application_win32.h +++ b/starboard/shared/win32/application_win32.h @@ -23,6 +23,7 @@ #include #include "starboard/common/mutex.h" +#include "starboard/common/time.h" #include "starboard/shared/starboard/application.h" #include "starboard/shared/starboard/localized_strings.h" #include "starboard/shared/starboard/queue_application.h" @@ -52,7 +53,7 @@ class ApplicationWin32 : public starboard::QueueApplication { bool DestroyWindow(SbWindow window); - void DispatchStart(SbTimeMonotonic timestamp) { + void DispatchStart(int64_t timestamp) { shared::starboard::Application::DispatchStart(timestamp); } @@ -71,10 +72,11 @@ class ApplicationWin32 : public starboard::QueueApplication { // Returns true if it is valid to poll/query for system events. bool MayHaveSystemEvents() override { return true; } - // Waits for an event until the timeout |time| runs out. If an event occurs - // in this time, it is returned, otherwise NULL is returned. If |time| is zero - // or negative, then this should function effectively like a no-wait poll. - Event* WaitForSystemEventWithTimeout(SbTime time) override; + // Waits for an event until the timeout |time| runs out (in microseconds). If + // an event occurs in this time, it is returned, otherwise NULL is returned. + // If |time| is zero or negative, then this should function effectively like a + // no-wait poll. + Event* WaitForSystemEventWithTimeout(int64_t time) override; // Wakes up any thread waiting within a call to // WaitForSystemEventWithTimeout(). @@ -96,8 +98,8 @@ class ApplicationWin32 : public starboard::QueueApplication { void Teardown() override {} void ProcessNextSystemMessage(); - SbTimeMonotonic GetNextTimedEventTargetTime() override { - return SbTimeGetMonotonicNow(); + int64_t GetNextTimedEventTargetTime() override { + return CurrentMonotonicTime(); } // Processes window key events, returning a corresponding Event instance. diff --git a/starboard/shared/win32/audio_decoder_thread.cc b/starboard/shared/win32/audio_decoder_thread.cc index 02bdb6b47361..f1bd9497fd6b 100644 --- a/starboard/shared/win32/audio_decoder_thread.cc +++ b/starboard/shared/win32/audio_decoder_thread.cc @@ -111,7 +111,7 @@ void AudioDecoderThread::Run() { } if (!work_done) { - semaphore_.TakeWait(kSbTimeMillisecond); + semaphore_.TakeWait(1000); } } } diff --git a/starboard/shared/win32/audio_sink.cc b/starboard/shared/win32/audio_sink.cc index 57d38cbe128c..db8e671f758b 100644 --- a/starboard/shared/win32/audio_sink.cc +++ b/starboard/shared/win32/audio_sink.cc @@ -24,12 +24,12 @@ #include "starboard/common/condition_variable.h" #include "starboard/common/log.h" #include "starboard/common/mutex.h" +#include "starboard/common/time.h" #include "starboard/configuration.h" #include "starboard/shared/starboard/audio_sink/audio_sink_internal.h" #include "starboard/shared/starboard/player/job_thread.h" #include "starboard/shared/starboard/thread_checker.h" #include "starboard/thread.h" -#include "starboard/time.h" namespace starboard { namespace shared { @@ -362,7 +362,7 @@ void XAudioAudioSink::Process() { SB_DCHECK(consumed_frames <= std::numeric_limits::max()); int consumed_frames_int = static_cast(consumed_frames); - consume_frames_func_(consumed_frames_int, SbTimeGetMonotonicNow(), context_); + consume_frames_func_(consumed_frames_int, CurrentMonotonicTime(), context_); submitted_frames_ -= consumed_frames_int; samples_played_ = voice_state.SamplesPlayed; queued_buffers_ = voice_state.BuffersQueued; diff --git a/starboard/shared/win32/condition_variable_wait_timed.cc b/starboard/shared/win32/condition_variable_wait_timed.cc index bfa48f578a86..a2192ad1e6a4 100644 --- a/starboard/shared/win32/condition_variable_wait_timed.cc +++ b/starboard/shared/win32/condition_variable_wait_timed.cc @@ -19,12 +19,12 @@ #include "starboard/shared/win32/time_utils.h" #include "starboard/shared/win32/types_internal.h" -using starboard::shared::win32::ConvertSbTimeToMillisRoundUp; +using starboard::shared::win32::ConvertUsecToMillisRoundUp; SbConditionVariableResult SbConditionVariableWaitTimed( SbConditionVariable* condition, SbMutex* mutex, - SbTime timeout) { + int64_t timeout) { if (!condition || !mutex) { return kSbConditionVariableFailed; } @@ -34,7 +34,7 @@ SbConditionVariableResult SbConditionVariableWaitTimed( } bool result = SleepConditionVariableSRW( SB_WIN32_INTERNAL_CONDITION(condition), SB_WIN32_INTERNAL_MUTEX(mutex), - ConvertSbTimeToMillisRoundUp(timeout), 0); + ConvertUsecToMillisRoundUp(timeout), 0); if (timeout == 0) { // Per documentation, "If the |timeout_duration| value is less than diff --git a/starboard/shared/win32/decrypting_decoder.cc b/starboard/shared/win32/decrypting_decoder.cc index 0ef81fa6abbd..19bafa74327d 100644 --- a/starboard/shared/win32/decrypting_decoder.cc +++ b/starboard/shared/win32/decrypting_decoder.cc @@ -148,7 +148,7 @@ bool DecryptingDecoder::TryWriteInputBuffer( int size = input_buffer->size() - bytes_to_skip_in_sample; std::int64_t win32_timestamp = - ConvertToWin32Time(input_buffer->timestamp()); + ConvertUsecToWin32Time(input_buffer->timestamp()); const uint8_t* iv = NULL; int iv_size = 0; const SbDrmSubSampleMapping* subsample_mapping = NULL; diff --git a/starboard/shared/win32/file_get_info.cc b/starboard/shared/win32/file_get_info.cc index eacb6b6f4df5..6a3bff46d956 100644 --- a/starboard/shared/win32/file_get_info.cc +++ b/starboard/shared/win32/file_get_info.cc @@ -43,14 +43,13 @@ bool SbFileGetInfo(SbFile file, SbFileInfo* out_info) { out_info->size = standard_info.EndOfFile.QuadPart; SB_DCHECK(out_info->size >= 0); - using starboard::shared::win32::ConvertFileTimeTicksToSbTime; + using starboard::shared::win32::ConvertFileTimeTicksToUsec; - out_info->creation_time = - ConvertFileTimeTicksToSbTime(basic_info.CreationTime); + out_info->creation_time = ConvertFileTimeTicksToUsec(basic_info.CreationTime); out_info->last_accessed = - ConvertFileTimeTicksToSbTime(basic_info.LastAccessTime); + ConvertFileTimeTicksToUsec(basic_info.LastAccessTime); out_info->last_modified = - ConvertFileTimeTicksToSbTime(basic_info.LastWriteTime); + ConvertFileTimeTicksToUsec(basic_info.LastWriteTime); out_info->is_symbolic_link = false; out_info->is_directory = standard_info.Directory; diff --git a/starboard/shared/win32/file_get_path_info.cc b/starboard/shared/win32/file_get_path_info.cc index 9ed102d9e69a..a0ab3a0b4c45 100644 --- a/starboard/shared/win32/file_get_path_info.cc +++ b/starboard/shared/win32/file_get_path_info.cc @@ -87,14 +87,14 @@ bool SbFileGetPathInfo(const char* path, SbFileInfo* out_info) { attribute_data.nFileSizeLow; SB_DCHECK(out_info->size >= 0); - using starboard::shared::win32::ConvertFileTimeToSbTime; + using starboard::shared::win32::ConvertFileTimeToUsec; out_info->creation_time = - ConvertFileTimeToSbTime(attribute_data.ftCreationTime); + ConvertFileTimeToUsec(attribute_data.ftCreationTime); out_info->last_accessed = - ConvertFileTimeToSbTime(attribute_data.ftLastAccessTime); + ConvertFileTimeToUsec(attribute_data.ftLastAccessTime); out_info->last_modified = - ConvertFileTimeToSbTime(attribute_data.ftLastWriteTime); + ConvertFileTimeToUsec(attribute_data.ftLastWriteTime); out_info->is_symbolic_link = false; out_info->is_directory = diff --git a/starboard/shared/win32/media_common.cc b/starboard/shared/win32/media_common.cc index 1c4a100ea6f5..4fa378dbde20 100644 --- a/starboard/shared/win32/media_common.cc +++ b/starboard/shared/win32/media_common.cc @@ -36,15 +36,15 @@ namespace shared { namespace win32 { // Converts microseconds to 10Mhz (100ns time). -int64_t ConvertToWin32Time(SbTime input) { +int64_t ConvertUsecToWin32Time(int64_t input) { int64_t out = input; out *= 10; return out; } // Convert the other way around. -SbTime ConvertToSbTime(int64_t input) { - SbTime out = input; +int64_t ConvertWin32TimeToUsec(int64_t input) { + int64_t out = input; out /= 10; return out; } diff --git a/starboard/shared/win32/media_common.h b/starboard/shared/win32/media_common.h index 21d1323979da..b689f87d4a32 100644 --- a/starboard/shared/win32/media_common.h +++ b/starboard/shared/win32/media_common.h @@ -51,10 +51,10 @@ using VideoFramePtr = ::starboard::scoped_refptr; using Microsoft::WRL::ComPtr; // Converts microseconds to 10Mhz (100ns time). -int64_t ConvertToWin32Time(SbTime input); +int64_t ConvertUsecToWin32Time(int64_t input); // Convert the other way around. -SbTime ConvertToSbTime(int64_t input); +int64_t ConvertWin32TimeToUsec(int64_t input); std::vector> GetAllOutputMediaTypes(int stream_id, IMFTransform* decoder); diff --git a/starboard/shared/win32/socket_set_tcp_keep_alive.cc b/starboard/shared/win32/socket_set_tcp_keep_alive.cc index 4c2b928c422d..ba88a1905822 100644 --- a/starboard/shared/win32/socket_set_tcp_keep_alive.cc +++ b/starboard/shared/win32/socket_set_tcp_keep_alive.cc @@ -21,7 +21,7 @@ namespace sbwin32 = starboard::shared::win32; -bool SbSocketSetTcpKeepAlive(SbSocket socket, bool value, SbTime period) { +bool SbSocketSetTcpKeepAlive(SbSocket socket, bool value, int64_t period) { bool result = sbwin32::SetBooleanSocketOption( socket, SOL_SOCKET, SO_KEEPALIVE, "SO_KEEPALIVE", value); return result; diff --git a/starboard/shared/win32/socket_waiter_internal.cc b/starboard/shared/win32/socket_waiter_internal.cc index 421685faaf8e..a0a7da438cb2 100644 --- a/starboard/shared/win32/socket_waiter_internal.cc +++ b/starboard/shared/win32/socket_waiter_internal.cc @@ -21,6 +21,7 @@ #include "starboard/common/log.h" #include "starboard/common/optional.h" +#include "starboard/common/time.h" #include "starboard/shared/win32/error_utils.h" #include "starboard/shared/win32/socket_internal.h" #include "starboard/shared/win32/thread_private.h" @@ -280,14 +281,14 @@ void SbSocketWaiterPrivate::Wait() { // We basically wait for the largest amount of time to achieve an indefinite // block. - WaitTimed(kSbTimeMax); + WaitTimed(kSbInt64Max); } -SbSocketWaiterResult SbSocketWaiterPrivate::WaitTimed(SbTime duration) { +SbSocketWaiterResult SbSocketWaiterPrivate::WaitTimed(int64_t duration_usec) { SB_DCHECK(SbThreadIsCurrent(thread_)); - const SbTimeMonotonic start_time = SbTimeGetMonotonicNow(); - int64_t duration_left = duration; + const int64_t start_time = starboard::CurrentMonotonicTime(); + int64_t duration_left = duration_usec; while (true) { // |waitees_| could have been modified in the last loop iteration, so @@ -295,7 +296,7 @@ SbSocketWaiterResult SbSocketWaiterPrivate::WaitTimed(SbTime duration) { const DWORD number_events = static_cast(waitees_.GetHandleArraySize()); - const DWORD millis = sbwin32::ConvertSbTimeToMillisRoundUp(duration_left); + const DWORD millis = sbwin32::ConvertUsecToMillisRoundUp(duration_left); { starboard::ScopedLock lock(unhandled_wakeup_count_mutex_); @@ -395,7 +396,7 @@ SbSocketWaiterResult SbSocketWaiterPrivate::WaitTimed(SbTime duration) { } const int64_t time_elapsed = - static_cast(SbTimeGetMonotonicNow()) - + static_cast(starboard::CurrentMonotonicTime()) - static_cast(start_time); duration_left -= time_elapsed; if (duration_left < 0) { diff --git a/starboard/shared/win32/socket_waiter_internal.h b/starboard/shared/win32/socket_waiter_internal.h index 0420e8676ae9..52d8eda1b1c5 100644 --- a/starboard/shared/win32/socket_waiter_internal.h +++ b/starboard/shared/win32/socket_waiter_internal.h @@ -55,7 +55,7 @@ class SbSocketWaiterPrivate { bool persistent); bool Remove(SbSocket socket); void Wait(); - SbSocketWaiterResult WaitTimed(SbTime duration); + SbSocketWaiterResult WaitTimed(int64_t duration_usec); void WakeUp(); void HandleWakeUpRead(); diff --git a/starboard/shared/win32/socket_waiter_wait_timed.cc b/starboard/shared/win32/socket_waiter_wait_timed.cc index 30bd455f816a..25c266bdc2ce 100644 --- a/starboard/shared/win32/socket_waiter_wait_timed.cc +++ b/starboard/shared/win32/socket_waiter_wait_timed.cc @@ -17,7 +17,7 @@ #include "starboard/shared/win32/socket_waiter_internal.h" SbSocketWaiterResult SbSocketWaiterWaitTimed(SbSocketWaiter waiter, - SbTime duration) { + int64_t duration) { if (!SbSocketWaiterIsValid(waiter)) { return kSbSocketWaiterResultInvalid; } diff --git a/starboard/shared/win32/starboard_main.cc b/starboard/shared/win32/starboard_main.cc index 2027a1c27b86..de504e59344d 100644 --- a/starboard/shared/win32/starboard_main.cc +++ b/starboard/shared/win32/starboard_main.cc @@ -40,12 +40,12 @@ namespace { void WaitForNetLogIfNecessary(const CommandLine& cmd_line) { if (cmd_line.HasSwitch(kNetLogCommandSwitchWait)) { - SbTime timeout = kSbTimeSecond * 2; + int64_t timeout_usec = 2'000'000; // 2 seconds. std::string val = cmd_line.GetSwitchValue(kNetLogCommandSwitchWait); if (!val.empty()) { - timeout = atoi(val.c_str()); + timeout_usec = atoi(val.c_str()); } - NetLogWaitForClientConnected(timeout); + NetLogWaitForClientConnected(timeout_usec); } } diff --git a/starboard/shared/win32/thread_sleep.cc b/starboard/shared/win32/thread_sleep.cc index b68067b01cae..1e19a368e072 100644 --- a/starboard/shared/win32/thread_sleep.cc +++ b/starboard/shared/win32/thread_sleep.cc @@ -18,11 +18,11 @@ #include "starboard/shared/win32/time_utils.h" -using starboard::shared::win32::ConvertSbTimeToMillisRoundUp; +using starboard::shared::win32::ConvertUsecToMillisRoundUp; -void SbThreadSleep(SbTime duration) { +void SbThreadSleep(int64_t duration) { if (duration < 0) { return; } - Sleep(ConvertSbTimeToMillisRoundUp(duration)); + Sleep(ConvertUsecToMillisRoundUp(duration)); } diff --git a/starboard/shared/win32/time_get_monotonic_now.cc b/starboard/shared/win32/time_get_monotonic_now.cc index bfa43f456b34..6cc71b3dd9d9 100644 --- a/starboard/shared/win32/time_get_monotonic_now.cc +++ b/starboard/shared/win32/time_get_monotonic_now.cc @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if SB_API_VERSION < 16 + #include "starboard/time.h" #include @@ -45,3 +47,5 @@ SbTimeMonotonic SbTimeGetMonotonicNow() { return static_cast(result); } + +#endif // SB_API_VERSION < 16 diff --git a/starboard/shared/win32/time_get_now.cc b/starboard/shared/win32/time_get_now.cc index 806f78e623da..a9ab54efb2b8 100644 --- a/starboard/shared/win32/time_get_now.cc +++ b/starboard/shared/win32/time_get_now.cc @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#if SB_API_VERSION < 16 + #include "starboard/time.h" #include @@ -28,3 +30,5 @@ SbTime SbTimeGetNow() { large_int.HighPart = file_time.dwHighDateTime; return static_cast(large_int.QuadPart) / 10; } + +#endif // SB_API_VERSION < 16 diff --git a/starboard/shared/win32/time_utils.h b/starboard/shared/win32/time_utils.h index b88388b3ad5a..584fcfbd3979 100644 --- a/starboard/shared/win32/time_utils.h +++ b/starboard/shared/win32/time_utils.h @@ -21,7 +21,7 @@ namespace starboard { namespace shared { namespace win32 { -inline SbTime ConvertFileTimeTicksToSbTime(const LARGE_INTEGER ticks) { +inline int64_t ConvertFileTimeTicksToUsec(const LARGE_INTEGER ticks) { // According to // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284(v=vs.85).aspx // FILETIME format is "Contains a 64-bit value representing the number of @@ -30,7 +30,7 @@ inline SbTime ConvertFileTimeTicksToSbTime(const LARGE_INTEGER ticks) { return ticks.QuadPart / kNumber100nanosecondTicksInMicrosecond; } -inline SbTime ConvertFileTimeToSbTime(const FILETIME file_time) { +inline int64_t ConvertFileTimeToUsec(const FILETIME file_time) { // According to // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284(v=vs.85).aspx // FILETIME format is "Contains a 64-bit value representing the number of @@ -38,21 +38,14 @@ inline SbTime ConvertFileTimeToSbTime(const FILETIME file_time) { LARGE_INTEGER ticks; ticks.QuadPart = (static_cast(file_time.dwHighDateTime) << 32) | file_time.dwLowDateTime; - return ConvertFileTimeTicksToSbTime(ticks); + return ConvertFileTimeTicksToUsec(ticks); } -inline SbTime ConvertSystemTimeToSbTime(const SYSTEMTIME system_time) { - FILETIME file_time = {0}; - SystemTimeToFileTime(&system_time, &file_time); - return ConvertFileTimeToSbTime(file_time); -} - -// Many Win32 calls take millis, but SbTime is microseconds. +// Many Win32 calls take millis, but Starboard uses microseconds. // Many nplb tests assume waits are at least as long as requested, so // round up. -inline DWORD ConvertSbTimeToMillisRoundUp(SbTime duration) { - const int64_t milliseconds_to_sleep = - (duration + kSbTimeMillisecond - 1) / kSbTimeMillisecond; +inline DWORD ConvertUsecToMillisRoundUp(int64_t duration_usec) { + const int64_t milliseconds_to_sleep = (duration_usec + 1000 - 1) / 1000; return static_cast(milliseconds_to_sleep); } diff --git a/starboard/shared/win32/video_decoder.cc b/starboard/shared/win32/video_decoder.cc index f8890195d88b..5734b3724d90 100644 --- a/starboard/shared/win32/video_decoder.cc +++ b/starboard/shared/win32/video_decoder.cc @@ -20,7 +20,6 @@ #include "starboard/shared/win32/dx_context_video_decoder.h" #include "starboard/shared/win32/error_utils.h" #include "starboard/shared/win32/hardware_decode_target_internal.h" -#include "starboard/time.h" // Include this after all other headers to avoid introducing redundant // definitions from other header files. @@ -167,7 +166,7 @@ scoped_ptr CreateVideoTransform( class VideoFrameImpl : public VideoFrame { public: - VideoFrameImpl(SbTime timestamp, std::function release_cb) + VideoFrameImpl(int64_t timestamp, std::function release_cb) : VideoFrame(timestamp), release_cb_(release_cb) { SB_DCHECK(release_cb_); } @@ -535,7 +534,7 @@ void VideoDecoder::ShutdownCodec() { // Microsoft recommends stalling to let other systems release their // references to the IMFSamples. if (video_codec_ == kSbMediaVideoCodecVp9) { - SbThreadSleep(150 * kSbTimeMillisecond); + SbThreadSleep(150'000); } decoder_.reset(); video_processor_.Reset(); @@ -624,7 +623,7 @@ scoped_refptr VideoDecoder::CreateVideoFrame( // weak references to the actual sample. LONGLONG win32_sample_time = 0; CheckResult(sample->GetSampleTime(&win32_sample_time)); - SbTime sample_time = ConvertToSbTime(win32_sample_time); + int64_t sample_time = ConvertWin32TimeToUsec(win32_sample_time); thread_lock_.Acquire(); thread_outputs_.emplace_back(sample_time, video_area_, sample); @@ -667,7 +666,7 @@ void VideoDecoder::DecoderThreadRun() { } if (event == nullptr) { - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); } else { switch (event->type) { case Event::kWriteInputBuffer: @@ -772,7 +771,7 @@ void VideoDecoder::DecoderThreadRun() { if (!wrote_input && !read_output) { // Throttle decode loop since no I/O was possible. - SbThreadSleep(kSbTimeMillisecond); + SbThreadSleep(1000); } } } diff --git a/starboard/shared/win32/video_decoder.h b/starboard/shared/win32/video_decoder.h index 8457a23bb6c5..f13ad2d789d7 100644 --- a/starboard/shared/win32/video_decoder.h +++ b/starboard/shared/win32/video_decoder.h @@ -58,7 +58,7 @@ class VideoDecoder void Initialize(const DecoderStatusCB& decoder_status_cb, const ErrorCB& error_cb) override; size_t GetPrerollFrameCount() const override; - SbTime GetPrerollTimeout() const override { return kSbTimeMax; } + int64_t GetPrerollTimeout() const override { return kSbInt64Max; } size_t GetMaxNumberOfCachedFrames() const override; void WriteInputBuffers(const InputBuffers& input_buffers) override; @@ -83,11 +83,11 @@ class VideoDecoder }; struct Output { - Output(SbTime time, + Output(int64_t time, const RECT& video_area, const ComPtr& video_sample) : time(time), video_area(video_area), video_sample(video_sample) {} - SbTime time; + int64_t time; RECT video_area; ComPtr video_sample; }; diff --git a/starboard/shared/win32/win32_audio_decoder.cc b/starboard/shared/win32/win32_audio_decoder.cc index 84d526abf08c..8ff8c0400e25 100644 --- a/starboard/shared/win32/win32_audio_decoder.cc +++ b/starboard/shared/win32/win32_audio_decoder.cc @@ -129,9 +129,10 @@ class AbstractWin32AudioDecoderImpl : public AbstractWin32AudioDecoder { SB_DCHECK(decoded_data_size == kEac3BufferSize); } - DecodedAudioPtr data_ptr(new DecodedAudio( - number_of_channels_, sample_type_, audio_frame_fmt_, - ConvertToSbTime(win32_timestamp), static_cast(decoded_data_size))); + DecodedAudioPtr data_ptr( + new DecodedAudio(number_of_channels_, sample_type_, audio_frame_fmt_, + ConvertWin32TimeToUsec(win32_timestamp), + static_cast(decoded_data_size))); std::copy(data, data + data_size, data_ptr->data()); std::memset(data_ptr->data() + data_size, 0, decoded_data_size - data_size); diff --git a/starboard/shared/win32/window_internal.h b/starboard/shared/win32/window_internal.h index 10e6cfb82cc6..2feb933d4fb8 100644 --- a/starboard/shared/win32/window_internal.h +++ b/starboard/shared/win32/window_internal.h @@ -21,7 +21,6 @@ #include #include "starboard/atomic.h" -#include "starboard/time.h" #include "starboard/window.h" struct SbWindowPrivate { diff --git a/starboard/shared/x11/application_x11.cc b/starboard/shared/x11/application_x11.cc index f01590e641d2..7deca2419392 100644 --- a/starboard/shared/x11/application_x11.cc +++ b/starboard/shared/x11/application_x11.cc @@ -36,11 +36,9 @@ #include "starboard/key.h" #include "starboard/player.h" #include "starboard/shared/linux/system_network_status.h" -#include "starboard/shared/posix/time_internal.h" #include "starboard/shared/starboard/audio_sink/audio_sink_internal.h" #include "starboard/shared/starboard/player/filter/cpu_video_frame.h" #include "starboard/shared/x11/window_internal.h" -#include "starboard/time.h" namespace { const char kTouchscreenPointerSwitch[] = "touchscreen_pointer"; @@ -805,7 +803,7 @@ void ApplicationX11::Composite() { } } composite_event_id_ = - SbEventSchedule(&CompositeCallback, this, kSbTimeSecond / 60); + SbEventSchedule(&CompositeCallback, this, 1'000'000 / 60); } void ApplicationX11::AcceptFrame(SbPlayer player, @@ -911,7 +909,7 @@ bool ApplicationX11::MayHaveSystemEvents() { } shared::starboard::Application::Event* -ApplicationX11::WaitForSystemEventWithTimeout(SbTime time) { +ApplicationX11::WaitForSystemEventWithTimeout(int64_t time) { SB_DCHECK(display_); shared::starboard::Application::Event* pending_event = GetPendingEvent(); diff --git a/starboard/shared/x11/application_x11.h b/starboard/shared/x11/application_x11.h index 94596c0972fc..4355f1fb1fca 100644 --- a/starboard/shared/x11/application_x11.h +++ b/starboard/shared/x11/application_x11.h @@ -91,7 +91,7 @@ class ApplicationX11 : public shared::starboard::QueueApplication { // --- QueueApplication overrides --- bool MayHaveSystemEvents() override; - Event* WaitForSystemEventWithTimeout(SbTime time) override; + Event* WaitForSystemEventWithTimeout(int64_t time) override; void WakeSystemEventWait() override; private: diff --git a/starboard/socket.h b/starboard/socket.h index adcd32b3c072..18c0ae0577a1 100644 --- a/starboard/socket.h +++ b/starboard/socket.h @@ -34,7 +34,6 @@ #define STARBOARD_SOCKET_H_ #include "starboard/export.h" -#include "starboard/time.h" #include "starboard/types.h" #ifdef __cplusplus @@ -356,14 +355,14 @@ SB_EXPORT bool SbSocketSetSendBufferSize(SbSocket socket, int32_t size); // return value indicates whether the option was actually set. // // |socket|: The SbSocket for which the option is set. -// |value|: If set to |true|, then |period| specifies the minimum time -// (SbTime) is always in microseconds) between keep-alive packets. If -// set to |false|, |period| is ignored. -// |period|: The time between keep-alive packets. This value is only relevant -// if |value| is |true|. +// |value|: If set to |true|, then |period| specifies the minimum time in +// microseconds between keep-alive packets. If set to |false|, |period| +// is ignored. +// |period|: The time in microseconds between keep-alive packets. This value +// is only relevant if |value| is |true|. SB_EXPORT bool SbSocketSetTcpKeepAlive(SbSocket socket, bool value, - SbTime period); + int64_t period); // Sets the |TCP_NODELAY|, or equivalent, option to |value| on |socket|. The // return value indicates whether the option was actually set. diff --git a/starboard/socket_waiter.h b/starboard/socket_waiter.h index 18bbfbd9879c..eb69317b36b0 100644 --- a/starboard/socket_waiter.h +++ b/starboard/socket_waiter.h @@ -36,7 +36,6 @@ #include "starboard/export.h" #include "starboard/socket.h" -#include "starboard/time.h" #include "starboard/types.h" #ifdef __cplusplus @@ -164,12 +163,12 @@ SB_EXPORT void SbSocketWaiterWait(SbSocketWaiter waiter); // The return value indicates the reason that the socket waiter exited. // This function should only be called on the thread that waits on this waiter. // -// |duration|: The minimum amount of time after which the socket waiter should -// exit if it is not woken up before then. As with SbThreadSleep() (see -// thread.h), this function may wait longer than |duration|, such as if the -// timeout expires while a callback is being fired. +// |duration|: The minimum amount of time in microseconds after which the socket +// waiter should exit if it is not woken up before then. As with +// SbThreadSleep() (see thread.h), this function may wait longer than +// |duration|, such as if the timeout expires while a callback is being fired. SB_EXPORT SbSocketWaiterResult SbSocketWaiterWaitTimed(SbSocketWaiter waiter, - SbTime duration); + int64_t duration); // Wakes up |waiter| once. This is the only thread-safe waiter function. // It can can be called from a SbSocketWaiterCallback to wake up its own waiter, diff --git a/starboard/stub/application_stub.cc b/starboard/stub/application_stub.cc index 2c07105f8b8a..7aeb224b092c 100644 --- a/starboard/stub/application_stub.cc +++ b/starboard/stub/application_stub.cc @@ -42,7 +42,7 @@ shared::starboard::Application::Event* ApplicationStub::PollNextSystemEvent() { } shared::starboard::Application::Event* -ApplicationStub::WaitForSystemEventWithTimeout(SbTime time) { +ApplicationStub::WaitForSystemEventWithTimeout(int64_t time) { return NULL; } diff --git a/starboard/stub/application_stub.h b/starboard/stub/application_stub.h index 6f5a8180c0dc..72a8cd2ade70 100644 --- a/starboard/stub/application_stub.h +++ b/starboard/stub/application_stub.h @@ -47,7 +47,7 @@ class ApplicationStub : public shared::starboard::QueueApplication { // --- QueueApplication overrides --- bool MayHaveSystemEvents() override; Event* PollNextSystemEvent() override; - Event* WaitForSystemEventWithTimeout(SbTime time) override; + Event* WaitForSystemEventWithTimeout(int64_t time) override; void WakeSystemEventWait() override; }; diff --git a/starboard/thread.h b/starboard/thread.h index bf5c81dac976..7327f7fbcc6c 100644 --- a/starboard/thread.h +++ b/starboard/thread.h @@ -21,7 +21,6 @@ #include "starboard/configuration.h" #include "starboard/export.h" -#include "starboard/time.h" #include "starboard/types.h" #ifdef __cplusplus @@ -199,7 +198,7 @@ SB_EXPORT void SbThreadYield(); // |duration|: The minimum amount of time, in microseconds, that the currently // executing thread should sleep. The function is a no-op if this value is // negative or |0|. -SB_EXPORT void SbThreadSleep(SbTime duration); +SB_EXPORT void SbThreadSleep(int64_t duration); // Returns the handle of the currently executing thread. SB_EXPORT SbThread SbThreadGetCurrent(); diff --git a/starboard/time.h b/starboard/time.h index afb8cfe5d11a..ab5c0bf66a88 100644 --- a/starboard/time.h +++ b/starboard/time.h @@ -19,6 +19,8 @@ #ifndef STARBOARD_TIME_H_ #define STARBOARD_TIME_H_ +#if SB_API_VERSION < 16 + #include "starboard/export.h" #include "starboard/types.h" @@ -91,8 +93,6 @@ SB_EXPORT SbTime SbTimeGetNow(); // Gets a monotonically increasing time representing right now. SB_EXPORT SbTimeMonotonic SbTimeGetMonotonicNow(); -#if SB_API_VERSION < 16 - // Returns whether the current platform supports time thread now SB_EXPORT bool SbTimeIsTimeThreadNowSupported(); @@ -103,10 +103,14 @@ SB_EXPORT bool SbTimeIsTimeThreadNowSupported(); // available then SbTimeGetMonotonicNow() should be used. SB_EXPORT SbTimeMonotonic SbTimeGetMonotonicThreadNow(); -#endif // SB_API_VERSION < 16 - #ifdef __cplusplus } // extern "C" #endif +#else // SB_API_VERSION < 16 + +#error This file is deprecated with SB_API_VERSION 16. + +#endif // SB_API_VERSION < 16 + #endif // STARBOARD_TIME_H_ diff --git a/starboard/user.h b/starboard/user.h index e04761442c71..378b04a558dc 100644 --- a/starboard/user.h +++ b/starboard/user.h @@ -28,7 +28,6 @@ #if SB_API_VERSION < 16 #include "starboard/export.h" -#include "starboard/time.h" #include "starboard/types.h" #ifdef __cplusplus diff --git a/starboard/xb1/shared/gpu_base_video_decoder.cc b/starboard/xb1/shared/gpu_base_video_decoder.cc index 84bab910f24a..e5b0308a2d2d 100644 --- a/starboard/xb1/shared/gpu_base_video_decoder.cc +++ b/starboard/xb1/shared/gpu_base_video_decoder.cc @@ -209,7 +209,7 @@ class GpuVideoDecoderBase::GPUDecodeTargetPrivate } } - SbTime timestamp() { return image_->timestamp(); } + int64_t timestamp() { return image_->timestamp(); } void ReleaseImage() { // Release the codec resource, while the D3D textures are still safe to use. @@ -551,7 +551,7 @@ int GpuVideoDecoderBase::OnOutputRetrieved( return 0; } - SbTime timestamp = image->timestamp(); + int64_t timestamp = image->timestamp(); { ScopedLock input_queue_lock(written_inputs_mutex_); const auto iter = FindByTimestamp(written_inputs_, timestamp); @@ -666,8 +666,7 @@ void GpuVideoDecoderBase::DecodeEndOfStream() { ScopedLock pending_inputs_lock(pending_inputs_mutex_); if (!pending_inputs_.empty()) { decoder_thread_->job_queue()->Schedule( - std::bind(&GpuVideoDecoderBase::DecodeEndOfStream, this), - kSbTimeMillisecond); + std::bind(&GpuVideoDecoderBase::DecodeEndOfStream, this), 1000); return; } } @@ -781,7 +780,7 @@ GpuVideoDecoderBase::GetAvailableFrameBuffer(uint16_t width, uint16_t height) { return nullptr; } is_resetting = decoder_behavior_.load() == kResettingDecoder; - frame_buffers_condition_.WaitTimed(50 * kSbTimeMillisecond); + frame_buffers_condition_.WaitTimed(50'000); // 50ms continue; } } diff --git a/starboard/xb1/shared/gpu_base_video_decoder.h b/starboard/xb1/shared/gpu_base_video_decoder.h index 34d45338813d..b93cd0fec79d 100644 --- a/starboard/xb1/shared/gpu_base_video_decoder.h +++ b/starboard/xb1/shared/gpu_base_video_decoder.h @@ -131,7 +131,7 @@ class GpuVideoDecoderBase SB_DCHECK(index < kNumberOfPlanes); return strides_[index]; } - SbTime timestamp() const { return timestamp_; } + int64_t timestamp() const { return timestamp_; } const SbMediaColorMetadata& color_metadata() const { return color_metadata_; } @@ -152,7 +152,7 @@ class GpuVideoDecoderBase int texture_corner_top_[kNumberOfPlanes]; Microsoft::WRL::ComPtr textures_[kNumberOfPlanes]; int strides_[kNumberOfPlanes]; - SbTime timestamp_; + int64_t timestamp_; // microseconds SbMediaColorMetadata color_metadata_; const std::function release_cb_; }; @@ -178,7 +178,7 @@ class GpuVideoDecoderBase void Initialize(const DecoderStatusCB& decoder_status_cb, const ErrorCB& error_cb) final; size_t GetPrerollFrameCount() const final; - SbTime GetPrerollTimeout() const final { return kSbTimeMax; } + int64_t GetPrerollTimeout() const final { return kSbInt64Max; } size_t GetMaxNumberOfCachedFrames() const override; void WriteInputBuffers(const InputBuffers& input_buffers) final; diff --git a/starboard/xb1/shared/video_frame_impl.h b/starboard/xb1/shared/video_frame_impl.h index 0f31ff2ed5f2..6440d28654fa 100644 --- a/starboard/xb1/shared/video_frame_impl.h +++ b/starboard/xb1/shared/video_frame_impl.h @@ -29,7 +29,7 @@ class VideoFrameImpl public: typedef ::starboard::shared::starboard::player::filter::VideoFrame VideoFrame; - VideoFrameImpl(SbTime timestamp, std::function release_cb) + VideoFrameImpl(int64_t timestamp, std::function release_cb) : VideoFrame(timestamp), release_cb_(release_cb) { SB_DCHECK(release_cb_); } diff --git a/third_party/v8/src/base/platform/platform-starboard.cc b/third_party/v8/src/base/platform/platform-starboard.cc index a524f7fb299a..e0913a26e668 100644 --- a/third_party/v8/src/base/platform/platform-starboard.cc +++ b/third_party/v8/src/base/platform/platform-starboard.cc @@ -22,7 +22,6 @@ #include "starboard/configuration.h" #include "starboard/configuration_constants.h" #include "starboard/memory.h" -#include "starboard/time.h" #include "starboard/time_zone.h" namespace v8 { diff --git a/third_party/v8/src/base/platform/time.cc b/third_party/v8/src/base/platform/time.cc index 29ea7091d759..476821a9a0e2 100644 --- a/third_party/v8/src/base/platform/time.cc +++ b/third_party/v8/src/base/platform/time.cc @@ -31,7 +31,6 @@ #if V8_OS_STARBOARD #include "starboard/common/time.h" -#include "starboard/time.h" #endif namespace {