movenchint.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /*
  2. * MOV, 3GP, MP4 muxer RTP hinting
  3. * Copyright (c) 2010 Martin Storsjo
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "movenc.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "internal.h"
  24. #include "rtpenc_chain.h"
  25. int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
  26. {
  27. MOVMuxContext *mov = s->priv_data;
  28. MOVTrack *track = &mov->tracks[index];
  29. MOVTrack *src_track = &mov->tracks[src_index];
  30. AVStream *src_st = s->streams[src_index];
  31. int ret = AVERROR(ENOMEM);
  32. track->tag = MKTAG('r','t','p',' ');
  33. track->src_track = src_index;
  34. track->enc = avcodec_alloc_context();
  35. if (!track->enc)
  36. goto fail;
  37. track->enc->codec_type = AVMEDIA_TYPE_DATA;
  38. track->enc->codec_tag = track->tag;
  39. track->rtp_ctx = ff_rtp_chain_mux_open(s, src_st, NULL,
  40. RTP_MAX_PACKET_SIZE);
  41. if (!track->rtp_ctx)
  42. goto fail;
  43. /* Copy the RTP AVStream timebase back to the hint AVStream */
  44. track->timescale = track->rtp_ctx->streams[0]->time_base.den;
  45. /* Mark the hinted track that packets written to it should be
  46. * sent to this track for hinting. */
  47. src_track->hint_track = index;
  48. return 0;
  49. fail:
  50. av_log(s, AV_LOG_WARNING,
  51. "Unable to initialize hinting of stream %d\n", src_index);
  52. av_freep(&track->enc);
  53. /* Set a default timescale, to avoid crashes in av_dump_format */
  54. track->timescale = 90000;
  55. return ret;
  56. }
  57. /**
  58. * Remove the first sample from the sample queue.
  59. */
  60. static void sample_queue_pop(HintSampleQueue *queue)
  61. {
  62. if (queue->len <= 0)
  63. return;
  64. if (queue->samples[0].own_data)
  65. av_free(queue->samples[0].data);
  66. queue->len--;
  67. memmove(queue->samples, queue->samples + 1, sizeof(HintSample)*queue->len);
  68. }
  69. /**
  70. * Empty the sample queue, releasing all memory.
  71. */
  72. static void sample_queue_free(HintSampleQueue *queue)
  73. {
  74. int i;
  75. for (i = 0; i < queue->len; i++)
  76. if (queue->samples[i].own_data)
  77. av_free(queue->samples[i].data);
  78. av_freep(&queue->samples);
  79. queue->len = 0;
  80. queue->size = 0;
  81. }
  82. /**
  83. * Add a reference to the sample data to the sample queue. The data is
  84. * not copied. sample_queue_retain should be called before pkt->data
  85. * is reused/freed.
  86. */
  87. static void sample_queue_push(HintSampleQueue *queue, AVPacket *pkt, int sample)
  88. {
  89. /* No need to keep track of smaller samples, since describing them
  90. * with immediates is more efficient. */
  91. if (pkt->size <= 14)
  92. return;
  93. if (!queue->samples || queue->len >= queue->size) {
  94. HintSample* samples;
  95. queue->size += 10;
  96. samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
  97. if (!samples)
  98. return;
  99. queue->samples = samples;
  100. }
  101. queue->samples[queue->len].data = pkt->data;
  102. queue->samples[queue->len].size = pkt->size;
  103. queue->samples[queue->len].sample_number = sample;
  104. queue->samples[queue->len].offset = 0;
  105. queue->samples[queue->len].own_data = 0;
  106. queue->len++;
  107. }
  108. /**
  109. * Make local copies of all referenced sample data in the queue.
  110. */
  111. static void sample_queue_retain(HintSampleQueue *queue)
  112. {
  113. int i;
  114. for (i = 0; i < queue->len; ) {
  115. HintSample *sample = &queue->samples[i];
  116. if (!sample->own_data) {
  117. uint8_t* ptr = av_malloc(sample->size);
  118. if (!ptr) {
  119. /* Unable to allocate memory for this one, remove it */
  120. memmove(queue->samples + i, queue->samples + i + 1,
  121. sizeof(HintSample)*(queue->len - i - 1));
  122. queue->len--;
  123. continue;
  124. }
  125. memcpy(ptr, sample->data, sample->size);
  126. sample->data = ptr;
  127. sample->own_data = 1;
  128. }
  129. i++;
  130. }
  131. }
  132. /**
  133. * Find matches of needle[n_pos ->] within haystack. If a sufficiently
  134. * large match is found, matching bytes before n_pos are included
  135. * in the match, too (within the limits of the arrays).
  136. *
  137. * @param haystack buffer that may contain parts of needle
  138. * @param h_len length of the haystack buffer
  139. * @param needle buffer containing source data that have been used to
  140. * construct haystack
  141. * @param n_pos start position in needle used for looking for matches
  142. * @param n_len length of the needle buffer
  143. * @param match_h_offset_ptr offset of the first matching byte within haystack
  144. * @param match_n_offset_ptr offset of the first matching byte within needle
  145. * @param match_len_ptr length of the matched segment
  146. * @return 0 if a match was found, < 0 if no match was found
  147. */
  148. static int match_segments(const uint8_t *haystack, int h_len,
  149. const uint8_t *needle, int n_pos, int n_len,
  150. int *match_h_offset_ptr, int *match_n_offset_ptr,
  151. int *match_len_ptr)
  152. {
  153. int h_pos;
  154. for (h_pos = 0; h_pos < h_len; h_pos++) {
  155. int match_len = 0;
  156. int match_h_pos, match_n_pos;
  157. /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
  158. while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
  159. needle[n_pos + match_len] == haystack[h_pos + match_len])
  160. match_len++;
  161. if (match_len <= 8)
  162. continue;
  163. /* If a sufficiently large match was found, try to expand
  164. * the matched segment backwards. */
  165. match_h_pos = h_pos;
  166. match_n_pos = n_pos;
  167. while (match_n_pos > 0 && match_h_pos > 0 &&
  168. needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
  169. match_n_pos--;
  170. match_h_pos--;
  171. match_len++;
  172. }
  173. if (match_len <= 14)
  174. continue;
  175. *match_h_offset_ptr = match_h_pos;
  176. *match_n_offset_ptr = match_n_pos;
  177. *match_len_ptr = match_len;
  178. return 0;
  179. }
  180. return -1;
  181. }
  182. /**
  183. * Look for segments in samples in the sample queue matching the data
  184. * in ptr. Samples not matching are removed from the queue. If a match
  185. * is found, the next time it will look for matches starting from the
  186. * end of the previous matched segment.
  187. *
  188. * @param data data to find matches for in the sample queue
  189. * @param len length of the data buffer
  190. * @param queue samples used for looking for matching segments
  191. * @param pos the offset in data of the matched segment
  192. * @param match_sample the number of the sample that contained the match
  193. * @param match_offset the offset of the matched segment within the sample
  194. * @param match_len the length of the matched segment
  195. * @return 0 if a match was found, < 0 if no match was found
  196. */
  197. static int find_sample_match(const uint8_t *data, int len,
  198. HintSampleQueue *queue, int *pos,
  199. int *match_sample, int *match_offset,
  200. int *match_len)
  201. {
  202. while (queue->len > 0) {
  203. HintSample *sample = &queue->samples[0];
  204. /* If looking for matches in a new sample, skip the first 5 bytes,
  205. * since they often may be modified/removed in the output packet. */
  206. if (sample->offset == 0 && sample->size > 5)
  207. sample->offset = 5;
  208. if (match_segments(data, len, sample->data, sample->offset,
  209. sample->size, pos, match_offset, match_len) == 0) {
  210. *match_sample = sample->sample_number;
  211. /* Next time, look for matches at this offset, with a little
  212. * margin to this match. */
  213. sample->offset = *match_offset + *match_len + 5;
  214. if (sample->offset + 10 >= sample->size)
  215. sample_queue_pop(queue); /* Not enough useful data left */
  216. return 0;
  217. }
  218. if (sample->offset < 10 && sample->size > 20) {
  219. /* No match found from the start of the sample,
  220. * try from the middle of the sample instead. */
  221. sample->offset = sample->size/2;
  222. } else {
  223. /* No match for this sample, remove it */
  224. sample_queue_pop(queue);
  225. }
  226. }
  227. return -1;
  228. }
  229. static void output_immediate(const uint8_t *data, int size,
  230. ByteIOContext *out, int *entries)
  231. {
  232. while (size > 0) {
  233. int len = size;
  234. if (len > 14)
  235. len = 14;
  236. put_byte(out, 1); /* immediate constructor */
  237. put_byte(out, len); /* amount of valid data */
  238. put_buffer(out, data, len);
  239. data += len;
  240. size -= len;
  241. for (; len < 14; len++)
  242. put_byte(out, 0);
  243. (*entries)++;
  244. }
  245. }
  246. static void output_match(ByteIOContext *out, int match_sample,
  247. int match_offset, int match_len, int *entries)
  248. {
  249. put_byte(out, 2); /* sample constructor */
  250. put_byte(out, 0); /* track reference */
  251. put_be16(out, match_len);
  252. put_be32(out, match_sample);
  253. put_be32(out, match_offset);
  254. put_be16(out, 1); /* bytes per block */
  255. put_be16(out, 1); /* samples per block */
  256. (*entries)++;
  257. }
  258. static void describe_payload(const uint8_t *data, int size,
  259. ByteIOContext *out, int *entries,
  260. HintSampleQueue *queue)
  261. {
  262. /* Describe the payload using different constructors */
  263. while (size > 0) {
  264. int match_sample, match_offset, match_len, pos;
  265. if (find_sample_match(data, size, queue, &pos, &match_sample,
  266. &match_offset, &match_len) < 0)
  267. break;
  268. output_immediate(data, pos, out, entries);
  269. data += pos;
  270. size -= pos;
  271. output_match(out, match_sample, match_offset, match_len, entries);
  272. data += match_len;
  273. size -= match_len;
  274. }
  275. output_immediate(data, size, out, entries);
  276. }
  277. /**
  278. * Write an RTP hint (that may contain one or more RTP packets)
  279. * for the packets in data. data contains one or more packets with a
  280. * BE32 size header.
  281. *
  282. * @param out buffer where the hints are written
  283. * @param data buffer containing RTP packets
  284. * @param size the size of the data buffer
  285. * @param trk the MOVTrack for the hint track
  286. * @param pts pointer where the timestamp for the written RTP hint is stored
  287. * @return the number of RTP packets in the written hint
  288. */
  289. static int write_hint_packets(ByteIOContext *out, const uint8_t *data,
  290. int size, MOVTrack *trk, int64_t *pts)
  291. {
  292. int64_t curpos;
  293. int64_t count_pos, entries_pos;
  294. int count = 0, entries;
  295. count_pos = url_ftell(out);
  296. /* RTPsample header */
  297. put_be16(out, 0); /* packet count */
  298. put_be16(out, 0); /* reserved */
  299. while (size > 4) {
  300. uint32_t packet_len = AV_RB32(data);
  301. uint16_t seq;
  302. uint32_t ts;
  303. data += 4;
  304. size -= 4;
  305. if (packet_len > size || packet_len <= 12)
  306. break;
  307. if (data[1] >= 200 && data[1] <= 204) {
  308. /* RTCP packet, just skip */
  309. data += packet_len;
  310. size -= packet_len;
  311. continue;
  312. }
  313. if (packet_len > trk->max_packet_size)
  314. trk->max_packet_size = packet_len;
  315. seq = AV_RB16(&data[2]);
  316. ts = AV_RB32(&data[4]);
  317. if (trk->prev_rtp_ts == 0)
  318. trk->prev_rtp_ts = ts;
  319. /* Unwrap the 32-bit RTP timestamp that wraps around often
  320. * into a not (as often) wrapping 64-bit timestamp. */
  321. trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
  322. trk->prev_rtp_ts = ts;
  323. if (*pts == AV_NOPTS_VALUE)
  324. *pts = trk->cur_rtp_ts_unwrapped;
  325. count++;
  326. /* RTPpacket header */
  327. put_be32(out, 0); /* relative_time */
  328. put_buffer(out, data, 2); /* RTP header */
  329. put_be16(out, seq); /* RTPsequenceseed */
  330. put_be16(out, 0); /* reserved + flags */
  331. entries_pos = url_ftell(out);
  332. put_be16(out, 0); /* entry count */
  333. data += 12;
  334. size -= 12;
  335. packet_len -= 12;
  336. entries = 0;
  337. /* Write one or more constructors describing the payload data */
  338. describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
  339. data += packet_len;
  340. size -= packet_len;
  341. curpos = url_ftell(out);
  342. url_fseek(out, entries_pos, SEEK_SET);
  343. put_be16(out, entries);
  344. url_fseek(out, curpos, SEEK_SET);
  345. }
  346. curpos = url_ftell(out);
  347. url_fseek(out, count_pos, SEEK_SET);
  348. put_be16(out, count);
  349. url_fseek(out, curpos, SEEK_SET);
  350. return count;
  351. }
  352. int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
  353. int track_index, int sample)
  354. {
  355. MOVMuxContext *mov = s->priv_data;
  356. MOVTrack *trk = &mov->tracks[track_index];
  357. AVFormatContext *rtp_ctx = trk->rtp_ctx;
  358. uint8_t *buf = NULL;
  359. int size;
  360. ByteIOContext *hintbuf = NULL;
  361. AVPacket hint_pkt;
  362. int ret = 0, count;
  363. if (!rtp_ctx)
  364. return AVERROR(ENOENT);
  365. if (!rtp_ctx->pb)
  366. return AVERROR(ENOMEM);
  367. sample_queue_push(&trk->sample_queue, pkt, sample);
  368. /* Feed the packet to the RTP muxer */
  369. ff_write_chained(rtp_ctx, 0, pkt, s);
  370. /* Fetch the output from the RTP muxer, open a new output buffer
  371. * for next time. */
  372. size = url_close_dyn_buf(rtp_ctx->pb, &buf);
  373. if ((ret = url_open_dyn_packet_buf(&rtp_ctx->pb,
  374. RTP_MAX_PACKET_SIZE)) < 0)
  375. goto done;
  376. if (size <= 0)
  377. goto done;
  378. /* Open a buffer for writing the hint */
  379. if ((ret = url_open_dyn_buf(&hintbuf)) < 0)
  380. goto done;
  381. av_init_packet(&hint_pkt);
  382. count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
  383. av_freep(&buf);
  384. /* Write the hint data into the hint track */
  385. hint_pkt.size = size = url_close_dyn_buf(hintbuf, &buf);
  386. hint_pkt.data = buf;
  387. hint_pkt.pts = hint_pkt.dts;
  388. hint_pkt.stream_index = track_index;
  389. if (pkt->flags & AV_PKT_FLAG_KEY)
  390. hint_pkt.flags |= AV_PKT_FLAG_KEY;
  391. if (count > 0)
  392. ff_mov_write_packet(s, &hint_pkt);
  393. done:
  394. av_free(buf);
  395. sample_queue_retain(&trk->sample_queue);
  396. return ret;
  397. }
  398. void ff_mov_close_hinting(MOVTrack *track) {
  399. AVFormatContext* rtp_ctx = track->rtp_ctx;
  400. uint8_t *ptr;
  401. av_freep(&track->enc);
  402. sample_queue_free(&track->sample_queue);
  403. if (!rtp_ctx)
  404. return;
  405. if (rtp_ctx->pb) {
  406. av_write_trailer(rtp_ctx);
  407. url_close_dyn_buf(rtp_ctx->pb, &ptr);
  408. av_free(ptr);
  409. }
  410. avformat_free_context(rtp_ctx);
  411. }