+/* This stores a string in buf with the correct encoding and also sets the
+ * first byte as the length. !str is accepted for an empty string.
+ * If the string is already encoded, invalid UTF-8 or has no multibyte sequence
+ * then we keep it as is, otherwise we signal UTF-8 encoding. */
+static int encode_str8(uint8_t *buf, const char *str)
+{
+ size_t str_len;
+ if (!str)
+ str = "";
+ str_len = strlen(str);
+ if (str[0] && (unsigned)str[0] >= 0x20) { /* Make sure the string is not already encoded. */
+ const uint8_t *q = str;
+ int has_multibyte = 0;
+ while (*q) {
+ uint32_t code;
+ GET_UTF8(code, *q++, goto invalid;) /* Is it valid UTF-8? */
+ has_multibyte |= (code > 127); /* Does it have multibyte UTF-8 chars in it? */
+ }
+ if (has_multibyte) { /* If we have multibyte chars and valid UTF-8, then encode as such! */
+ if (str_len > 254)
+ return AVERROR(EINVAL);
+ buf[0] = str_len + 1;
+ buf[1] = 0x15;
+ memcpy(&buf[2], str, str_len);
+ return 0;
+ }
+ }
+invalid:
+ /* Otherwise let's just encode the string as is! */
+ if (str_len > 255)
+ return AVERROR(EINVAL);
+ buf[0] = str_len;
+ memcpy(&buf[1], str, str_len);
+ return 0;
+}
+
+static MpegTSService *mpegts_add_service(AVFormatContext *s, int sid,