Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ public class BannerView extends FrameLayout {
private boolean isBidAdLoaded;
private boolean expired;
private boolean isRefreshStopped;
// Size of the creative currently in the slot, captured when it is displayed. 0 x 0 when unknown.
private int creativeWidth;
private int creativeHeight;

private final ScreenStateReceiver screenStateReceiver = new ScreenStateReceiver();

Expand Down Expand Up @@ -132,6 +135,8 @@ public void onAdDisplayed() {

@Override
public void onAdFailed(AdException exception) {
// The Prebid creative failed to render, so there is no creative size to report.
clearCreativeSize();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A detached Prebid creative can clear the size of the ad on screen. displayViewListener is shared by every DisplayView this banner creates. displayAdServerView() calls removeAllViews() without destroying displayView, and displayPrebidView() only destroys it while it's still a child. So after a Prebid → GAM refresh, the old creative is still alive and wired to this listener. If it reports a failure later (a video error, for example), this line sets the size to 0x0 while GAM's creative is on screen.

It's an edge case, but the fix belongs one level down: destroy and null displayView in displayAdServerView(), the same way displayPrebidView() does. That also stops the detached creative from leaking and from sending callbacks to bannerViewListener.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 835a955. displayAdServerView() now destroys and nulls displayView before removing views, and onAdServerWin_DestroysPreviousPrebidCreative covers it.

if (bannerViewListener != null) {
bannerViewListener.onAdFailed(BannerView.this, exception);
}
Expand Down Expand Up @@ -227,8 +232,20 @@ public void onPrebidSdkWin() {

@Override
public void onAdServerWin(View view) {
onAdServerWin(view, null);
}

@Override
public void onAdServerWin(View view, @Nullable AdSize adSize) {
markPrimaryAdRequestFinished();

// Report the ad server's creative, never the Prebid bid that lost to it.
if (view != null && adSize != null) {
setCreativeSize(adSize.getWidth(), adSize.getHeight());
} else {
clearCreativeSize();
}

notifyAdLoadedListener();
displayAdServerView(view);
}
Expand Down Expand Up @@ -363,6 +380,7 @@ public void destroy() {
displayView.destroy();
}
cancelExpiration();
clearCreativeSize();
bidRequesterListener = null;

PrebidMobilePluginRegister.getInstance().unregisterEventListener(adUnitConfig.getFingerprint());
Expand Down Expand Up @@ -552,6 +570,14 @@ private void displayPrebidView() {

removeAllViews();

// Captured before the creative is created, so it is set by the time onAdLoaded fires.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small doc mismatch. The Javadoc says the value doesn't change until the next creative is displayed, and that a refresh still loading keeps reporting the creative on screen. But on a Prebid win this runs right after removeAllViews() and before the new creative has loaded. So from here until onAdLoaded (or until the creative fails), the getters report the new bid's size for an empty slot.

Reading it in onAdLoaded is fine. I'd either say in the Javadoc that the value is set when a creative starts displaying and is meant to be read from onAdLoaded, or keep the bid size in a pending field and apply it in displayViewListener.onAdLoaded().

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 835a955. displayPrebidView() sets a pending size (and nulls the current one, since the old creative is removed), onAdLoaded() publishes it before notifying the host, and a render failure discards it. The Javadoc says the value describes the creative on screen and is meant to be read from onAdLoaded.

final Bid winnerBid = getWinnerBid();
if (winnerBid != null) {
setCreativeSize(winnerBid.getWidth(), winnerBid.getHeight());
} else {
clearCreativeSize();
}

displayView = new DisplayView(getContext(), displayViewListener, displayVideoListener, adUnitConfig, bidResponse);
if (bidResponse.getPreferredPluginRendererName() == PrebidMobilePluginRegister.PREBID_MOBILE_RENDERER_NAME) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correction to my earlier comment on the plugin-renderer MATCH_PARENT branch: it isn't only plugin renderers. This line compares strings with ==. getPreferredPluginRendererName() returns either null (no rendererName in the bid's meta, the usual case) or a string parsed from JSON, which isn't interned. So in practice every Prebid creative takes the MATCH_PARENT branch, and the bid-sized addView only runs in the new tests, because mockBidResponse returns the interned constant.

This predates the PR, and switching to .equals wouldn't change much in production, since null still falls through. But the new Javadoc ("a third party plugin renderer lays its view out to match this view") implies the default renderer is laid out at the bid size, and the tests exercise a branch production doesn't take. I'd make it PrebidMobilePluginRegister.PREBID_MOBILE_RENDERER_NAME.equals(...), have mockBidResponse return null for the renderer name so the tests follow the real path, and adjust that Javadoc bullet.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 835a955. It now uses PREBID_MOBILE_RENDERER_NAME.equals(...), the test helper returns a null renderer name so tests take the MATCH_PARENT path (asserted in creativeSize_OnPrebidWin_CreativeFillsBannerView), and the Javadoc says the creative fills the view rather than being laid out at the bid size.

final Pair<Integer, Integer> sizePair = bidResponse.getWinningBidWidthHeightPairDips(getContext());
Expand Down Expand Up @@ -657,6 +683,7 @@ private void expireAdIfNeeded() {
displayView = null;
}
removeAllViews();
clearCreativeSize();
}

if (bannerViewListener != null) {
Expand All @@ -672,6 +699,56 @@ public BidResponse getBidResponse() {
return bidResponse;
}

@Nullable
final Bid getWinnerBid() {
return bidResponse != null ? bidResponse.getWinningBid() : null;
}

/**
* Declared width, in dp, of the creative currently displayed by this view. Read it in
* {@link BannerViewListener#onAdLoaded(BannerView)} to learn which of several requested
* sizes won, e.g. 300x250 or 320x50.
* <p>
* The value is captured when a creative is displayed and does not change until the next one
* is displayed, so a refresh that is still loading or that fails keeps reporting the creative
* on screen.
* <ul>
* <li>Prebid win: the winning bid's {@code w}. This is the size the bid declares, not a
* measured one: a third party plugin renderer lays its view out to match this view, and
* MRAID {@code resize()} or {@code expand()} can change the creative after it loads.</li>
* <li>Ad server win: the size the ad server's event handler reports for its creative
* (e.g. the GAM event handler), or 0 when the handler does not report one.</li>
* <li>0 when nothing is displayed: before the first ad, after a creative fails to
* render, after an expired ad is removed, and after {@link #destroy()}.</li>
* </ul>
*/
public int getCreativeWidth() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 means two different things here. It's returned when nothing is displayed, and also when a creative is displayed but its size is unknown. That includes a GAM fluid ad, a handler that doesn't report a size (Next-Gen today, or any custom BannerEventHandler), and a Prebid bid without w/h. Those are optional in OpenRTB and often missing on outstream video in a multiformat banner. A host that follows this Javadoc and sets the slot height to getCreativeHeight() collapses a live ad to 0 dp in all of those cases.

One fix that also simplifies the code: keep a single @Nullable AdSize creativeSize field and expose getCreativeSize(), returning null only when nothing is displayed. Hosts can then tell "no ad" from "ad of unknown size". It replaces the two ints, setCreativeSize/clearCreativeSize and the two set-or-clear blocks, and uses the same AdSize type as addAdditionalSizes() and the new onAdServerWin(View, AdSize). If you'd rather keep the int getters, please at least say in the Javadoc that 0 doesn't mean the slot is empty.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 835a955. There is now a single @Nullable AdSize getCreativeSize(): null only when nothing is displayed, and 0x0 when a creative is displayed but its size is unknown (bid without w/h, fluid or other non-positive size, or no size from the handler). The Javadoc says not to size the slot from 0x0.

return creativeWidth;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When GAM wins, this returns the size of the bid that lost.

onAdServerWin calls notifyAdLoadedListener() (line 207) while bidResponse still holds the Prebid bid from onFetchCompleted. So inside onAdLoaded for a GAM creative these getters describe a creative that was never rendered:

  • Sizes 300x250 + 320x50, Prebid bids 320x50, GAM serves its own 300x250 line item → the host reads 320x50 and shrinks the slot, clipping the GAM creative.
  • Prebid has no bid → onError nulls bidResponse → the getters return 0, which the Javadoc defines as no-fill, even though GAM filled the slot. A host that collapses on 0 hides a served ad.

The PR mentions iOS parity, but iOS doesn't have this gap: the size travels with the view (adServerDidWin(_ view:, adSize:) → bannerView(_:didReceiveAdWithAdSize:)), so the GAM path reports GAM's served size.

Suggested fix (also resolves the staleness comment below): record the size where a view is actually displayed rather than deriving it here — in displayPrebidView() (the bid size is already computed there for addView) and in displayAdServerView() (size from the event handler, e.g. AdManagerAdView.getAdSize(), via an overload or a default method on BannerEventListener), and clear it on failure, expiry and destroy.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 46de0e5. The size is now captured where a view is displayed. BannerEventListener gets a default onAdServerWin(View, AdSize) overload, and GamBannerEventHandler passes AdManagerAdView.getAdSize(), so a GAM win reports GAM's served size. A handler that reports no size (or a fluid one) gives 0 instead of the losing bid's size. NextGen still uses the one-arg call, so it reports 0 for now.


/**
* Declared height, in dp, of the creative currently displayed by this view, or 0 when it is
* unknown. See {@link #getCreativeWidth()} for when the value is captured and cleared.
*/
public int getCreativeHeight() {
return creativeHeight;
}

private void setCreativeSize(int width, int height) {
// A non positive dimension, such as a fluid ad server size, is not a usable size.
if (width <= 0 || height <= 0) {
clearCreativeSize();
return;
}
creativeWidth = width;
creativeHeight = height;
}

private void clearCreativeSize() {
creativeWidth = 0;
creativeHeight = 0;
}

@Nullable
public String getImpOrtbConfig() {
return adUnitConfig.getImpOrtbConfig();
Expand Down Expand Up @@ -706,11 +783,6 @@ final void setBidResponse(BidResponse response) {
bidResponse = response;
}

@VisibleForTesting
final Bid getWinnerBid() {
return bidResponse != null ? bidResponse.getWinningBid() : null;
}

@VisibleForTesting
final boolean isPrimaryAdServerRequestInProgress() {
return isPrimaryAdServerRequestInProgress;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,24 @@
package org.prebid.mobile.rendering.bidding.listeners;

import android.view.View;
import androidx.annotation.Nullable;
import org.prebid.mobile.AdSize;
import org.prebid.mobile.api.exceptions.AdException;

public interface BannerEventListener {
void onPrebidSdkWin();

void onAdServerWin(View view);

/**
* Ad server win that also reports the size of the creative the ad server served, in dp.
* Event handlers that know the served size should call this instead of
* {@link #onAdServerWin(View)}, so the banner can report it. Pass null when the size is unknown.
*/
default void onAdServerWin(View view, @Nullable AdSize adSize) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, but worth considering while this API is new: the two overloads delegate to each other. This default forwards two-arg → one-arg, and BannerView's one-arg override forwards back to two-arg. That works today because BannerView overrides both. But BannerView is the only implementer and event handlers are the callers, so the delegation runs the wrong way. If someone later drops the two-arg override, or writes a wrapper that follows this Javadoc and forwards one-arg → two-arg, it recurses until StackOverflowError. A wrapper that only overrides the one-arg method silently drops the size.

Flipping it keeps every existing caller compiling, and matches iOS, where adServerDidWin(_:adSize:) is the only variant:

/** @deprecated Use {@link #onAdServerWin(View, AdSize)}. */
@Deprecated
default void onAdServerWin(View view) {
    onAdServerWin(view, null);
}

void onAdServerWin(View view, @Nullable AdSize adSize);

BannerView then only implements the two-arg method. It would only break code that implements BannerEventListener itself, which should be rare outside the SDK.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 835a955. The two-arg onAdServerWin(View, AdSize) is now abstract, the one-arg overload is a @Deprecated default forwarding null, and BannerView implements only the two-arg method.

onAdServerWin(view);
}

void onAdFailed(AdException exception);

void onAdClicked();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import android.util.AttributeSet;
import android.util.Pair;
import android.view.View;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand All @@ -36,6 +37,7 @@
import org.prebid.mobile.api.rendering.listeners.BannerVideoListener;
import org.prebid.mobile.api.rendering.listeners.BannerViewListener;
import org.prebid.mobile.api.rendering.pluginrenderer.PrebidMobilePluginRegister;
import org.prebid.mobile.api.rendering.pluginrenderer.PrebidMobilePluginRenderer;
import org.prebid.mobile.configuration.AdUnitConfiguration;
import org.prebid.mobile.rendering.bidding.data.bid.Bid;
import org.prebid.mobile.rendering.bidding.data.bid.BidResponse;
Expand Down Expand Up @@ -85,6 +87,9 @@ public class BannerViewTest {
@Mock
private ScreenStateReceiver mockScreenStateReceiver;

private PrebidMobilePluginRenderer fakeRenderer;
private PrebidMobilePluginRenderer previousDefaultRenderer;

@Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
Expand All @@ -101,6 +106,18 @@ public void setup() throws Exception {
assertEquals(AdPosition.UNDEFINED.getValue(), bannerView.getAdPosition().getValue());
}

@After
public void tearDown() {
if (fakeRenderer == null) {
return;
}
PrebidMobilePluginRegister register = PrebidMobilePluginRegister.getInstance();
register.unregisterPlugin(fakeRenderer);
if (previousDefaultRenderer != null) {
register.registerPlugin(previousDefaultRenderer);
}
}

@Test
public void createPrebidBannerViewWithAttributes_InstanceCreated() {
AttributeSet attributes = Robolectric.buildAttributeSet().build();
Expand Down Expand Up @@ -734,4 +751,179 @@ public void setPbAdSlot_EqualsGetPbAdSlot() {
assertEquals(expected, bannerView.getPbAdSlot());
}

//region ================= Creative size
@Test
public void creativeSize_BeforeAnyAd_IsZero() {
assertEquals(0, bannerView.getCreativeWidth());
assertEquals(0, bannerView.getCreativeHeight());
}

@Test
public void creativeSize_OnPrebidWin_IsWinningBidSizeWhenOnAdLoadedFires() throws IllegalAccessException {
final int[] sizeAtOnAdLoaded = new int[2];
doAnswer(invocation -> {
sizeAtOnAdLoaded[0] = bannerView.getCreativeWidth();
sizeAtOnAdLoaded[1] = bannerView.getCreativeHeight();
return null;
}).when(mockBannerListener).onAdLoaded(bannerView);

displayPrebidAd(320, 50, null);
RenderingTestUtils.getDisplayViewListener(bannerView).onAdLoaded();

assertArrayEquals(new int[]{320, 50}, sizeAtOnAdLoaded);
assertEquals(320, bannerView.getCreativeWidth());
assertEquals(50, bannerView.getCreativeHeight());
}

@Test
public void creativeSize_OnAdServerWinWithSize_IsAdServerSizeNotLosingBidSize() {
final int[] sizeAtOnAdLoaded = new int[2];
doAnswer(invocation -> {
sizeAtOnAdLoaded[0] = bannerView.getCreativeWidth();
sizeAtOnAdLoaded[1] = bannerView.getCreativeHeight();
return null;
}).when(mockBannerListener).onAdLoaded(bannerView);

// Prebid bids 320x50 but the ad server serves its own 300x250 creative.
RenderingTestUtils.getBidRequesterListener(bannerView).onFetchCompleted(mockBidResponse(320, 50, null));
RenderingTestUtils.getBannerEventListener(bannerView).onAdServerWin(new View(mockContext), new AdSize(300, 250));

assertArrayEquals(new int[]{300, 250}, sizeAtOnAdLoaded);
assertEquals(300, bannerView.getCreativeWidth());
assertEquals(250, bannerView.getCreativeHeight());
}

@Test
public void creativeSize_OnAdServerWinWithoutSize_IsZero() {
displayPrebidAd(320, 50, null);

RenderingTestUtils.getBidRequesterListener(bannerView).onFetchCompleted(mockBidResponse(300, 250, null));
RenderingTestUtils.getBannerEventListener(bannerView).onAdServerWin(new View(mockContext));

assertEquals(0, bannerView.getCreativeWidth());
assertEquals(0, bannerView.getCreativeHeight());
}

@Test
public void creativeSize_OnAdServerWinWithFluidSize_IsZero() {
RenderingTestUtils.getBannerEventListener(bannerView).onAdServerWin(new View(mockContext), new AdSize(-3, -4));

assertEquals(0, bannerView.getCreativeWidth());
assertEquals(0, bannerView.getCreativeHeight());
}

@Test
public void creativeSize_WhileRefreshIsInFlight_KeepsDisplayedCreativeSize() {
displayPrebidAd(300, 250, null);

RenderingTestUtils.getBidRequesterListener(bannerView).onFetchCompleted(mockBidResponse(320, 50, null));

assertEquals(300, bannerView.getCreativeWidth());
assertEquals(250, bannerView.getCreativeHeight());

RenderingTestUtils.getBannerEventListener(bannerView).onPrebidSdkWin();

assertEquals(320, bannerView.getCreativeWidth());
assertEquals(50, bannerView.getCreativeHeight());
}

@Test
public void creativeSize_WhenRefreshFindsNoBid_KeepsDisplayedCreativeSize() {
displayPrebidAd(300, 250, null);

RenderingTestUtils.getBidRequesterListener(bannerView).onError(new AdException(AdException.NO_BIDS, "No bids"));
RenderingTestUtils.getBannerEventListener(bannerView).onPrebidSdkWin();

verify(mockBannerListener).onAdFailed(eq(bannerView), any(AdException.class));
assertEquals(300, bannerView.getCreativeWidth());
assertEquals(250, bannerView.getCreativeHeight());
}

@Test
public void creativeSize_WhenCreativeFailsToRender_IsZero() throws IllegalAccessException {
displayPrebidAd(320, 50, null);

RenderingTestUtils.getDisplayViewListener(bannerView).onAdFailed(new AdException(AdException.INTERNAL_ERROR, ""));

assertEquals(0, bannerView.getCreativeWidth());
assertEquals(0, bannerView.getCreativeHeight());
}

@Test
public void creativeSize_WhenExpiredAdIsRemoved_IsZero() throws IllegalAccessException {
bannerView.setAutoRefreshDelay(30);
displayPrebidAd(320, 50, 1);
RenderingTestUtils.getDisplayViewListener(bannerView).onAdLoaded();

Shadows.shadowOf(Looper.getMainLooper()).idleFor(1, TimeUnit.SECONDS);

verify(mockBannerListener).onAdExpired(bannerView);
assertEquals(0, bannerView.getCreativeWidth());
assertEquals(0, bannerView.getCreativeHeight());
}

@Test
public void creativeSize_WhenExpiredAdIsKept_KeepsSize() throws IllegalAccessException {
displayPrebidAd(320, 50, 1);
RenderingTestUtils.getDisplayViewListener(bannerView).onAdLoaded();

Shadows.shadowOf(Looper.getMainLooper()).idleFor(1, TimeUnit.SECONDS);

verify(mockBannerListener).onAdExpired(bannerView);
assertEquals(320, bannerView.getCreativeWidth());
assertEquals(50, bannerView.getCreativeHeight());
}

@Test
public void creativeSize_AfterDestroy_IsZero() {
displayPrebidAd(320, 50, null);

bannerView.destroy();

assertEquals(0, bannerView.getCreativeWidth());
assertEquals(0, bannerView.getCreativeHeight());
}

private void displayPrebidAd(int width, int height, Integer expirationTimeSeconds) {
registerFakeRenderer();
RenderingTestUtils.getBidRequesterListener(bannerView)
.onFetchCompleted(mockBidResponse(width, height, expirationTimeSeconds));
RenderingTestUtils.getBannerEventListener(bannerView).onPrebidSdkWin();
}

private BidResponse mockBidResponse(int width, int height, Integer expirationTimeSeconds) {
final Bid mockBid = mock(Bid.class);
when(mockBid.getWidth()).thenReturn(width);
when(mockBid.getHeight()).thenReturn(height);
when(mockBid.getAdm()).thenReturn("adm");

final BidResponse mockBidResponse = mock(BidResponse.class);
when(mockBidResponse.getWinningBid()).thenReturn(mockBid);
when(mockBidResponse.getExpirationTimeSeconds()).thenReturn(expirationTimeSeconds);
when(mockBidResponse.getPreferredPluginRendererName()).thenReturn(PrebidMobilePluginRegister.PREBID_MOBILE_RENDERER_NAME);
when(mockBidResponse.getWinningBidWidthHeightPairDips(any())).thenReturn(Pair.create(width, height));
return mockBidResponse;
}

/**
* Replaces the default renderer with one that returns a fresh plain view, so a Prebid win can be
* displayed without rendering a real creative.
*/
private void registerFakeRenderer() {
if (fakeRenderer != null) {
return;
}
fakeRenderer = mock(PrebidMobilePluginRenderer.class);
when(fakeRenderer.getName()).thenReturn(PrebidMobilePluginRegister.PREBID_MOBILE_RENDERER_NAME);
when(fakeRenderer.getVersion()).thenReturn("1.0");
when(fakeRenderer.isSupportRenderingFor(any())).thenReturn(true);
when(fakeRenderer.createBannerAdView(any(), any(), any(), any(), any()))
.thenAnswer(invocation -> new View(mockContext));

final PrebidMobilePluginRegister register = PrebidMobilePluginRegister.getInstance();
previousDefaultRenderer = register.getDefaultPluginRenderer();
register.registerPlugin(fakeRenderer);
}
//endregion ================= Creative size

}
Loading