stormcloud-video-player 0.8.64 → 0.8.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -761,7 +761,7 @@ function toVastMediaErrorCode(error) {
761
761
  }
762
762
  }
763
763
  function createHlsAdPlayer(contentVideo, options) {
764
- var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP;
764
+ var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP, _ref;
765
765
  var adPlaying = false;
766
766
  var originalMutedState = false;
767
767
  var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
@@ -793,6 +793,16 @@ function createHlsAdPlayer(contentVideo, options) {
793
793
  var sawDecodedVideoFrame = false;
794
794
  var videoFrameCallbackHandle;
795
795
  var pendingPlayPromise;
796
+ var currentVastTagUrl;
797
+ var funnelContext = {};
798
+ var mediaCandidates = [];
799
+ var mediaCandidateIndex = 0;
800
+ var mediaStartTimerId;
801
+ var MEDIA_START_TIMEOUT_MS = (_ref = options === null || options === void 0 ? void 0 : options.mediaStartTimeoutMs) !== null && _ref !== void 0 ? _ref : 8e3;
802
+ var VAST_ERROR_MEDIA_TIMEOUT = 402;
803
+ var pendingVastRequests = /* @__PURE__ */ new Set();
804
+ var pendingRequestAbortReason;
805
+ var forcedMuteByAutoplay = false;
796
806
  function createTrackingState() {
797
807
  return {
798
808
  impression: false,
@@ -843,6 +853,77 @@ function createHlsAdPlayer(contentVideo, options) {
843
853
  }
844
854
  }
845
855
  }
856
+ var SENSITIVE_URL_PARAMS = /* @__PURE__ */ new Set([
857
+ "ppid",
858
+ "rdid",
859
+ "idtype",
860
+ "is_lat",
861
+ "ifa",
862
+ "idfa",
863
+ "aaid",
864
+ "uid",
865
+ "user_id",
866
+ "userid",
867
+ "device_id",
868
+ "deviceid",
869
+ "ip",
870
+ "ua",
871
+ "gdpr_consent",
872
+ "us_privacy",
873
+ "gpp",
874
+ "addtl_consent",
875
+ "cust_params",
876
+ "email"
877
+ ]);
878
+ function redactUrl(url) {
879
+ if (!url) return url;
880
+ try {
881
+ var parsed = new URL(url);
882
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
883
+ try {
884
+ for(var _iterator = Array.from(parsed.searchParams.keys())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
885
+ var key = _step.value;
886
+ if (SENSITIVE_URL_PARAMS.has(key.toLowerCase())) {
887
+ parsed.searchParams.set(key, "REDACTED");
888
+ }
889
+ }
890
+ } catch (err) {
891
+ _didIteratorError = true;
892
+ _iteratorError = err;
893
+ } finally{
894
+ try {
895
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
896
+ _iterator.return();
897
+ }
898
+ } finally{
899
+ if (_didIteratorError) {
900
+ throw _iteratorError;
901
+ }
902
+ }
903
+ }
904
+ return parsed.toString();
905
+ } catch (unused) {
906
+ return url.split("?")[0];
907
+ }
908
+ }
909
+ function logFunnel(stage) {
910
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
911
+ var payload = _object_spread({
912
+ stage: stage,
913
+ breakId: funnelContext.breakId,
914
+ requestId: funnelContext.requestId,
915
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0,
916
+ adId: currentAd === null || currentAd === void 0 ? void 0 : currentAd.id,
917
+ podIndex: podIndex,
918
+ podSize: podAds.length,
919
+ vastUrl: redactUrl(currentVastTagUrl),
920
+ mediaUrl: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url,
921
+ mediaType: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.type,
922
+ muted: adVideoElement ? adVideoElement.muted : void 0
923
+ }, extra);
924
+ console.log("[HlsAdPlayer][FUNNEL] ".concat(stage), payload);
925
+ emit("ad_funnel", payload);
926
+ }
846
927
  function buildTrackingMacroContext() {
847
928
  var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
848
929
  var _options2_ad;
@@ -882,20 +963,53 @@ function createHlsAdPlayer(contentVideo, options) {
882
963
  urls.forEach(function(url) {
883
964
  try {
884
965
  var trackingUrl = substituteVastTrackingMacros(url, macroContext);
966
+ var trackingHost;
967
+ try {
968
+ trackingHost = new URL(trackingUrl).host;
969
+ } catch (unused) {
970
+ logFunnel("tracking_url_invalid", {
971
+ trackingUrl: redactUrl(trackingUrl)
972
+ });
973
+ return;
974
+ }
975
+ var unexpanded = trackingUrl.match(/\[[A-Z_]+\]/g);
976
+ if (unexpanded) {
977
+ logFunnel("tracking_url_unexpanded_macro", {
978
+ trackingHost: trackingHost,
979
+ macros: Array.from(new Set(unexpanded))
980
+ });
981
+ }
885
982
  var img = new Image(1, 1);
886
983
  inFlightBeacons.add(img);
887
984
  var timeoutId;
888
- var release = function release() {
985
+ var release = function release(outcome) {
889
986
  if (timeoutId !== void 0) clearTimeout(timeoutId);
890
987
  img.onload = null;
891
988
  img.onerror = null;
892
989
  inFlightBeacons.delete(img);
990
+ console.log("[HlsAdPlayer] Tracking pixel settled (".concat(outcome, "): ").concat(trackingUrl));
991
+ if (outcome !== "load") {
992
+ logFunnel("tracking_request_settled", {
993
+ reason: outcome,
994
+ trackingHost: trackingHost
995
+ });
996
+ }
997
+ };
998
+ img.onload = function() {
999
+ return release("load");
1000
+ };
1001
+ img.onerror = function() {
1002
+ return release("error");
893
1003
  };
894
- img.onload = release;
895
- img.onerror = release;
896
- timeoutId = setTimeout(release, BEACON_TIMEOUT_MS);
1004
+ timeoutId = setTimeout(function() {
1005
+ return release("timeout");
1006
+ }, BEACON_TIMEOUT_MS);
897
1007
  img.src = trackingUrl;
898
1008
  console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(trackingUrl));
1009
+ logFunnel("tracking_request_created", {
1010
+ trackingHost: trackingHost,
1011
+ errorCode: options2 === null || options2 === void 0 ? void 0 : options2.errorCode
1012
+ });
899
1013
  } catch (error) {
900
1014
  console.warn("[HlsAdPlayer] Error firing tracking pixel:", error);
901
1015
  }
@@ -925,54 +1039,80 @@ function createHlsAdPlayer(contentVideo, options) {
925
1039
  bitrate: level.bitrate || 5e6
926
1040
  };
927
1041
  }
928
- function selectBestMediaFile(mediaFiles) {
929
- if (mediaFiles.length === 0) {
930
- throw new Error("No media files available");
931
- }
932
- var firstFile = mediaFiles[0];
933
- if (!firstFile) {
934
- throw new Error("No media files available");
935
- }
936
- if (mediaFiles.length === 1) {
937
- return firstFile;
938
- }
1042
+ function getMediaTargetQuality() {
939
1043
  var mainQuality = getMainStreamQuality();
940
- if (!mainQuality) {
941
- console.log("[HlsAdPlayer] No main stream quality info, using first media file");
942
- return firstFile;
943
- }
944
- console.log("[HlsAdPlayer] Main stream quality:", mainQuality);
945
- var scoredFiles = mediaFiles.map(function(file) {
946
- var widthDiff = Math.abs(file.width - mainQuality.width);
947
- var heightDiff = Math.abs(file.height - mainQuality.height);
948
- var resolutionDiff = widthDiff + heightDiff;
949
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
950
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
951
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
952
- return {
1044
+ var dpr = typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
1045
+ var containerWidth = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientWidth) || contentVideo.clientWidth) * dpr;
1046
+ var containerHeight = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientHeight) || contentVideo.clientHeight) * dpr;
1047
+ if (!mainQuality && !(containerWidth > 0 && containerHeight > 0)) {
1048
+ return null;
1049
+ }
1050
+ var base = mainQuality !== null && mainQuality !== void 0 ? mainQuality : {
1051
+ width: containerWidth,
1052
+ height: containerHeight,
1053
+ bitrate: 5e6
1054
+ };
1055
+ var width = containerWidth > 0 ? Math.min(base.width, containerWidth) : base.width;
1056
+ var height = containerHeight > 0 ? Math.min(base.height, containerHeight) : base.height;
1057
+ return {
1058
+ width: width,
1059
+ height: height,
1060
+ bitrate: base.bitrate
1061
+ };
1062
+ }
1063
+ function rankMediaCandidates(mediaFiles) {
1064
+ var probe = adVideoElement !== null && adVideoElement !== void 0 ? adVideoElement : document.createElement("video");
1065
+ var pageIsHttps = typeof location !== "undefined" && location.protocol === "https:";
1066
+ var target = getMediaTargetQuality();
1067
+ var accepted = [];
1068
+ mediaFiles.forEach(function(file, index) {
1069
+ var isHls = isHlsMediaFile(file);
1070
+ var mimeForProbe = isHls ? "application/vnd.apple.mpegurl" : file.type || "video/mp4";
1071
+ var canPlay = probe.canPlayType(mimeForProbe);
1072
+ var playable = isHls ? import_hls.default.isSupported() || canPlay !== "" : canPlay !== "";
1073
+ var insecure = pageIsHttps && /^http:/i.test(file.url);
1074
+ var details = {
1075
+ index: index,
1076
+ candidateUrl: file.url,
1077
+ candidateType: file.type,
1078
+ width: file.width,
1079
+ height: file.height,
1080
+ bitrate: file.bitrate,
1081
+ canPlayType: canPlay,
1082
+ hlsJs: isHls ? import_hls.default.isSupported() : void 0
1083
+ };
1084
+ if (!playable) {
1085
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1086
+ reason: "rejected",
1087
+ why: "cannot_play_type"
1088
+ }));
1089
+ return;
1090
+ }
1091
+ var score = 0;
1092
+ if (target) {
1093
+ var resolutionDiff = Math.abs(file.width - target.width) + Math.abs(file.height - target.height);
1094
+ var bitrateDiff = Math.abs((file.bitrate || 5e3) * 1e3 - target.bitrate);
1095
+ score = resolutionDiff * 2 + bitrateDiff / 1e3;
1096
+ }
1097
+ accepted.push({
953
1098
  file: file,
954
1099
  score: score,
955
- resolutionDiff: resolutionDiff,
956
- bitrateDiff: bitrateDiff
957
- };
1100
+ insecure: insecure
1101
+ });
1102
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1103
+ reason: "accepted",
1104
+ // Mixed-content media is often auto-upgraded, so it is kept as a last resort.
1105
+ why: insecure ? "insecure_http_deprioritized" : "playable",
1106
+ score: score
1107
+ }));
958
1108
  });
959
- scoredFiles.sort(function(a, b) {
1109
+ accepted.sort(function(a, b) {
1110
+ if (a.insecure !== b.insecure) return a.insecure ? 1 : -1;
960
1111
  return a.score - b.score;
961
1112
  });
962
- var bestMatch = scoredFiles[0];
963
- if (!bestMatch) {
964
- console.log("[HlsAdPlayer] No best match found, using first media file");
965
- return firstFile;
966
- }
967
- console.log("[HlsAdPlayer] Selected media file:", {
968
- url: bestMatch.file.url,
969
- resolution: "".concat(bestMatch.file.width, "x").concat(bestMatch.file.height),
970
- bitrate: bestMatch.file.bitrate,
971
- score: bestMatch.score,
972
- resolutionDiff: bestMatch.resolutionDiff,
973
- bitrateDiff: bestMatch.bitrateDiff
1113
+ return accepted.map(function(entry) {
1114
+ return entry.file;
974
1115
  });
975
- return bestMatch.file;
976
1116
  }
977
1117
  function isHlsMediaFile(mediaFile) {
978
1118
  var type = mediaFile.type.toLowerCase();
@@ -989,9 +1129,10 @@ function createHlsAdPlayer(contentVideo, options) {
989
1129
  var url = (mediaFile.url.toLowerCase().split("?")[0] || "").trim();
990
1130
  return type.startsWith("audio/") || url.endsWith(".mp3") || url.endsWith(".aac") || url.endsWith(".m4a") || url.endsWith(".ogg") || url.endsWith(".oga") || url.endsWith(".opus") || url.endsWith(".wav") || url.endsWith(".weba");
991
1131
  }
992
- function collectVideoMediaFiles(linear, verbose) {
1132
+ function collectVideoMediaFiles(linear, verbose, stats) {
993
1133
  var mediaFileElements = linear.querySelectorAll(":scope > MediaFiles > MediaFile");
994
1134
  var mediaFiles = [];
1135
+ if (stats) stats.total += mediaFileElements.length;
995
1136
  if (verbose) {
996
1137
  console.log("[HlsAdPlayer] Found ".concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
997
1138
  }
@@ -1012,6 +1153,7 @@ function createHlsAdPlayer(contentVideo, options) {
1012
1153
  }
1013
1154
  var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
1014
1155
  if (apiFramework === "VPAID") {
1156
+ if (stats) stats.vpaid++;
1015
1157
  if (verbose) {
1016
1158
  console.log("[HlsAdPlayer] MediaFile ".concat(index, " ignored (VPAID creatives are not supported)"));
1017
1159
  }
@@ -1027,11 +1169,13 @@ function createHlsAdPlayer(contentVideo, options) {
1027
1169
  bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
1028
1170
  };
1029
1171
  if (isAudioMediaFile(mediaFile)) {
1172
+ if (stats) stats.audio++;
1030
1173
  console.warn("[HlsAdPlayer] MediaFile ".concat(index, ' skipped (audio-only, type="').concat(type, '") — audio ads are not played to avoid a black screen'));
1031
1174
  return;
1032
1175
  }
1033
1176
  var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
1034
1177
  if (!isHlsMediaFile(mediaFile) && hasExplicitDimensions && (mediaFile.width <= 1 || mediaFile.height <= 1)) {
1178
+ if (stats) stats.audio++;
1035
1179
  console.warn("[HlsAdPlayer] MediaFile ".concat(index, " skipped (degenerate dimensions ").concat(mediaFile.width, "x").concat(mediaFile.height, ', type="').concat(type, '") — likely an audio-only placeholder rendition'));
1036
1180
  return;
1037
1181
  }
@@ -1040,8 +1184,11 @@ function createHlsAdPlayer(contentVideo, options) {
1040
1184
  if (verbose) {
1041
1185
  console.log("[HlsAdPlayer] Added ".concat(isHlsMediaFile(mediaFile) ? "HLS" : "progressive", " MediaFile: ").concat(url));
1042
1186
  }
1043
- } else if (verbose) {
1044
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1187
+ } else {
1188
+ if (stats) stats.unsupported++;
1189
+ if (verbose) {
1190
+ console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1191
+ }
1045
1192
  }
1046
1193
  });
1047
1194
  return mediaFiles;
@@ -1165,26 +1312,58 @@ function createHlsAdPlayer(contentVideo, options) {
1165
1312
  }
1166
1313
  function parseVastXml(xmlString) {
1167
1314
  try {
1168
- var _adElements_find;
1169
1315
  var xmlDoc = parseXml(xmlString);
1170
1316
  if (!xmlDoc) return {
1171
1317
  type: "empty"
1172
1318
  };
1173
1319
  var root = xmlDoc.documentElement;
1174
1320
  var adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1175
- var adElement = (_adElements_find = adElements.find(function(el) {
1176
- return getAdSequence(el) === void 0;
1177
- })) !== null && _adElements_find !== void 0 ? _adElements_find : adElements[0];
1178
- if (!adElement) {
1321
+ if (adElements.length === 0) {
1179
1322
  var _root_getAttribute;
1180
1323
  console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " response"));
1181
1324
  return emptyVastResult(root);
1182
1325
  }
1183
- var parsed = parseAdElement(adElement, true);
1184
- if (parsed.type === "wrapper") {
1185
- console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1326
+ var ordered = _to_consumable_array(adElements.filter(function(el) {
1327
+ return getAdSequence(el) === void 0;
1328
+ })).concat(_to_consumable_array(adElements.filter(function(el) {
1329
+ return getAdSequence(el) !== void 0;
1330
+ })));
1331
+ var firstEmpty;
1332
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1333
+ try {
1334
+ for(var _iterator = ordered.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1335
+ var _step_value = _sliced_to_array(_step.value, 2), index = _step_value[0], adElement = _step_value[1];
1336
+ var parsed = parseAdElement(adElement, true);
1337
+ if (parsed.type === "empty") {
1338
+ firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : firstEmpty = parsed;
1339
+ continue;
1340
+ }
1341
+ if (index > 0) {
1342
+ logFunnel("vast_ad_fallback", {
1343
+ usedAdIndex: index,
1344
+ adCount: ordered.length
1345
+ });
1346
+ }
1347
+ if (parsed.type === "wrapper") {
1348
+ console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1349
+ }
1350
+ return parsed;
1351
+ }
1352
+ } catch (err) {
1353
+ _didIteratorError = true;
1354
+ _iteratorError = err;
1355
+ } finally{
1356
+ try {
1357
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1358
+ _iterator.return();
1359
+ }
1360
+ } finally{
1361
+ if (_didIteratorError) {
1362
+ throw _iteratorError;
1363
+ }
1364
+ }
1186
1365
  }
1187
- return parsed;
1366
+ return firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : emptyVastResult(root);
1188
1367
  } catch (error) {
1189
1368
  console.error("[HlsAdPlayer] Error parsing VAST XML:", error);
1190
1369
  return {
@@ -1230,6 +1409,10 @@ function createHlsAdPlayer(contentVideo, options) {
1230
1409
  pushUrls(errorUrls, inLine.querySelectorAll(":scope > Error"));
1231
1410
  if (adElement.getAttribute("conditionalAd") === "true") {
1232
1411
  console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)");
1412
+ logFunnel("vast_no_supported_media", {
1413
+ reason: "vpaid_only",
1414
+ conditionalAd: true
1415
+ });
1233
1416
  return {
1234
1417
  type: "empty",
1235
1418
  errorUrls: errorUrls,
@@ -1238,11 +1421,17 @@ function createHlsAdPlayer(contentVideo, options) {
1238
1421
  }
1239
1422
  var linear;
1240
1423
  var mediaFiles = [];
1424
+ var rejectStats = {
1425
+ total: 0,
1426
+ vpaid: 0,
1427
+ audio: 0,
1428
+ unsupported: 0
1429
+ };
1241
1430
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1242
1431
  try {
1243
1432
  for(var _iterator = Array.from(inLine.querySelectorAll(":scope > Creatives > Creative > Linear"))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1244
1433
  var candidate = _step.value;
1245
- var files = collectVideoMediaFiles(candidate, verbose);
1434
+ var files = collectVideoMediaFiles(candidate, verbose, rejectStats);
1246
1435
  if (files.length > 0) {
1247
1436
  linear = candidate;
1248
1437
  mediaFiles = files;
@@ -1265,6 +1454,10 @@ function createHlsAdPlayer(contentVideo, options) {
1265
1454
  }
1266
1455
  if (!linear) {
1267
1456
  console.warn("[HlsAdPlayer] No supported linear media files in <Ad>");
1457
+ var reason = rejectStats.total === 0 ? "no_mediafiles" : rejectStats.vpaid > 0 ? "vpaid_only" : rejectStats.audio > 0 ? "audio_only" : "unsupported_type";
1458
+ logFunnel("vast_no_supported_media", _object_spread({
1459
+ reason: reason
1460
+ }, rejectStats));
1268
1461
  return {
1269
1462
  type: "empty",
1270
1463
  errorUrls: errorUrls,
@@ -1300,7 +1493,11 @@ function createHlsAdPlayer(contentVideo, options) {
1300
1493
  return _ts_generator(this, function(_state) {
1301
1494
  switch(_state.label){
1302
1495
  case 0:
1496
+ if (destroyed) {
1497
+ throw new Error("VAST request skipped: ad player destroyed");
1498
+ }
1303
1499
  controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
1500
+ if (controller) pendingVastRequests.add(controller);
1304
1501
  timeoutId = controller ? setTimeout(function() {
1305
1502
  return controller.abort();
1306
1503
  }, VAST_REQUEST_TIMEOUT_MS) : void 0;
@@ -1349,6 +1546,9 @@ function createHlsAdPlayer(contentVideo, options) {
1349
1546
  6
1350
1547
  ];
1351
1548
  console.warn('[HlsAdPlayer] VAST fetch failed with credentials="'.concat(credentials, '", retrying without credentials:'), error);
1549
+ logFunnel("vast_credentials_retry", {
1550
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1551
+ });
1352
1552
  return [
1353
1553
  4,
1354
1554
  requestVast("omit")
@@ -1382,11 +1582,15 @@ function createHlsAdPlayer(contentVideo, options) {
1382
1582
  case 10:
1383
1583
  error1 = _state.sent();
1384
1584
  if (controller === null || controller === void 0 ? void 0 : controller.signal.aborted) {
1585
+ if (pendingRequestAbortReason) {
1586
+ throw new Error("".concat(pendingRequestAbortReason, " (timeout): ").concat(vastTagUrl));
1587
+ }
1385
1588
  throw new Error("VAST request timeout after ".concat(VAST_REQUEST_TIMEOUT_MS, "ms: ").concat(vastTagUrl));
1386
1589
  }
1387
1590
  throw error1;
1388
1591
  case 11:
1389
1592
  if (timeoutId !== void 0) clearTimeout(timeoutId);
1593
+ if (controller) pendingVastRequests.delete(controller);
1390
1594
  return [
1391
1595
  7
1392
1596
  ];
@@ -1400,7 +1604,7 @@ function createHlsAdPlayer(contentVideo, options) {
1400
1604
  }
1401
1605
  function fetchAndParseVastAd(_0) {
1402
1606
  return _async_to_generator(function(vastTagUrl) {
1403
- var depth, accumulatedTracking, rules, vastXml, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1607
+ var depth, accumulatedTracking, rules, vastXml, fetchStartedAt, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1404
1608
  var _arguments = arguments;
1405
1609
  return _ts_generator(this, function(_state) {
1406
1610
  switch(_state.label){
@@ -1408,6 +1612,11 @@ function createHlsAdPlayer(contentVideo, options) {
1408
1612
  depth = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : 0, accumulatedTracking = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : createEmptyTrackingUrls(), rules = _arguments.length > 3 && _arguments[3] !== void 0 ? _arguments[3] : {
1409
1613
  followAdditionalWrappers: true
1410
1614
  };
1615
+ if (destroyed) return [
1616
+ 2,
1617
+ null
1618
+ ];
1619
+ fetchStartedAt = Date.now();
1411
1620
  _state.label = 1;
1412
1621
  case 1:
1413
1622
  _state.trys.push([
@@ -1430,14 +1639,35 @@ function createHlsAdPlayer(contentVideo, options) {
1430
1639
  error = _state.sent();
1431
1640
  if (depth === 0) throw error;
1432
1641
  console.warn("[HlsAdPlayer] Wrapped VAST request failed:", error);
1433
- fireTrackingPixels(accumulatedTracking.error, {
1434
- errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1642
+ logFunnel("wrapper_fetch", {
1643
+ reason: "failure",
1644
+ depth: depth,
1645
+ wrapperUrl: redactUrl(vastTagUrl),
1646
+ elapsedMs: Date.now() - fetchStartedAt,
1647
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1435
1648
  });
1649
+ if (!destroyed) {
1650
+ fireTrackingPixels(accumulatedTracking.error, {
1651
+ errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1652
+ });
1653
+ }
1436
1654
  return [
1437
1655
  2,
1438
1656
  null
1439
1657
  ];
1440
1658
  case 4:
1659
+ if (destroyed) return [
1660
+ 2,
1661
+ null
1662
+ ];
1663
+ if (depth > 0) {
1664
+ logFunnel("wrapper_fetch", {
1665
+ reason: "success",
1666
+ depth: depth,
1667
+ wrapperUrl: redactUrl(vastTagUrl),
1668
+ elapsedMs: Date.now() - fetchStartedAt
1669
+ });
1670
+ }
1441
1671
  console.log("[HlsAdPlayer] VAST XML received");
1442
1672
  console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1443
1673
  parsed = parseVastXml(vastXml);
@@ -1469,6 +1699,9 @@ function createHlsAdPlayer(contentVideo, options) {
1469
1699
  ];
1470
1700
  }
1471
1701
  mergeTrackingUrls(parsed.ad.trackingUrls, accumulatedTracking);
1702
+ logFunnel("inline_resolved", {
1703
+ depth: depth
1704
+ });
1472
1705
  return [
1473
1706
  2,
1474
1707
  parsed.ad
@@ -1489,6 +1722,10 @@ function createHlsAdPlayer(contentVideo, options) {
1489
1722
  ];
1490
1723
  case 1:
1491
1724
  vastXml = _state.sent();
1725
+ if (destroyed) return [
1726
+ 2,
1727
+ []
1728
+ ];
1492
1729
  console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(vastXml.length, ")"));
1493
1730
  trimmedXml = vastXml.trim();
1494
1731
  if (trimmedXml.length === 0) {
@@ -1776,14 +2013,17 @@ function createHlsAdPlayer(contentVideo, options) {
1776
2013
  var progress = currentTime / currentAd.duration;
1777
2014
  if (progress >= 0.25 && !trackingFired.firstQuartile) {
1778
2015
  trackingFired.firstQuartile = true;
2016
+ logFunnel("first_quartile");
1779
2017
  fireTrackingPixels(currentAd.trackingUrls.firstQuartile);
1780
2018
  }
1781
2019
  if (progress >= 0.5 && !trackingFired.midpoint) {
1782
2020
  trackingFired.midpoint = true;
2021
+ logFunnel("midpoint");
1783
2022
  fireTrackingPixels(currentAd.trackingUrls.midpoint);
1784
2023
  }
1785
2024
  if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1786
2025
  trackingFired.thirdQuartile = true;
2026
+ logFunnel("third_quartile");
1787
2027
  fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);
1788
2028
  }
1789
2029
  };
@@ -1806,6 +2046,16 @@ function createHlsAdPlayer(contentVideo, options) {
1806
2046
  if (!trackingFired.impression) {
1807
2047
  trackingFired.impression = true;
1808
2048
  resolvedAds.add(currentAd);
2049
+ logFunnel("playing", {
2050
+ mutedByAutoplay: forcedMuteByAutoplay,
2051
+ candidateIndex: mediaCandidateIndex
2052
+ });
2053
+ logFunnel("impression_fired", {
2054
+ pixelCount: currentAd.trackingUrls.impression.length
2055
+ });
2056
+ if (currentAd.trackingUrls.impression.length === 0) {
2057
+ console.warn("[HlsAdPlayer] Ad started but VAST contained no <Impression> URLs - GAM will not count it");
2058
+ }
1809
2059
  fireTrackingPixels(currentAd.trackingUrls.impression);
1810
2060
  fireTrackingPixels(currentAd.trackingUrls.creativeView);
1811
2061
  fireTrackingPixels(currentAd.trackingUrls.verificationNotExecuted, {
@@ -1828,6 +2078,7 @@ function createHlsAdPlayer(contentVideo, options) {
1828
2078
  sampleViewability();
1829
2079
  settleViewability();
1830
2080
  trackingFired.complete = true;
2081
+ logFunnel("complete");
1831
2082
  fireTrackingPixels(currentAd.trackingUrls.complete);
1832
2083
  console.log("[HlsAdPlayer] Ad completed");
1833
2084
  if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
@@ -1836,16 +2087,41 @@ function createHlsAdPlayer(contentVideo, options) {
1836
2087
  handleAdComplete();
1837
2088
  };
1838
2089
  var onError = function onError(e) {
2090
+ var _adVideoElement_error, _adVideoElement_error1;
1839
2091
  if (!adPlaying) return;
1840
2092
  console.error("[HlsAdPlayer] Ad video error:", e);
1841
- reportCurrentAdError(toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error));
1842
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
1843
- return;
1844
- }
1845
- handleAdError();
2093
+ var vastErrorCode = toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error);
2094
+ logFunnel("media_error", {
2095
+ mediaErrorCode: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error = adVideoElement.error) === null || _adVideoElement_error === void 0 ? void 0 : _adVideoElement_error.code,
2096
+ errorMessage: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error1 = adVideoElement.error) === null || _adVideoElement_error1 === void 0 ? void 0 : _adVideoElement_error1.message,
2097
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2098
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2099
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2100
+ vastErrorCode: vastErrorCode
2101
+ });
2102
+ recoverFromAdFailure(vastErrorCode);
2103
+ };
2104
+ var onMediaDiagnostic = function onMediaDiagnostic(event) {
2105
+ if (!adPlaying || !adVideoElement || trackingFired.impression) return;
2106
+ if (!adVideoElement.currentSrc) return;
2107
+ logFunnel("media_event", {
2108
+ reason: event.type,
2109
+ readyState: adVideoElement.readyState,
2110
+ networkState: adVideoElement.networkState,
2111
+ currentSrc: adVideoElement.currentSrc
2112
+ });
1846
2113
  };
1847
2114
  var onVolumeChange = function onVolumeChange() {
1848
2115
  if (!currentAd || !adVideoElement) return;
2116
+ if (forcedMuteByAutoplay && !adVideoElement.muted) {
2117
+ var userActivation = navigator.userActivation;
2118
+ if (userActivation && !userActivation.isActive) {
2119
+ logFunnel("unexpected_unmute", {
2120
+ paused: adVideoElement.paused
2121
+ });
2122
+ }
2123
+ forcedMuteByAutoplay = false;
2124
+ }
1849
2125
  var muted = adVideoElement.muted || adVideoElement.volume === 0;
1850
2126
  if (!trackingFired.start) {
1851
2127
  trackingFired.lastMuted = muted;
@@ -1905,6 +2181,22 @@ function createHlsAdPlayer(contentVideo, options) {
1905
2181
  {
1906
2182
  type: "play",
1907
2183
  handler: onPlay
2184
+ },
2185
+ {
2186
+ type: "stalled",
2187
+ handler: onMediaDiagnostic
2188
+ },
2189
+ {
2190
+ type: "suspend",
2191
+ handler: onMediaDiagnostic
2192
+ },
2193
+ {
2194
+ type: "abort",
2195
+ handler: onMediaDiagnostic
2196
+ },
2197
+ {
2198
+ type: "emptied",
2199
+ handler: onMediaDiagnostic
1908
2200
  }
1909
2201
  ];
1910
2202
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
@@ -2194,16 +2486,51 @@ function createHlsAdPlayer(contentVideo, options) {
2194
2486
  function settlePendingPlay() {
2195
2487
  pendingPlayPromise = void 0;
2196
2488
  }
2489
+ function toVastPlayErrorCode(error) {
2490
+ return (error === null || error === void 0 ? void 0 : error.name) === "NotSupportedError" ? VAST_ERROR_NO_SUPPORTED_MEDIA : VAST_ERROR_MEDIA_DISPLAY;
2491
+ }
2492
+ function failAdPlayback(context, error) {
2493
+ var vastErrorCode = toVastPlayErrorCode(error);
2494
+ console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2495
+ logFunnel("play_failed", {
2496
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2497
+ errorMessage: error === null || error === void 0 ? void 0 : error.message,
2498
+ vastErrorCode: vastErrorCode
2499
+ });
2500
+ recoverFromAdFailure(vastErrorCode);
2501
+ }
2197
2502
  function startAdPlayback(context) {
2503
+ var isMutedRetry = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2198
2504
  if (!adVideoElement) return;
2505
+ var computed = typeof getComputedStyle === "function" && adContainerEl ? getComputedStyle(adContainerEl) : void 0;
2506
+ logFunnel(isMutedRetry ? "muted_retry" : "play_called", {
2507
+ context: context,
2508
+ isConnected: adVideoElement.isConnected,
2509
+ clientWidth: adVideoElement.clientWidth,
2510
+ clientHeight: adVideoElement.clientHeight,
2511
+ containerDisplay: computed === null || computed === void 0 ? void 0 : computed.display,
2512
+ containerVisibility: computed === null || computed === void 0 ? void 0 : computed.visibility
2513
+ });
2199
2514
  var playPromise = adVideoElement.play();
2200
2515
  pendingPlayPromise = playPromise;
2201
2516
  playPromise.catch(function(error) {
2202
2517
  if (pendingPlayPromise !== playPromise) {
2203
2518
  return;
2204
2519
  }
2205
- console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2206
- handleAdError();
2520
+ logFunnel("play_rejected", {
2521
+ context: context,
2522
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2523
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2524
+ });
2525
+ if (!isMutedRetry && (error === null || error === void 0 ? void 0 : error.name) === "NotAllowedError" && adVideoElement && !adVideoElement.muted) {
2526
+ console.warn("[HlsAdPlayer] Unmuted ".concat(context, " blocked by autoplay policy - retrying muted"));
2527
+ originalMutedState = true;
2528
+ forcedMuteByAutoplay = true;
2529
+ adVideoElement.muted = true;
2530
+ startAdPlayback(context, true);
2531
+ return;
2532
+ }
2533
+ failAdPlayback(context, error);
2207
2534
  }).finally(function() {
2208
2535
  if (pendingPlayPromise === playPromise) {
2209
2536
  pendingPlayPromise = void 0;
@@ -2242,17 +2569,109 @@ function createHlsAdPlayer(contentVideo, options) {
2242
2569
  adVideoElement.volume = Math.max(0, Math.min(1, originalVolume));
2243
2570
  adVideoElement.muted = originalMutedState;
2244
2571
  }
2572
+ function clearMediaStartTimer() {
2573
+ if (mediaStartTimerId !== void 0) {
2574
+ clearTimeout(mediaStartTimerId);
2575
+ mediaStartTimerId = void 0;
2576
+ }
2577
+ }
2578
+ function startMediaStartTimer() {
2579
+ clearMediaStartTimer();
2580
+ if (!(MEDIA_START_TIMEOUT_MS > 0)) return;
2581
+ var startedAt = Date.now();
2582
+ mediaStartTimerId = setTimeout(function() {
2583
+ mediaStartTimerId = void 0;
2584
+ if (!adPlaying || trackingFired.impression) return;
2585
+ console.warn("[HlsAdPlayer] Ad media did not start playing within ".concat(MEDIA_START_TIMEOUT_MS, "ms"));
2586
+ logFunnel("play_resolved_but_never_started", {
2587
+ timeoutMs: MEDIA_START_TIMEOUT_MS,
2588
+ elapsedMs: Date.now() - startedAt,
2589
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2590
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2591
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2592
+ paused: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.paused,
2593
+ vastErrorCode: VAST_ERROR_MEDIA_TIMEOUT
2594
+ });
2595
+ recoverFromAdFailure(VAST_ERROR_MEDIA_TIMEOUT);
2596
+ }, MEDIA_START_TIMEOUT_MS);
2597
+ }
2598
+ function resetVideoElementForNextSource() {
2599
+ clearStallWatchdog();
2600
+ if (requiresMediaPipelineResetAfterAds()) {
2601
+ recreateAdVideoElement();
2602
+ setupAdEventListeners();
2603
+ } else {
2604
+ prepareVideoElementForNewSource();
2605
+ }
2606
+ }
2607
+ function tryNextMediaCandidate() {
2608
+ if (!currentAd || trackingFired.impression) return false;
2609
+ if (mediaCandidateIndex >= mediaCandidates.length - 1) return false;
2610
+ var failedUrl = currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url;
2611
+ mediaCandidateIndex++;
2612
+ var next = mediaCandidates[mediaCandidateIndex];
2613
+ if (!next) return false;
2614
+ logFunnel("media_fallback", {
2615
+ failedUrl: failedUrl,
2616
+ nextUrl: next.url,
2617
+ nextType: next.type,
2618
+ candidateIndex: mediaCandidateIndex,
2619
+ candidateCount: mediaCandidates.length
2620
+ });
2621
+ resetVideoElementForNextSource();
2622
+ try {
2623
+ loadMediaCandidate(next);
2624
+ return true;
2625
+ } catch (error) {
2626
+ console.error("[HlsAdPlayer] Failed to load fallback media file:", error);
2627
+ return tryNextMediaCandidate();
2628
+ }
2629
+ }
2630
+ function recoverFromAdFailure(vastErrorCode) {
2631
+ clearMediaStartTimer();
2632
+ if (tryNextMediaCandidate()) return;
2633
+ reportCurrentAdError(vastErrorCode);
2634
+ if (podIndex < podAds.length - 1 && advanceToNextPodAd()) return;
2635
+ handleAdError();
2636
+ }
2245
2637
  function loadCurrentAdMedia() {
2246
2638
  if (!adVideoElement || !currentAd) {
2247
2639
  throw new Error("No ad video element or ad to load");
2248
2640
  }
2249
- var mediaFile = selectBestMediaFile(currentAd.mediaFiles);
2641
+ mediaCandidates = rankMediaCandidates(currentAd.mediaFiles);
2642
+ mediaCandidateIndex = 0;
2643
+ var mediaFile = mediaCandidates[0];
2250
2644
  if (!mediaFile) {
2251
- throw new Error("No media file available for ad");
2645
+ logFunnel("media_unsupported", {
2646
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA,
2647
+ candidates: currentAd.mediaFiles.length
2648
+ });
2649
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2650
+ throw new Error("No media file this browser can play");
2651
+ }
2652
+ try {
2653
+ loadMediaCandidate(mediaFile);
2654
+ } catch (error) {
2655
+ if (tryNextMediaCandidate()) return;
2656
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2657
+ throw error;
2658
+ }
2659
+ }
2660
+ function loadMediaCandidate(mediaFile) {
2661
+ if (!adVideoElement || !currentAd) {
2662
+ throw new Error("No ad video element or ad to load");
2252
2663
  }
2253
2664
  currentAdMediaFile = mediaFile;
2254
2665
  var isHlsAd = isHlsMediaFile(mediaFile);
2666
+ logFunnel("media_selected", {
2667
+ width: mediaFile.width,
2668
+ height: mediaFile.height,
2669
+ bitrate: mediaFile.bitrate,
2670
+ candidateIndex: mediaCandidateIndex,
2671
+ candidates: mediaCandidates.length
2672
+ });
2255
2673
  console.log("[HlsAdPlayer] Loading ".concat(isHlsAd ? "HLS" : "progressive", " ad (pod ").concat(podIndex + 1, "/").concat(podAds.length || 1, ") from: ").concat(mediaFile.url));
2674
+ startMediaStartTimer();
2256
2675
  if (isHlsAd && import_hls.default.isSupported()) {
2257
2676
  if (adHls) {
2258
2677
  adHls.destroy();
@@ -2261,6 +2680,9 @@ function createHlsAdPlayer(contentVideo, options) {
2261
2680
  enableWorker: true,
2262
2681
  lowLatencyMode: false
2263
2682
  });
2683
+ logFunnel("media_load", {
2684
+ pipeline: "hls.js"
2685
+ });
2264
2686
  adHls.loadSource(mediaFile.url);
2265
2687
  adHls.attachMedia(adVideoElement);
2266
2688
  adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
@@ -2270,10 +2692,24 @@ function createHlsAdPlayer(contentVideo, options) {
2270
2692
  adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
2271
2693
  console.error("[HlsAdPlayer] HLS error:", data);
2272
2694
  if (data.fatal) {
2273
- handleAdError();
2695
+ var _data_response, _data_response1, _data_frag;
2696
+ var vastErrorCode = data.type === import_hls.default.ErrorTypes.NETWORK_ERROR ? 401 : VAST_ERROR_MEDIA_DISPLAY;
2697
+ logFunnel("hls_fatal", {
2698
+ reason: data.details,
2699
+ errorName: data.type,
2700
+ errorMessage: data.details,
2701
+ responseCode: (_data_response = data.response) === null || _data_response === void 0 ? void 0 : _data_response.code,
2702
+ responseText: (_data_response1 = data.response) === null || _data_response1 === void 0 ? void 0 : _data_response1.text,
2703
+ fragUrl: (_data_frag = data.frag) === null || _data_frag === void 0 ? void 0 : _data_frag.url,
2704
+ vastErrorCode: vastErrorCode
2705
+ });
2706
+ recoverFromAdFailure(vastErrorCode);
2274
2707
  }
2275
2708
  });
2276
2709
  } else if (isHlsAd && adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
2710
+ logFunnel("media_load", {
2711
+ pipeline: "native-hls"
2712
+ });
2277
2713
  adVideoElement.src = mediaFile.url;
2278
2714
  startAdPlayback("native HLS ad playback");
2279
2715
  } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {
@@ -2281,45 +2717,47 @@ function createHlsAdPlayer(contentVideo, options) {
2281
2717
  adHls.destroy();
2282
2718
  adHls = void 0;
2283
2719
  }
2720
+ logFunnel("media_load", {
2721
+ pipeline: "progressive"
2722
+ });
2284
2723
  adVideoElement.src = mediaFile.url;
2285
2724
  adVideoElement.load();
2286
2725
  startAdPlayback("progressive ad playback");
2287
2726
  } else {
2727
+ clearMediaStartTimer();
2728
+ logFunnel("media_unsupported", {
2729
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA
2730
+ });
2288
2731
  throw new Error("Unsupported ad media file type: ".concat(mediaFile.type));
2289
2732
  }
2290
2733
  }
2291
2734
  function advanceToNextPodAd() {
2292
- if (podIndex >= podAds.length - 1) {
2293
- return false;
2294
- }
2295
- settleViewability();
2296
- podIndex++;
2297
- currentAd = podAds[podIndex];
2298
- currentAdMediaFile = void 0;
2299
- resetAdTracking();
2300
- if (currentAd) {
2301
- console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2302
- }
2303
- clearStallWatchdog();
2304
- if (requiresMediaPipelineResetAfterAds()) {
2305
- recreateAdVideoElement();
2306
- setupAdEventListeners();
2307
- } else {
2308
- prepareVideoElementForNewSource();
2309
- }
2310
- try {
2311
- loadCurrentAdMedia();
2312
- emit("pod_ad_started", {
2313
- index: podIndex,
2314
- total: podAds.length
2315
- });
2316
- return true;
2317
- } catch (error) {
2318
- console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2319
- return false;
2735
+ clearMediaStartTimer();
2736
+ while(podIndex < podAds.length - 1){
2737
+ settleViewability();
2738
+ podIndex++;
2739
+ currentAd = podAds[podIndex];
2740
+ currentAdMediaFile = void 0;
2741
+ resetAdTracking();
2742
+ if (currentAd) {
2743
+ console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2744
+ }
2745
+ resetVideoElementForNextSource();
2746
+ try {
2747
+ loadCurrentAdMedia();
2748
+ emit("pod_ad_started", {
2749
+ index: podIndex,
2750
+ total: podAds.length
2751
+ });
2752
+ return true;
2753
+ } catch (error) {
2754
+ console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2755
+ }
2320
2756
  }
2757
+ return false;
2321
2758
  }
2322
2759
  function clearStallWatchdog() {
2760
+ clearMediaStartTimer();
2323
2761
  if (stallWatchdogId != null) {
2324
2762
  clearInterval(stallWatchdogId);
2325
2763
  stallWatchdogId = void 0;
@@ -2335,11 +2773,10 @@ function createHlsAdPlayer(contentVideo, options) {
2335
2773
  function handleAdStall() {
2336
2774
  console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame");
2337
2775
  clearStallWatchdog();
2338
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2339
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2340
- return;
2341
- }
2342
- handleAdError();
2776
+ logFunnel("stall", {
2777
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2778
+ });
2779
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2343
2780
  }
2344
2781
  function getDecodedVideoFrameCount(video) {
2345
2782
  try {
@@ -2401,11 +2838,10 @@ function createHlsAdPlayer(contentVideo, options) {
2401
2838
  function handleVideoDecodeFailure() {
2402
2839
  console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative");
2403
2840
  clearStallWatchdog();
2404
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2405
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2406
- return;
2407
- }
2408
- handleAdError();
2841
+ logFunnel("decode_failure", {
2842
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2843
+ });
2844
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2409
2845
  }
2410
2846
  function startStallWatchdog() {
2411
2847
  clearStallWatchdog();
@@ -2529,6 +2965,15 @@ function createHlsAdPlayer(contentVideo, options) {
2529
2965
  Promise.reject(new Error("Ad already playing"))
2530
2966
  ];
2531
2967
  }
2968
+ if (destroyed) {
2969
+ return [
2970
+ 2,
2971
+ Promise.reject(new Error("Ad player destroyed"))
2972
+ ];
2973
+ }
2974
+ currentVastTagUrl = vastTagUrl;
2975
+ pendingRequestAbortReason = void 0;
2976
+ logFunnel("request_sent");
2532
2977
  _state.label = 1;
2533
2978
  case 1:
2534
2979
  _state.trys.push([
@@ -2563,8 +3008,18 @@ function createHlsAdPlayer(contentVideo, options) {
2563
3008
  ads = _state.sent();
2564
3009
  _state.label = 4;
2565
3010
  case 4:
3011
+ if (destroyed) {
3012
+ return [
3013
+ 2,
3014
+ Promise.reject(new Error("Ad player destroyed"))
3015
+ ];
3016
+ }
3017
+ if (!ads.length && pendingRequestAbortReason) {
3018
+ throw new Error(pendingRequestAbortReason);
3019
+ }
2566
3020
  if (!ads.length) {
2567
3021
  console.warn("[HlsAdPlayer] No ads available from VAST response");
3022
+ logFunnel("no_fill");
2568
3023
  emit("ad_error");
2569
3024
  return [
2570
3025
  2,
@@ -2575,6 +3030,23 @@ function createHlsAdPlayer(contentVideo, options) {
2575
3030
  podIndex = 0;
2576
3031
  currentAd = ads[0];
2577
3032
  currentAdMediaFile = void 0;
3033
+ logFunnel("vast_received", {
3034
+ adCount: ads.length,
3035
+ durations: ads.map(function(ad) {
3036
+ return ad.duration;
3037
+ }),
3038
+ impressionUrls: ads.map(function(ad) {
3039
+ return ad.trackingUrls.impression.length;
3040
+ })
3041
+ });
3042
+ ads.forEach(function(ad, index) {
3043
+ if (ad.trackingUrls.impression.length === 0) {
3044
+ logFunnel("vast_missing_impression", {
3045
+ adIndex: index,
3046
+ missingAdId: ad.id
3047
+ });
3048
+ }
3049
+ });
2578
3050
  console.log("[HlsAdPlayer] Pod parsed: ".concat(ads.length, ' ad(s), first="').concat(currentAd === null || currentAd === void 0 ? void 0 : currentAd.title, '", duration=').concat(currentAd === null || currentAd === void 0 ? void 0 : currentAd.duration, "s"));
2579
3051
  return [
2580
3052
  2,
@@ -2583,6 +3055,9 @@ function createHlsAdPlayer(contentVideo, options) {
2583
3055
  case 5:
2584
3056
  error = _state.sent();
2585
3057
  console.error("[HlsAdPlayer] Error requesting ads:", error);
3058
+ logFunnel("request_failed", {
3059
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3060
+ });
2586
3061
  emit("ad_error");
2587
3062
  return [
2588
3063
  2,
@@ -2638,13 +3113,22 @@ function createHlsAdPlayer(contentVideo, options) {
2638
3113
  adContainerEl.style.pointerEvents = "auto";
2639
3114
  }
2640
3115
  emit("content_pause");
2641
- loadCurrentAdMedia();
3116
+ try {
3117
+ loadCurrentAdMedia();
3118
+ } catch (loadError) {
3119
+ if (!(podIndex < podAds.length - 1 && advanceToNextPodAd())) {
3120
+ throw loadError;
3121
+ }
3122
+ }
2642
3123
  return [
2643
3124
  2,
2644
3125
  Promise.resolve()
2645
3126
  ];
2646
3127
  } catch (error) {
2647
3128
  console.error("[HlsAdPlayer] Error playing ad:", error);
3129
+ logFunnel("play_failed", {
3130
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3131
+ });
2648
3132
  handleAdError();
2649
3133
  return [
2650
3134
  2,
@@ -2686,6 +3170,9 @@ function createHlsAdPlayer(contentVideo, options) {
2686
3170
  var previousMutedState;
2687
3171
  return _ts_generator(this, function(_state) {
2688
3172
  console.log("[HlsAdPlayer] Stopping ad");
3173
+ if (adPlaying && currentAd && !trackingFired.impression) {
3174
+ logFunnel("stopped_before_start");
3175
+ }
2689
3176
  settleViewability();
2690
3177
  fireNotUsedForUnplayedAds();
2691
3178
  clearStallWatchdog();
@@ -2718,15 +3205,18 @@ function createHlsAdPlayer(contentVideo, options) {
2718
3205
  },
2719
3206
  destroy: function destroy() {
2720
3207
  console.log("[HlsAdPlayer] Destroying");
3208
+ if (adPlaying && currentAd && !trackingFired.impression) {
3209
+ logFunnel("stopped_before_start");
3210
+ }
2721
3211
  settleViewability();
2722
3212
  fireNotUsedForUnplayedAds();
2723
3213
  destroyed = true;
2724
- clearStallWatchdog();
3214
+ pendingRequestAbortReason = "Ad player destroyed";
2725
3215
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2726
3216
  try {
2727
- for(var _iterator = pendingTimeouts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2728
- var timeoutId = _step.value;
2729
- clearTimeout(timeoutId);
3217
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3218
+ var controller = _step.value;
3219
+ controller.abort();
2730
3220
  }
2731
3221
  } catch (err) {
2732
3222
  _didIteratorError = true;
@@ -2742,6 +3232,28 @@ function createHlsAdPlayer(contentVideo, options) {
2742
3232
  }
2743
3233
  }
2744
3234
  }
3235
+ pendingVastRequests.clear();
3236
+ clearStallWatchdog();
3237
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
3238
+ try {
3239
+ for(var _iterator1 = pendingTimeouts[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
3240
+ var timeoutId = _step1.value;
3241
+ clearTimeout(timeoutId);
3242
+ }
3243
+ } catch (err) {
3244
+ _didIteratorError1 = true;
3245
+ _iteratorError1 = err;
3246
+ } finally{
3247
+ try {
3248
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
3249
+ _iterator1.return();
3250
+ }
3251
+ } finally{
3252
+ if (_didIteratorError1) {
3253
+ throw _iteratorError1;
3254
+ }
3255
+ }
3256
+ }
2745
3257
  pendingTimeouts = [];
2746
3258
  adPlaying = false;
2747
3259
  setAdPlayingFlag(false);
@@ -2761,6 +3273,35 @@ function createHlsAdPlayer(contentVideo, options) {
2761
3273
  isAdPlaying: function isAdPlaying() {
2762
3274
  return adPlaying;
2763
3275
  },
3276
+ setFunnelContext: function setFunnelContext(context) {
3277
+ funnelContext = _object_spread({}, context);
3278
+ },
3279
+ abortPendingRequest: function abortPendingRequest() {
3280
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "VAST request aborted (timeout)";
3281
+ if (pendingVastRequests.size === 0) return;
3282
+ pendingRequestAbortReason = reason;
3283
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
3284
+ try {
3285
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3286
+ var controller = _step.value;
3287
+ controller.abort();
3288
+ }
3289
+ } catch (err) {
3290
+ _didIteratorError = true;
3291
+ _iteratorError = err;
3292
+ } finally{
3293
+ try {
3294
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
3295
+ _iterator.return();
3296
+ }
3297
+ } finally{
3298
+ if (_didIteratorError) {
3299
+ throw _iteratorError;
3300
+ }
3301
+ }
3302
+ }
3303
+ pendingVastRequests.clear();
3304
+ },
2764
3305
  resize: function resize(width, height) {
2765
3306
  console.log("[HlsAdPlayer] Resizing to ".concat(width, "x").concat(height));
2766
3307
  if (adContainerEl) {
@@ -2796,6 +3337,13 @@ function createHlsAdPlayer(contentVideo, options) {
2796
3337
  if (adVideoElement && adPlaying) {
2797
3338
  var clamped = Math.max(0, Math.min(1, volume));
2798
3339
  adVideoElement.volume = clamped;
3340
+ var userActivation = navigator.userActivation;
3341
+ if (clamped > 0 && forcedMuteByAutoplay && userActivation && !userActivation.isActive) {
3342
+ logFunnel("unmute_blocked_without_gesture", {
3343
+ requestedVolume: clamped
3344
+ });
3345
+ return;
3346
+ }
2799
3347
  adVideoElement.muted = clamped === 0;
2800
3348
  }
2801
3349
  },
@@ -6859,7 +7407,7 @@ var AdTimingService = /*#__PURE__*/ function() {
6859
7407
  {
6860
7408
  key: "adFitsRemainingBudget",
6861
7409
  value: function adFitsRemainingBudget(durationMs) {
6862
- if (durationMs <= 0) {
7410
+ if (durationMs <= 0 || this.expectedAdBreakDurationMs == null) {
6863
7411
  return true;
6864
7412
  }
6865
7413
  return durationMs <= this.getDurationBudgetRemainingMs();
@@ -6918,6 +7466,11 @@ var AdTimingService = /*#__PURE__*/ function() {
6918
7466
  value: function markAdStarted() {
6919
7467
  this.currentAdIndex++;
6920
7468
  this.totalAdsInBreak = this.currentAdIndex;
7469
+ }
7470
+ },
7471
+ {
7472
+ key: "noteAdRequestSent",
7473
+ value: function noteAdRequestSent() {
6921
7474
  this.totalAdRequestsInBreak++;
6922
7475
  this.lastAdRequestTime = Date.now();
6923
7476
  }
@@ -6969,6 +7522,9 @@ var AdTimingService = /*#__PURE__*/ function() {
6969
7522
  if (message.includes("timeout")) {
6970
7523
  return true;
6971
7524
  }
7525
+ if (message.includes("ad player destroyed") || message.includes("aborted")) {
7526
+ return true;
7527
+ }
6972
7528
  if (message.includes("rate limit") || message.includes("too many requests")) {
6973
7529
  return true;
6974
7530
  }
@@ -8102,6 +8658,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8102
8658
  this.adDetectSentForCurrentBreak = false;
8103
8659
  this.continuousFetchingActive = false;
8104
8660
  this.continuousFetchLoopRunning = false;
8661
+ this.breakFunnel = {};
8662
+ this.controllerCallInFlight = false;
8663
+ this.playbackStartedForCurrentRequest = false;
8664
+ this.opportunityEpoch = -1;
8105
8665
  this.adRequestQueue = [];
8106
8666
  this.adPodQueue = [];
8107
8667
  this.maxPlaceholderDurationMs = 5e3;
@@ -8154,7 +8714,25 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8154
8714
  adPlayer.on("ad_interaction", function(event) {
8155
8715
  if (event) _this.host.onAdInteraction(event);
8156
8716
  });
8717
+ adPlayer.on("ad_funnel", function(payload) {
8718
+ if (!(payload === null || payload === void 0 ? void 0 : payload.stage)) return;
8719
+ _this.countFunnelStage(payload.stage);
8720
+ if (payload.reason) {
8721
+ _this.countFunnelStage("".concat(payload.stage, ":").concat(payload.reason));
8722
+ }
8723
+ if (payload.stage === "impression_fired" && payload.pixelCount != null) {
8724
+ _this.countFunnelStage("impression_urls", payload.pixelCount);
8725
+ }
8726
+ if (payload.visibilityState === "hidden") {
8727
+ _this.countFunnelStage("while_hidden");
8728
+ }
8729
+ });
8157
8730
  adPlayer.on("ad_impression", function() {
8731
+ _this.timing.consecutiveFailures = 0;
8732
+ if (!_this.playbackStartedForCurrentRequest) {
8733
+ _this.playbackStartedForCurrentRequest = true;
8734
+ _this.timing.markAdStarted();
8735
+ }
8158
8736
  sendAdImpressionTracking(_this.host.config.licenseKey, _object_spread_props(_object_spread({
8159
8737
  source: "hls",
8160
8738
  adIndex: _this.timing.currentAdIndex
@@ -8198,6 +8776,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8198
8776
  }
8199
8777
  }
8200
8778
  console.error("[AD-ERROR]", errorMessage, errorPayload || "");
8779
+ if (_this.controllerCallInFlight) {
8780
+ _this.timing.recordGamNoFill();
8781
+ return;
8782
+ }
8201
8783
  _this.handleAdFailure();
8202
8784
  });
8203
8785
  adPlayer.on("content_pause", function() {
@@ -8269,6 +8851,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8269
8851
  }
8270
8852
  var preservedMutedState = adPlayer.getOriginalMutedState();
8271
8853
  var preservedVolumeState = adPlayer.getOriginalVolume();
8854
+ this.playbackStartedForCurrentRequest = false;
8272
8855
  if (adPlayer) {
8273
8856
  try {
8274
8857
  adPlayer.destroy();
@@ -8358,9 +8941,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8358
8941
  if (this.timing.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {
8359
8942
  this.timing.expectedAdBreakDurationMs = adBreakDurationMs;
8360
8943
  }
8944
+ this.noteOpportunity("scte35", this.cueManager.activeScte35BreakKey);
8361
8945
  return [
8362
8946
  4,
8363
- this.startOptimizedPod(baseVastUrl, adBreakDurationMs, currentMuted, currentVolume)
8947
+ this.startOptimizedPod(baseVastUrl, adBreakDurationMs)
8364
8948
  ];
8365
8949
  case 1:
8366
8950
  podPlayed = _state.sent();
@@ -8394,7 +8978,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8394
8978
  value: // ───────────────────────────────────────────────────────────────
8395
8979
  // Optimized pod (single multi-ad request)
8396
8980
  // ───────────────────────────────────────────────────────────────
8397
- function startOptimizedPod(baseVastUrl, breakDurationMs, currentMuted, currentVolume) {
8981
+ function startOptimizedPod(baseVastUrl, breakDurationMs) {
8398
8982
  return _async_to_generator(function() {
8399
8983
  var podUrl, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
8400
8984
  return _ts_generator(this, function(_state) {
@@ -8433,10 +9017,13 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8433
9017
  case 2:
8434
9018
  _state.sent();
8435
9019
  this.timing.startAdRequestWatchdog(requestToken);
8436
- this.timing.lastAdRequestTime = Date.now();
9020
+ this.timing.noteAdRequestSent();
9021
+ this.beginFunnelRequest(adPlayer, requestToken);
8437
9022
  return [
8438
9023
  4,
8439
- adPlayer.requestAds(podUrl)
9024
+ this.callController(function() {
9025
+ return adPlayer.requestAds(podUrl);
9026
+ })
8440
9027
  ];
8441
9028
  case 3:
8442
9029
  _state.sent();
@@ -8465,16 +9052,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8465
9052
  this.timing.startAdFailsafeTimer(requestToken);
8466
9053
  return [
8467
9054
  4,
8468
- adPlayer.play()
9055
+ this.callController(function() {
9056
+ return adPlayer.play();
9057
+ })
8469
9058
  ];
8470
9059
  case 4:
8471
9060
  _state.sent();
8472
- this.timing.markAdStarted();
8473
9061
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
8474
9062
  this.timing.scheduleAdStopAtBreakBoundary();
8475
9063
  }
8476
- adPlayer.setAdVolume(currentMuted ? 0 : currentVolume);
8477
- this.timing.consecutiveFailures = 0;
9064
+ adPlayer.setAdVolume(getAdAudioVolume(adPlayer));
8478
9065
  this.continuousFetchingActive = true;
8479
9066
  this.startContinuousFetching(baseVastUrl);
8480
9067
  return [
@@ -8839,7 +9426,6 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8839
9426
  ];
8840
9427
  case 3:
8841
9428
  _state.sent();
8842
- this.timing.consecutiveFailures = 0;
8843
9429
  return [
8844
9430
  3,
8845
9431
  8
@@ -8852,6 +9438,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8852
9438
  3,
8853
9439
  6
8854
9440
  ];
9441
+ this.timing.consecutiveFailures++;
8855
9442
  return [
8856
9443
  4,
8857
9444
  this.tryNextAvailableAdWithRateLimit()
@@ -8943,11 +9530,137 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8943
9530
  }
8944
9531
  }
8945
9532
  },
9533
+ {
9534
+ key: "countFunnelStage",
9535
+ value: function countFunnelStage(stage) {
9536
+ var amount = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1;
9537
+ var _this_breakFunnel_stage;
9538
+ this.breakFunnel[stage] = ((_this_breakFunnel_stage = this.breakFunnel[stage]) !== null && _this_breakFunnel_stage !== void 0 ? _this_breakFunnel_stage : 0) + amount;
9539
+ }
9540
+ },
9541
+ {
9542
+ key: "logOrchestratorFunnel",
9543
+ value: function logOrchestratorFunnel(stage) {
9544
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
9545
+ this.countFunnelStage(stage);
9546
+ console.log("[AdBreak][FUNNEL] ".concat(stage), _object_spread({
9547
+ breakId: this.timing.adBreakEpoch,
9548
+ requestId: this.currentRequestId,
9549
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0
9550
+ }, extra));
9551
+ }
9552
+ },
9553
+ {
9554
+ key: "noteOpportunity",
9555
+ value: function noteOpportunity(source, breakKey) {
9556
+ if (breakKey && breakKey === this.opportunityBreakKey && this.opportunityEpoch === this.timing.adBreakEpoch) {
9557
+ this.logOrchestratorFunnel("duplicate_break_start", {
9558
+ source: source,
9559
+ breakKey: breakKey
9560
+ });
9561
+ return;
9562
+ }
9563
+ this.opportunityBreakKey = breakKey;
9564
+ this.opportunityEpoch = this.timing.adBreakEpoch;
9565
+ this.logOrchestratorFunnel("opportunity_created", {
9566
+ source: source,
9567
+ breakKey: breakKey,
9568
+ expectedDurationMs: this.timing.expectedAdBreakDurationMs
9569
+ });
9570
+ }
9571
+ },
9572
+ {
9573
+ key: "beginFunnelRequest",
9574
+ value: function beginFunnelRequest(adPlayer, requestToken) {
9575
+ var _adPlayer_setFunnelContext;
9576
+ if (this.controllerCallInFlight) {
9577
+ this.logOrchestratorFunnel("duplicate_request_detected", {
9578
+ newRequestId: requestToken
9579
+ });
9580
+ }
9581
+ this.currentRequestId = requestToken;
9582
+ this.requestStartedAt = Date.now();
9583
+ (_adPlayer_setFunnelContext = adPlayer.setFunnelContext) === null || _adPlayer_setFunnelContext === void 0 ? void 0 : _adPlayer_setFunnelContext.call(adPlayer, {
9584
+ breakId: this.timing.adBreakEpoch,
9585
+ requestId: requestToken
9586
+ });
9587
+ }
9588
+ },
9589
+ {
9590
+ key: "isAdLoadingWithoutPlayback",
9591
+ value: function isAdLoadingWithoutPlayback() {
9592
+ return this.host.getAdPlayer().isAdPlaying() && !this.playbackStartedForCurrentRequest;
9593
+ }
9594
+ },
9595
+ {
9596
+ key: "noteStopBeforeStart",
9597
+ value: function noteStopBeforeStart(reason) {
9598
+ if (!this.isAdLoadingWithoutPlayback()) return;
9599
+ this.logOrchestratorFunnel("ad_stopped_before_start", {
9600
+ reason: reason,
9601
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9602
+ });
9603
+ }
9604
+ },
9605
+ {
9606
+ key: "handleRequestWatchdogTimeout",
9607
+ value: function handleRequestWatchdogTimeout() {
9608
+ var adPlayer = this.host.getAdPlayer();
9609
+ if (this.controllerCallInFlight && adPlayer.abortPendingRequest) {
9610
+ this.logOrchestratorFunnel("request_aborted_timeout", {
9611
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9612
+ });
9613
+ adPlayer.abortPendingRequest("VAST request aborted after request watchdog timeout");
9614
+ return;
9615
+ }
9616
+ this.handleAdFailure();
9617
+ }
9618
+ },
9619
+ {
9620
+ key: "callController",
9621
+ value: function callController(call) {
9622
+ return _async_to_generator(function() {
9623
+ return _ts_generator(this, function(_state) {
9624
+ switch(_state.label){
9625
+ case 0:
9626
+ this.controllerCallInFlight = true;
9627
+ _state.label = 1;
9628
+ case 1:
9629
+ _state.trys.push([
9630
+ 1,
9631
+ ,
9632
+ 3,
9633
+ 4
9634
+ ]);
9635
+ return [
9636
+ 4,
9637
+ call()
9638
+ ];
9639
+ case 2:
9640
+ _state.sent();
9641
+ return [
9642
+ 3,
9643
+ 4
9644
+ ];
9645
+ case 3:
9646
+ this.controllerCallInFlight = false;
9647
+ return [
9648
+ 7
9649
+ ];
9650
+ case 4:
9651
+ return [
9652
+ 2
9653
+ ];
9654
+ }
9655
+ });
9656
+ }).call(this);
9657
+ }
9658
+ },
8946
9659
  {
8947
9660
  key: "playSingleAd",
8948
9661
  value: function playSingleAd(vastTagUrl) {
8949
9662
  return _async_to_generator(function() {
8950
- var adPlayer, requestToken, ap, requestUrl, playError, error, errorMessage;
9663
+ var adPlayer, requestToken, ap, requestUrl, _ap_getLoadedAdDuration, adDurationS, remainingMs, playError, error, errorMessage;
8951
9664
  return _ts_generator(this, function(_state) {
8952
9665
  switch(_state.label){
8953
9666
  case 0:
@@ -8989,13 +9702,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8989
9702
  case 2:
8990
9703
  _state.sent();
8991
9704
  this.timing.startAdRequestWatchdog(requestToken);
8992
- this.timing.lastAdRequestTime = Date.now();
9705
+ this.timing.noteAdRequestSent();
8993
9706
  ap = this.host.getAdPlayer();
8994
9707
  requestUrl = this.withCurrentPodBudget(vastTagUrl);
8995
9708
  this.currentVastUrl = requestUrl;
9709
+ this.beginFunnelRequest(ap, requestToken);
8996
9710
  return [
8997
9711
  4,
8998
- ap.requestAds(requestUrl)
9712
+ this.callController(function() {
9713
+ return ap.requestAds(requestUrl);
9714
+ })
8999
9715
  ];
9000
9716
  case 3:
9001
9717
  _state.sent();
@@ -9009,6 +9725,14 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9009
9725
  2
9010
9726
  ];
9011
9727
  if (!this.timing.ensureLoadedAdFitsBudget(ap)) {
9728
+ ;
9729
+ adDurationS = (_ap_getLoadedAdDuration = ap.getLoadedAdDuration) === null || _ap_getLoadedAdDuration === void 0 ? void 0 : _ap_getLoadedAdDuration.call(ap);
9730
+ remainingMs = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
9731
+ this.logOrchestratorFunnel("discarded_budget", {
9732
+ vastUrl: requestUrl,
9733
+ adDurationMs: adDurationS != null ? adDurationS * 1e3 : void 0,
9734
+ remainingMs: remainingMs
9735
+ });
9012
9736
  this.timing.rejectLoadedAdForDuration(ap);
9013
9737
  this.recreateAdController();
9014
9738
  throw new Error("ad_duration_exceeds_budget");
@@ -9024,16 +9748,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9024
9748
  this.timing.startAdFailsafeTimer(requestToken);
9025
9749
  return [
9026
9750
  4,
9027
- ap.play()
9751
+ this.callController(function() {
9752
+ return ap.play();
9753
+ })
9028
9754
  ];
9029
9755
  case 5:
9030
9756
  _state.sent();
9031
- this.timing.markAdStarted();
9032
9757
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
9033
9758
  this.timing.scheduleAdStopAtBreakBoundary();
9034
9759
  }
9035
9760
  ap.setAdVolume(getAdAudioVolume(ap));
9036
- this.timing.consecutiveFailures = 0;
9037
9761
  this.timing.temporaryFailureUrls.delete(vastTagUrl);
9038
9762
  return [
9039
9763
  3,
@@ -9197,7 +9921,6 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9197
9921
  ];
9198
9922
  case 5:
9199
9923
  _state.sent();
9200
- this.timing.consecutiveFailures = 0;
9201
9924
  return [
9202
9925
  3,
9203
9926
  10
@@ -9209,6 +9932,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9209
9932
  3,
9210
9933
  8
9211
9934
  ];
9935
+ this.timing.consecutiveFailures++;
9212
9936
  return [
9213
9937
  4,
9214
9938
  this.tryNextAvailableAdWithRateLimit()
@@ -9259,6 +9983,67 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9259
9983
  // ───────────────────────────────────────────────────────────────
9260
9984
  // Ad break completion
9261
9985
  // ───────────────────────────────────────────────────────────────
9986
+ key: "logBreakFunnel",
9987
+ value: function logBreakFunnel() {
9988
+ var funnel = this.breakFunnel;
9989
+ this.breakFunnel = {};
9990
+ if (Object.keys(funnel).length === 0) return;
9991
+ var count = function count(stage) {
9992
+ var _funnel_stage;
9993
+ return (_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0;
9994
+ };
9995
+ var breakId = this.opportunityEpoch;
9996
+ if (count("request_sent") > 0 && count("impression_fired") === 0) {
9997
+ console.log("[AdBreak][FUNNEL] break_abandoned_before_start", {
9998
+ breakId: breakId,
9999
+ requests: count("request_sent")
10000
+ });
10001
+ }
10002
+ console.log("[AdBreak][FUNNEL] Break summary", {
10003
+ breakId: breakId,
10004
+ opportunities: count("opportunity_created"),
10005
+ requests: count("request_sent"),
10006
+ duplicates: count("duplicate_request_detected") + count("duplicate_break_start"),
10007
+ filled: count("vast_received"),
10008
+ noFill: count("no_fill"),
10009
+ requestFailed: count("request_failed"),
10010
+ requestAbortedTimeout: count("request_aborted_timeout"),
10011
+ credentialsRetries: count("vast_credentials_retry"),
10012
+ wrapperFailures: count("wrapper_fetch:failure"),
10013
+ noSupportedMedia: count("vast_no_supported_media"),
10014
+ vpaidOnly: count("vast_no_supported_media:vpaid_only"),
10015
+ missingImpression: count("vast_missing_impression"),
10016
+ discardedBudget: count("discarded_budget"),
10017
+ mediaCandidates: count("media_candidate:accepted") + count("media_candidate:rejected"),
10018
+ mediaRejected: count("media_candidate:rejected"),
10019
+ mediaFallbacks: count("media_fallback"),
10020
+ playCalled: count("play_called"),
10021
+ playRejected: count("play_rejected"),
10022
+ mutedRetry: count("muted_retry"),
10023
+ startTimeouts: count("play_resolved_but_never_started"),
10024
+ impressions: count("impression_fired"),
10025
+ impressionUrls: count("impression_urls"),
10026
+ trackingRequests: count("tracking_request_created"),
10027
+ trackingNotLoaded: count("tracking_request_settled:error") + count("tracking_request_settled:timeout"),
10028
+ trackingUnexpandedMacros: count("tracking_url_unexpanded_macro"),
10029
+ trackingInvalidUrls: count("tracking_url_invalid"),
10030
+ vastAdFallbacks: count("vast_ad_fallback"),
10031
+ mediaEvents: count("media_event"),
10032
+ quartile25: count("first_quartile"),
10033
+ quartile50: count("midpoint"),
10034
+ quartile75: count("third_quartile"),
10035
+ complete: count("complete"),
10036
+ stoppedBeforeStart: count("stopped_before_start"),
10037
+ stoppedBeforeStartByBreakEnd: count("ad_stopped_before_start"),
10038
+ unexpectedUnmutes: count("unexpected_unmute"),
10039
+ unmuteBlocked: count("unmute_blocked_without_gesture"),
10040
+ visibilityHidden: count("while_hidden"),
10041
+ playbackFailures: count("play_failed") + count("media_error") + count("hls_fatal") + count("stall") + count("decode_failure") + count("media_unsupported"),
10042
+ stages: funnel
10043
+ });
10044
+ }
10045
+ },
10046
+ {
9262
10047
  key: "handleAdPodComplete",
9263
10048
  value: function handleAdPodComplete() {
9264
10049
  if (this.debug) {
@@ -9279,6 +10064,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9279
10064
  this.adPodQueue = [];
9280
10065
  this.showAds = false;
9281
10066
  this.host.getAdPlayer().stop().catch(function() {});
10067
+ this.logBreakFunnel();
9282
10068
  var restoredMuted = this.host.getAdPlayer().getOriginalMutedState();
9283
10069
  var restoredVolume = this.host.getAdPlayer().getOriginalVolume();
9284
10070
  if (this.host.video.muted !== restoredMuted) {
@@ -9630,7 +10416,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9630
10416
  _this.startScte35AdBreak(marker, cueKey, marker.durationSeconds != null ? marker.durationSeconds * 1e3 : _this.timing.expectedAdBreakDurationMs);
9631
10417
  },
9632
10418
  onWatchdogTimeout: function onWatchdogTimeout() {
9633
- return _this.adBreak.handleAdFailure();
10419
+ return _this.adBreak.handleRequestWatchdogTimeout();
9634
10420
  },
9635
10421
  onFailsafeTimeout: function onFailsafeTimeout() {
9636
10422
  return _this.adBreak.handleAdFailure();
@@ -9735,6 +10521,8 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9735
10521
  licenseKey: this.config.licenseKey
9736
10522
  } : {}, ((_this_hlsEngine = this.hlsEngine) === null || _this_hlsEngine === void 0 ? void 0 : _this_hlsEngine.hls) ? {
9737
10523
  mainHlsInstance: this.hlsEngine.hls
10524
+ } : {}, this.config.adMediaStartTimeoutMs != null ? {
10525
+ mediaStartTimeoutMs: this.config.adMediaStartTimeoutMs
9738
10526
  } : {}));
9739
10527
  }
9740
10528
  },
@@ -10089,6 +10877,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10089
10877
  this.timing.clearAdStartTimer();
10090
10878
  this.timing.clearAdStopTimer();
10091
10879
  if (adPlaying) {
10880
+ this.adBreak.noteStopBeforeStart("scte_end");
10092
10881
  this.adPlayer.stop().catch(function() {});
10093
10882
  }
10094
10883
  this.adBreak.handleAdPodComplete();
@@ -10128,6 +10917,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10128
10917
  console.log("[StormcloudVideoPlayer] Ad break boundary reached (overrun=".concat(overrunMs, "ms) - hard-stopping ads and resuming stream"));
10129
10918
  }
10130
10919
  if (adPlaying) {
10920
+ this.adBreak.noteStopBeforeStart("break_boundary");
10131
10921
  this.adPlayer.stop().catch(function() {});
10132
10922
  }
10133
10923
  this.adBreak.handleAdPodComplete();
@@ -10256,6 +11046,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10256
11046
  this.adBreak.showAds = true;
10257
11047
  this.adBreak.inAdBreak = true;
10258
11048
  this.timing.currentAdBreakStartWallClockMs = Date.now();
11049
+ if (durationMs > 0) {
11050
+ this.timing.setAdBreakDurationBoundary(durationMs);
11051
+ }
11052
+ this.adBreak.noteOpportunity("vmap", key);
10259
11053
  _state.label = 1;
10260
11054
  case 1:
10261
11055
  _state.trys.push([