[FFmpeg-devel] [PATCH] Matroid patch: add support for writing additional metadata to filename

tak-matroid tak at thematroid.com
Wed Mar 10 03:50:33 EET 2021


* Support micro seconds for image2 strftime filename
* Support micro seconds for segment strftime filename
* Support duration for segment output

Signed-off-by: tak-matroid <tak at matroid.com>
---
 libavformat/avformat.h |  7 ++++-
 libavformat/img2enc.c  | 40 +++++++++++++++++----------
 libavformat/segment.c  | 61 +++++++++++++++++++++++++++++++++++++-----
 libavformat/utils.c    | 38 +++++++++++++++++++++++---
 libavutil/time.c       | 17 ++++++++++++
 libavutil/time.h       | 11 ++++++++
 6 files changed, 149 insertions(+), 25 deletions(-)

diff --git a/libavformat/avformat.h b/libavformat/avformat.h
index 7da2f3d98e..f5084f622c 100644
--- a/libavformat/avformat.h
+++ b/libavformat/avformat.h
@@ -2808,10 +2808,15 @@ void av_dump_format(AVFormatContext *ic,
  * @param path numbered sequence string
  * @param number frame number
  * @param flags AV_FRAME_FILENAME_FLAGS_*
+ * @param ts frame pts in AV_TIME_BASE_Q
+ * @param duration duration of segment
  * @return 0 if OK, -1 on format error
  */
+int av_get_frame_filename3(char *buf, int buf_size,
+                          const char *path, int number, int flags, int64_t ts, double duration);
+
 int av_get_frame_filename2(char *buf, int buf_size,
-                          const char *path, int number, int flags);
+                          const char *path, int number, int flags, int64_t ts);
 
 int av_get_frame_filename(char *buf, int buf_size,
                           const char *path, int number);
diff --git a/libavformat/img2enc.c b/libavformat/img2enc.c
index 0f7a21ffa0..37118d02fc 100644
--- a/libavformat/img2enc.c
+++ b/libavformat/img2enc.c
@@ -27,7 +27,9 @@
 #include "libavutil/log.h"
 #include "libavutil/opt.h"
 #include "libavutil/pixdesc.h"
+#include "libavutil/time.h"
 #include "libavutil/time_internal.h"
+#include <sys/time.h>
 #include "avformat.h"
 #include "avio_internal.h"
 #include "internal.h"
@@ -130,31 +132,40 @@ static int write_packet(AVFormatContext *s, AVPacket *pkt)
     VideoMuxData *img = s->priv_data;
     AVIOContext *pb[4] = {0};
     char filename[1024];
-    AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
+    AVStream *stream = s->streams[pkt->stream_index];
+    AVCodecParameters *par = stream->codecpar;
     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(par->format);
     int ret, i;
     int nb_renames = 0;
+    int64_t ts = av_rescale_q(pkt->pts, stream->time_base, AV_TIME_BASE_Q);
     AVDictionary *options = NULL;
 
     if (img->update) {
         av_strlcpy(filename, img->path, sizeof(filename));
-    } else if (img->use_strftime) {
-        time_t now0;
-        struct tm *tm, tmpbuf;
-        time(&now0);
-        tm = localtime_r(&now0, &tmpbuf);
-        if (!strftime(filename, sizeof(filename), img->path, tm)) {
-            av_log(s, AV_LOG_ERROR, "Could not get frame filename with strftime\n");
-            return AVERROR(EINVAL);
+    } else if (img->use_strftime || img->frame_pts) {
+        char temp_name[sizeof(filename)];
+        if (img->use_strftime) {
+            struct timeval tv;
+            gettimeofday(&tv, NULL);
+            if (!av_strftime_micro(temp_name, sizeof(temp_name), img->path, &tv)) {
+                av_log(s, AV_LOG_ERROR, "Could not get frame filename with strftime\n");
+                return AVERROR(EINVAL);
+            }
+        } else {
+            av_strlcpy(temp_name, img->path, sizeof(temp_name));
         }
-    } else if (img->frame_pts) {
-        if (av_get_frame_filename2(filename, sizeof(filename), img->path, pkt->pts, AV_FRAME_FILENAME_FLAGS_MULTIPLE) < 0) {
-            av_log(s, AV_LOG_ERROR, "Cannot write filename by pts of the frames.");
-            return AVERROR(EINVAL);
+
+        if (img->frame_pts) {
+            if (av_get_frame_filename2(filename, sizeof(filename), temp_name, pkt->pts, AV_FRAME_FILENAME_FLAGS_MULTIPLE, ts) < 0) {
+                av_log(s, AV_LOG_ERROR, "Cannot write filename by pts of the frames.");
+                return AVERROR(EINVAL);
+            }
+        } else {
+            av_strlcpy(filename, temp_name, sizeof(filename));
         }
     } else if (av_get_frame_filename2(filename, sizeof(filename), img->path,
                                       img->img_number,
-                                      AV_FRAME_FILENAME_FLAGS_MULTIPLE) < 0 &&
+                                      AV_FRAME_FILENAME_FLAGS_MULTIPLE, ts) < 0 &&
                img->img_number > 1) {
         av_log(s, AV_LOG_ERROR,
                "Could not get frame filename number %d from pattern '%s'. "
@@ -162,6 +173,7 @@ static int write_packet(AVFormatContext *s, AVPacket *pkt)
                img->img_number, img->path);
         return AVERROR(EINVAL);
     }
+
     for (i = 0; i < 4; i++) {
         av_dict_copy(&options, img->protocol_opts, 0);
         snprintf(img->tmp[i], sizeof(img->tmp[i]), "%s.tmp", filename);
diff --git a/libavformat/segment.c b/libavformat/segment.c
index dff3d0ed48..f4ad3ccceb 100644
--- a/libavformat/segment.c
+++ b/libavformat/segment.c
@@ -41,7 +41,9 @@
 #include "libavutil/time.h"
 #include "libavutil/timecode.h"
 #include "libavutil/time_internal.h"
+#include <sys/time.h>
 #include "libavutil/timestamp.h"
+#include "libavutil/avstring.h"
 
 typedef struct SegmentListEntry {
     int index;
@@ -118,6 +120,8 @@ typedef struct SegmentContext {
     int   write_empty;
 
     int use_rename;
+    int use_pts;
+    int64_t segment_ts;
     char temp_list_filename[1024];
 
     SegmentListEntry cur_entry;
@@ -204,19 +208,23 @@ static int set_segment_filename(AVFormatContext *s)
     if (seg->segment_idx_wrap)
         seg->segment_idx %= seg->segment_idx_wrap;
     if (seg->use_strftime) {
-        time_t now0;
-        struct tm *tm, tmpbuf;
-        time(&now0);
-        tm = localtime_r(&now0, &tmpbuf);
-        if (!strftime(buf, sizeof(buf), s->url, tm)) {
-            av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
+        struct timeval tv;
+        gettimeofday(&tv, NULL);
+        if (!av_strftime_micro(buf, sizeof(buf), s->url, &tv)) {
+            av_log(s, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
             return AVERROR(EINVAL);
         }
+    } else if (seg->use_pts)  {
+        av_strlcpy(buf, s->url, sizeof(buf));
     } else if (av_get_frame_filename(buf, sizeof(buf),
                                      s->url, seg->segment_idx) < 0) {
         av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->url);
         return AVERROR(EINVAL);
     }
+
+    if (seg->use_pts)
+        av_strlcat(buf, ".tmp", sizeof(buf));
+
     new_name = av_strdup(buf);
     if (!new_name)
         return AVERROR(ENOMEM);
@@ -251,6 +259,7 @@ static int segment_start(AVFormatContext *s, int write_header)
     }
 
     seg->segment_idx++;
+    seg->segment_ts = -1;
     if ((seg->segment_idx_wrap) && (seg->segment_idx % seg->segment_idx_wrap == 0))
         seg->segment_idx_wrap_nb++;
 
@@ -374,6 +383,34 @@ static int segment_end(AVFormatContext *s, int write_trailer, int is_last)
         av_log(s, AV_LOG_ERROR, "Failure occurred when ending segment '%s'\n",
                oc->url);
 
+    if (seg->use_pts) {
+        char final_name[1024];
+        if (av_get_frame_filename3(final_name, sizeof(final_name), seg->cur_entry.filename,
+                                   0, AV_FRAME_FILENAME_FLAGS_MULTIPLE, seg->segment_ts,
+                                   seg->cur_entry.end_time - seg->cur_entry.start_time) < 0) {
+            av_log(s, AV_LOG_ERROR, "Cannot rename filename by pts of the frames.");
+            return AVERROR(EINVAL);
+        }
+        // remove .tmp
+        final_name[strlen(final_name) - 4] = '\0';
+
+        char *url, *src, *dst;
+        if (!(url = av_strdup(oc->url)))
+            return AVERROR(ENOMEM);
+        const char *dir = av_dirname(url);
+        if (!(src = av_append_path_component(dir, seg->cur_entry.filename)) ||
+            !(dst = av_append_path_component(dir, final_name)))
+            return AVERROR(ENOMEM);
+        if (ff_rename(src, dst, s))
+            return AVERROR(EINVAL);
+
+        av_free(url); av_free(src); av_free(dst);
+        size_t len = strlen(final_name) + 1;
+        if ((ret = av_reallocp(&seg->cur_entry.filename, len)) < 0)
+            return ret;
+        av_strlcpy(seg->cur_entry.filename, final_name, len);
+    }
+
     if (seg->list) {
         if (seg->list_size || seg->list_type == LIST_TYPE_M3U8) {
             SegmentListEntry *entry = av_mallocz(sizeof(*entry));
@@ -685,6 +722,7 @@ static int seg_init(AVFormatContext *s)
     int i;
 
     seg->segment_count = 0;
+    seg->segment_ts = -1;
     if (!seg->write_header_trailer)
         seg->individual_header_trailer = 0;
 
@@ -872,6 +910,15 @@ static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)
     }
 
 calc_times:
+    if (pkt->stream_index == seg->reference_stream_index) {
+        if (seg->use_pts) {
+            if (pkt->pts != AV_NOPTS_VALUE && (seg->segment_ts < 0 ||
+                av_compare_ts(pkt->pts, st->time_base, seg->segment_ts, AV_TIME_BASE_Q) < 0)) {
+                seg->segment_ts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
+            }
+        }
+    }
+
     if (seg->times) {
         end_pts = seg->segment_count < seg->nb_times ?
             seg->times[seg->segment_count] : INT64_MAX;
@@ -1045,7 +1092,7 @@ static const AVOption options[] = {
     { "strftime",          "set filename expansion with strftime at segment creation", OFFSET(use_strftime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
     { "increment_tc", "increment timecode between each segment", OFFSET(increment_tc), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
     { "break_non_keyframes", "allow breaking segments on non-keyframes", OFFSET(break_non_keyframes), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
-
+    { "frame_pts", "use current frame pts for filename", OFFSET(use_pts), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
     { "individual_header_trailer", "write header/trailer to each segment", OFFSET(individual_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
     { "write_header_trailer", "write a header to the first segment and a trailer to the last one", OFFSET(write_header_trailer), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, E },
     { "reset_timestamps", "reset timestamps at the beginning of each segment", OFFSET(reset_timestamps), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E },
diff --git a/libavformat/utils.c b/libavformat/utils.c
index 36164e0f0d..f4f6eabddb 100644
--- a/libavformat/utils.c
+++ b/libavformat/utils.c
@@ -20,6 +20,7 @@
  */
 
 #include <stdint.h>
+#include <ctype.h>
 
 #include "config.h"
 
@@ -4701,10 +4702,17 @@ uint64_t ff_get_formatted_ntp_time(uint64_t ntp_time_us)
     return ntp_ts;
 }
 
-int av_get_frame_filename2(char *buf, int buf_size, const char *path, int number, int flags)
+int av_get_frame_filename2(char *buf, int buf_size, const char *path,
+                           int number, int flags, int64_t ts)
+{
+    return av_get_frame_filename3(buf, buf_size, path, number, flags, ts, 0);
+}
+
+int av_get_frame_filename3(char *buf, int buf_size, const char *path,
+                           int number, int flags, int64_t ts, double duration)
 {
     const char *p;
-    char *q, buf1[20], c;
+    char *q, buf1[32], c;
     int nd, len, percentd_found;
 
     q = buf;
@@ -4741,6 +4749,30 @@ int av_get_frame_filename2(char *buf, int buf_size, const char *path, int number
                 memcpy(q, buf1, len);
                 q += len;
                 break;
+            case 't':
+                if (!(flags & AV_FRAME_FILENAME_FLAGS_MULTIPLE) && percentd_found)
+                    goto fail;
+                percentd_found = 1;
+                int64_t seconds   = ts / AV_TIME_BASE;
+                int64_t microsecs = ts % AV_TIME_BASE;
+                snprintf(buf1, sizeof(buf1), "%010" PRId64 ".%06" PRId64, seconds, microsecs);
+                len = strlen(buf1);
+                if ((q - buf + len) > buf_size - 1)
+                    goto fail;
+                memcpy(q, buf1, len);
+                q += len;
+                break;
+            case 'l':
+                if (!(flags & AV_FRAME_FILENAME_FLAGS_MULTIPLE) && percentd_found)
+                    goto fail;
+                percentd_found = 1;
+                snprintf(buf1, sizeof(buf1), "%017.6f", duration);
+                len = strlen(buf1);
+                if ((q - buf + len) > buf_size - 1)
+                    goto fail;
+                memcpy(q, buf1, len);
+                q += len;
+                break;
             default:
                 goto fail;
             }
@@ -4761,7 +4793,7 @@ fail:
 
 int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
 {
-    return av_get_frame_filename2(buf, buf_size, path, number, 0);
+    return av_get_frame_filename2(buf, buf_size, path, number, 0, 0);
 }
 
 void av_url_split(char *proto, int proto_size,
diff --git a/libavutil/time.c b/libavutil/time.c
index 740afc4785..54152173a6 100644
--- a/libavutil/time.c
+++ b/libavutil/time.c
@@ -96,3 +96,20 @@ int av_usleep(unsigned usec)
     return AVERROR(ENOSYS);
 #endif
 }
+
+size_t av_strftime_micro(char *buf, size_t size, const char *format, const struct timeval *tv)
+{
+  struct tm *tm;
+  char *temp_name = av_malloc(size);
+  if (!temp_name)
+    return 0;
+
+  if (!(tm = localtime(&(tv->tv_sec))))
+    return 0;
+
+  strftime(temp_name, size, format, tm);
+  size_t retval = snprintf(buf, size, temp_name, tv->tv_usec);
+
+  av_free(temp_name);
+  return retval;
+}
diff --git a/libavutil/time.h b/libavutil/time.h
index dc169b064a..baa9aacc73 100644
--- a/libavutil/time.h
+++ b/libavutil/time.h
@@ -21,6 +21,7 @@
 #ifndef AVUTIL_TIME_H
 #define AVUTIL_TIME_H
 
+#include "mem.h"
 #include <stdint.h>
 
 /**
@@ -53,4 +54,14 @@ int av_gettime_relative_is_monotonic(void);
  */
 int av_usleep(unsigned usec);
 
+/**
+ * Linux strftime function with micro second accuracy
+ * @param buf    char buffer to write output
+ * @param size   max number of bytes
+ * @param format format string, identical to the one for strftime
+ * @param tv     timeval struct containing current time
+ * @return number of bytes written
+ */
+size_t av_strftime_micro(char *buf, size_t size, const char *format, const struct timeval *tv);
+
 #endif /* AVUTIL_TIME_H */
-- 
2.30.1



More information about the ffmpeg-devel mailing list